1use std::collections::HashSet;
4
5use crate::error::{binding, BindingResult};
6use crate::input::sealed::{self, AxisKind};
7use crate::{binding::ArraySource, data::AxisValues, AdapterError, 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 origin: Option<&'columns crate::data::DataSourceInfo>,
46}
47
48impl<'columns> ColumnProjection<'columns> {
49 pub fn new(
55 source_shape: (usize, usize),
56 columns: &'columns [(usize, &'columns dyn ArraySource)],
57 ) -> std::result::Result<Self, AdapterError> {
58 let projection = Self {
59 source_shape,
60 columns,
61 identities: None,
62 origin: None,
63 };
64 projection.validate()?;
65 Ok(projection)
66 }
67
68 pub fn from_identities(
78 source_shape: (usize, usize),
79 identities: &'columns [(usize, &'columns str)],
80 ) -> std::result::Result<Self, AdapterError> {
81 let projection = Self {
82 source_shape,
83 columns: &[],
84 identities: Some(identities),
85 origin: None,
86 };
87 projection.validate()?;
88 Ok(projection)
89 }
90
91 pub fn with_identities(
104 mut self,
105 identities: &'columns [(usize, &'columns str)],
106 ) -> std::result::Result<Self, AdapterError> {
107 self.validate_identities(identities)?;
108 self.identities = Some(identities);
109 Ok(self)
110 }
111
112 #[doc(hidden)]
114 pub fn with_origin(
115 mut self,
116 origin: &'columns crate::data::DataSourceInfo,
117 ) -> Result<Self, AdapterError> {
118 let rows = self.source_shape.0;
119 let indices = self
120 .columns
121 .iter()
122 .map(|(index, _)| *index)
123 .collect::<Vec<_>>();
124 let expected = if origin.selected_shape().len() == 1 && indices.len() == 1 {
125 vec![rows]
126 } else {
127 vec![rows, indices.len()]
128 };
129 if origin.source_shape() != [rows, self.source_shape.1]
130 || origin.selected_shape() != expected
131 || origin
132 .selected_indices()
133 .is_some_and(|selected| selected != indices)
134 {
135 return Err(binding(
136 "column projection",
137 "captured source selection does not match the projection",
138 ));
139 }
140 self.origin = Some(origin);
141 Ok(self)
142 }
143
144 fn validate_identities(&self, identities: &[(usize, &str)]) -> BindingResult<()> {
145 let mut indices = HashSet::new();
146 let mut names = HashSet::new();
147 indices
148 .try_reserve(identities.len())
149 .map_err(|source| AdapterError::Allocation {
150 operation: "column identities",
151 source,
152 })?;
153 names
154 .try_reserve(identities.len())
155 .map_err(|source| AdapterError::Allocation {
156 operation: "column identities",
157 source,
158 })?;
159 for &(index, identity) in identities {
160 crate::source::lookup(Some(self), index, "column identities")?;
161 if !indices.insert(index) {
162 return Err(binding(
163 "column identities",
164 format!("duplicate logical column {index}"),
165 ));
166 }
167 if !names.insert(identity) {
168 return Err(binding(
169 "column identities",
170 format!("duplicate raw identity {identity:?}"),
171 ));
172 }
173 }
174 for &(index, _) in self.columns {
175 if !indices.contains(&index) {
176 return Err(binding(
177 "column identities",
178 format!("no raw identity supplied for logical column {index}"),
179 ));
180 }
181 }
182 Ok(())
183 }
184
185 fn column(&self, index: usize, role: &'static str) -> BindingResult<&dyn ArraySource> {
186 crate::source::lookup(Some(self), index, role)?;
187 self.columns
188 .iter()
189 .find(|(column, _)| *column == index)
190 .map(|(_, source)| *source)
191 .ok_or_else(|| binding(role, format!("logical column {index} was not projected")))
192 }
193}
194
195fn original_column(error: AdapterError, index: usize) -> AdapterError {
196 match error {
197 AdapterError::UnsupportedElement { role, element, .. } => {
198 AdapterError::UnsupportedElement {
199 role,
200 element,
201 column: Some(index),
202 }
203 }
204 AdapterError::SourceRow { slot, value, .. } => AdapterError::SourceRow {
205 slot,
206 value,
207 column: Some(index),
208 },
209 other => other,
210 }
211}
212
213impl sealed::Sealed for ColumnProjection<'_> {
214 fn binding_origin(&self) -> Option<&crate::data::DataSourceInfo> {
215 self.origin
216 }
217
218 fn column_identities(&self) -> Option<&[(usize, &str)]> {
219 self.identities
220 }
221
222 fn axis_kind(&self, index: usize, role: &'static str) -> BindingResult<AxisKind> {
223 sealed::Sealed::axis_kind(self.column(index, role)?, 0, role)
224 .map_err(|error| original_column(error, index))
225 }
226}
227
228macro_rules! projected_column {
229 ($method:ident, $ty:ty) => {
230 fn $method(&self, index: usize, role: &'static str) -> BindingResult<Vec<$ty>> {
231 self.column(index, role)?
232 .$method(0, role)
233 .map_err(|error| original_column(error, index))
234 }
235 };
236}
237
238impl ArraySource for ColumnProjection<'_> {
239 fn validate(&self) -> BindingResult<()> {
240 if self.columns.is_empty() && self.identities.is_none() {
241 return Err(binding(
242 "column projection",
243 "supply at least one value column",
244 ));
245 }
246 let mut indices = HashSet::new();
247 indices
248 .try_reserve(self.columns.len())
249 .map_err(|source| AdapterError::Allocation {
250 operation: "column projection",
251 source,
252 })?;
253 for &(index, source) in self.columns {
254 crate::source::lookup(Some(self), index, "column projection")?;
255 if !indices.insert(index) {
256 return Err(binding(
257 "column projection",
258 format!("duplicate logical column {index}"),
259 ));
260 }
261 source.validate()?;
262 let actual = source.shape();
263 if actual != (self.source_shape.0, 1) {
264 return Err(AdapterError::Shape {
265 operation: "column projection",
266 expected: vec![self.source_shape.0, 1],
267 actual: vec![actual.0, actual.1],
268 });
269 }
270 }
271 if let Some(identities) = self.identities {
272 self.validate_identities(identities)?;
273 }
274 Ok(())
275 }
276
277 fn shape(&self) -> (usize, usize) {
278 self.source_shape
279 }
280
281 projected_column!(numeric_column, Option<f64>);
282 projected_column!(category_column, Option<String>);
283 projected_column!(boolean_column, Option<bool>);
284 projected_column!(id_column, usize);
285
286 fn axis_column(&self, index: usize, role: &'static str) -> BindingResult<AxisValues> {
287 match sealed::Sealed::axis_kind(self, index, role)? {
288 AxisKind::Numeric => {
289 let values = self.numeric_column(index, role)?;
290 Ok(AxisValues::Numeric(NumericValues::nullable(
291 crate::source::identity(Some(self), index, role)?,
292 values,
293 )))
294 }
295 AxisKind::Category => {
296 let values = self.category_column(index, role)?;
297 Ok(AxisValues::Category(CategoryValues::nullable(
298 crate::source::identity(Some(self), index, role)?,
299 values,
300 )?))
301 }
302 }
303 }
304}
305
306impl sealed::Sealed for &ColumnProjection<'_> {
307 fn binding_origin(&self) -> Option<&crate::data::DataSourceInfo> {
308 self.origin
309 }
310}
311
312impl crate::binding::ColumnsInput for &ColumnProjection<'_> {
313 fn local_identities(&self) -> bool {
314 self.origin
315 .is_some_and(|origin| origin.selector().is_none())
316 }
317
318 fn bind_columns(self, _: Option<&dyn ArraySource>) -> BindingResult<crate::input::Columns> {
319 let indices = self
320 .columns
321 .iter()
322 .map(|(index, _)| *index)
323 .collect::<Vec<_>>();
324 crate::input::selected(Some(self), &indices)
325 }
326}
327
328impl crate::binding::NumericSeriesInput for &ColumnProjection<'_> {
329 fn bind_series(
330 self,
331 source: Option<&dyn ArraySource>,
332 role: &'static str,
333 ) -> BindingResult<crate::input::SeriesBinding> {
334 use crate::binding::ColumnsInput;
335 let local = self.local_identities();
336 crate::input::multiple(self.bind_columns(source)?, local, role)
337 }
338}