1use std::collections::HashSet;
4
5use crate::error::{binding, BindingResult};
6use crate::input::sealed::{self, AxisKind};
7use crate::{AdapterError, ArraySource, AxisValues, CategoryValues, NumericValues};
8
9pub struct ColumnProjection<'columns> {
42 source_shape: (usize, usize),
43 columns: &'columns [(usize, &'columns dyn ArraySource)],
44 identities: Option<&'columns [(usize, &'columns str)]>,
45}
46
47impl<'columns> ColumnProjection<'columns> {
48 pub fn new(
54 source_shape: (usize, usize),
55 columns: &'columns [(usize, &'columns dyn ArraySource)],
56 ) -> std::result::Result<Self, AdapterError> {
57 let projection = Self {
58 source_shape,
59 columns,
60 identities: None,
61 };
62 projection.validate()?;
63 Ok(projection)
64 }
65
66 pub fn from_identities(
76 source_shape: (usize, usize),
77 identities: &'columns [(usize, &'columns str)],
78 ) -> std::result::Result<Self, AdapterError> {
79 let projection = Self {
80 source_shape,
81 columns: &[],
82 identities: Some(identities),
83 };
84 projection.validate()?;
85 Ok(projection)
86 }
87
88 pub fn with_identities(
101 mut self,
102 identities: &'columns [(usize, &'columns str)],
103 ) -> std::result::Result<Self, AdapterError> {
104 self.validate_identities(identities)?;
105 self.identities = Some(identities);
106 Ok(self)
107 }
108
109 fn validate_identities(&self, identities: &[(usize, &str)]) -> BindingResult<()> {
110 let mut indices = HashSet::new();
111 let mut names = HashSet::new();
112 indices
113 .try_reserve(identities.len())
114 .map_err(|source| AdapterError::Allocation {
115 operation: "column identities",
116 source,
117 })?;
118 names
119 .try_reserve(identities.len())
120 .map_err(|source| AdapterError::Allocation {
121 operation: "column identities",
122 source,
123 })?;
124 for &(index, identity) in identities {
125 crate::source::lookup(Some(self), index, "column identities")?;
126 if !indices.insert(index) {
127 return Err(binding(
128 "column identities",
129 format!("duplicate logical column {index}"),
130 ));
131 }
132 if !names.insert(identity) {
133 return Err(binding(
134 "column identities",
135 format!("duplicate raw identity {identity:?}"),
136 ));
137 }
138 }
139 for &(index, _) in self.columns {
140 if !indices.contains(&index) {
141 return Err(binding(
142 "column identities",
143 format!("no raw identity supplied for logical column {index}"),
144 ));
145 }
146 }
147 Ok(())
148 }
149
150 fn column(&self, index: usize, role: &'static str) -> BindingResult<&dyn ArraySource> {
151 crate::source::lookup(Some(self), index, role)?;
152 self.columns
153 .iter()
154 .find(|(column, _)| *column == index)
155 .map(|(_, source)| *source)
156 .ok_or_else(|| binding(role, format!("logical column {index} was not projected")))
157 }
158}
159
160fn original_column(error: AdapterError, index: usize) -> AdapterError {
161 match error {
162 AdapterError::UnsupportedElement { role, element, .. } => {
163 AdapterError::UnsupportedElement {
164 role,
165 element,
166 column: Some(index),
167 }
168 }
169 AdapterError::SourceRow { slot, value, .. } => AdapterError::SourceRow {
170 slot,
171 value,
172 column: Some(index),
173 },
174 other => other,
175 }
176}
177
178impl sealed::Sealed for ColumnProjection<'_> {
179 fn column_identities(&self) -> Option<&[(usize, &str)]> {
180 self.identities
181 }
182
183 fn axis_kind(&self, index: usize, role: &'static str) -> BindingResult<AxisKind> {
184 sealed::Sealed::axis_kind(self.column(index, role)?, 0, role)
185 .map_err(|error| original_column(error, index))
186 }
187}
188
189macro_rules! projected_column {
190 ($method:ident, $ty:ty) => {
191 fn $method(&self, index: usize, role: &'static str) -> BindingResult<Vec<$ty>> {
192 self.column(index, role)?
193 .$method(0, role)
194 .map_err(|error| original_column(error, index))
195 }
196 };
197}
198
199impl ArraySource for ColumnProjection<'_> {
200 fn validate(&self) -> BindingResult<()> {
201 if self.columns.is_empty() && self.identities.is_none() {
202 return Err(binding(
203 "column projection",
204 "supply at least one value column",
205 ));
206 }
207 let mut indices = HashSet::new();
208 indices
209 .try_reserve(self.columns.len())
210 .map_err(|source| AdapterError::Allocation {
211 operation: "column projection",
212 source,
213 })?;
214 for &(index, source) in self.columns {
215 crate::source::lookup(Some(self), index, "column projection")?;
216 if !indices.insert(index) {
217 return Err(binding(
218 "column projection",
219 format!("duplicate logical column {index}"),
220 ));
221 }
222 source.validate()?;
223 let actual = source.shape();
224 if actual != (self.source_shape.0, 1) {
225 return Err(AdapterError::Shape {
226 operation: "column projection",
227 expected: vec![self.source_shape.0, 1],
228 actual: vec![actual.0, actual.1],
229 });
230 }
231 }
232 if let Some(identities) = self.identities {
233 self.validate_identities(identities)?;
234 }
235 Ok(())
236 }
237
238 fn shape(&self) -> (usize, usize) {
239 self.source_shape
240 }
241
242 projected_column!(numeric_column, Option<f64>);
243 projected_column!(category_column, Option<String>);
244 projected_column!(boolean_column, Option<bool>);
245 projected_column!(id_column, usize);
246 projected_column!(byte_column, u8);
247
248 fn axis_column(&self, index: usize, role: &'static str) -> BindingResult<AxisValues> {
249 match sealed::Sealed::axis_kind(self, index, role)? {
250 AxisKind::Numeric => {
251 let values = self.numeric_column(index, role)?;
252 Ok(AxisValues::Numeric(NumericValues::nullable(
253 crate::source::identity(Some(self), index, role)?,
254 values,
255 )))
256 }
257 AxisKind::Category => {
258 let values = self.category_column(index, role)?;
259 Ok(AxisValues::Category(CategoryValues::nullable(
260 crate::source::identity(Some(self), index, role)?,
261 values,
262 )?))
263 }
264 }
265 }
266}