Skip to main content

lichtung_plot_ndarray/
input.rs

1//! Sealed role protocols distinguish integer selectors, vectors, matrices and masks.
2use std::collections::HashSet;
3use std::ops::RangeFull;
4
5use ndarray::{ArrayView, ArrayView1, ArrayView2, Dimension, Ix1, Ix2};
6
7use crate::error::{binding, length, unsupported, BindingResult};
8use crate::{
9    binding::{ArrayElement, ArraySource},
10    data::{AxisValues, SourceRows},
11    BooleanValues, CategoryValues, NumericValues,
12};
13
14pub(crate) mod sealed {
15    pub enum AxisKind {
16        Numeric,
17        Category,
18    }
19
20    pub trait Sealed {
21        fn selected_index(&self) -> Option<usize> {
22            None
23        }
24        fn all_columns(&self) -> bool {
25            false
26        }
27        fn numeric_only(&self) -> bool {
28            false
29        }
30        fn native_slots(&self) -> bool {
31            false
32        }
33        fn cell_shape(&self) -> Option<(usize, usize)> {
34            None
35        }
36        fn selected_columns(&self) -> Option<&[usize]> {
37            None
38        }
39        fn binding_origin(&self) -> Option<&crate::data::DataSourceInfo> {
40            None
41        }
42        fn column_identities(&self) -> Option<&[(usize, &str)]> {
43            None
44        }
45        fn axis_kind(&self, _: usize, role: &'static str) -> super::BindingResult<AxisKind> {
46            Err(super::binding(
47                role,
48                "this input is not an array axis source",
49            ))
50        }
51    }
52}
53fn axis_kind<T: ArrayElement>(index: usize, role: &'static str) -> BindingResult<sealed::AxisKind> {
54    if T::NUMERIC {
55        Ok(sealed::AxisKind::Numeric)
56    } else if T::CATEGORY {
57        Ok(sealed::AxisKind::Category)
58    } else {
59        Err(crate::error::unsupported_column::<T>(role, index))
60    }
61}
62impl sealed::Sealed for usize {
63    fn selected_index(&self) -> Option<usize> {
64        Some(*self)
65    }
66}
67impl sealed::Sealed for RangeFull {
68    fn all_columns(&self) -> bool {
69        true
70    }
71}
72impl<T> sealed::Sealed for ArrayView1<'_, T> {}
73impl<T: ArrayElement> sealed::Sealed for ArrayView2<'_, T> {
74    fn cell_shape(&self) -> Option<(usize, usize)> {
75        Some(self.dim())
76    }
77    fn axis_kind(&self, index: usize, role: &'static str) -> BindingResult<sealed::AxisKind> {
78        axis_kind::<T>(index, role)
79    }
80}
81impl<T> sealed::Sealed for (ArrayView1<'_, T>, ArrayView1<'_, bool>) {}
82impl<T: ArrayElement> sealed::Sealed for (ArrayView2<'_, T>, ArrayView2<'_, bool>) {
83    fn cell_shape(&self) -> Option<(usize, usize)> {
84        Some(self.0.dim())
85    }
86    fn axis_kind(&self, index: usize, role: &'static str) -> BindingResult<sealed::AxisKind> {
87        axis_kind::<T>(index, role)
88    }
89}
90macro_rules! native {
91    ($($ty:ty),+) => {$ (impl sealed::Sealed for $ty { fn native_slots(&self) -> bool { true } })+};
92}
93native!(
94    NumericValues,
95    CategoryValues,
96    BooleanValues,
97    SourceRows,
98    AxisValues
99);
100
101impl sealed::Sealed for crate::Color {}
102
103/// Bind a fixed complete Color or a numeric color variable for a native plot.
104pub trait ColorSourceInput: sealed::Sealed {
105    #[doc(hidden)]
106    fn bind_color_source(
107        self,
108        source: Option<&dyn ArraySource>,
109        expected: usize,
110        reference: Option<&crate::data::DataSourceRef>,
111    ) -> BindingResult<crate::scales::ColorSource>;
112}
113
114impl<T: NumericInput> ColorSourceInput for T {
115    fn bind_color_source(
116        self,
117        source: Option<&dyn ArraySource>,
118        expected: usize,
119        reference: Option<&crate::data::DataSourceRef>,
120    ) -> BindingResult<crate::scales::ColorSource> {
121        let capture = crate::capture::Capture::existing(source, reference);
122        let values = capture.bind(self, 1, |input, source| input.bind_numeric(source, "color"))?;
123        crate::error::length("color", values.name(), expected, values.len())?;
124        Ok(values.into())
125    }
126}
127
128impl ColorSourceInput for crate::Color {
129    fn bind_color_source(
130        self,
131        _: Option<&dyn ArraySource>,
132        _: usize,
133        _: Option<&crate::data::DataSourceRef>,
134    ) -> BindingResult<crate::scales::ColorSource> {
135        Ok(self.into())
136    }
137}
138impl sealed::Sealed for crate::scales::ColorSource {}
139impl ColorSourceInput for crate::scales::ColorSource {
140    fn bind_color_source(
141        self,
142        _: Option<&dyn ArraySource>,
143        expected: usize,
144        _: Option<&crate::data::DataSourceRef>,
145    ) -> BindingResult<crate::scales::ColorSource> {
146        match &self {
147            crate::scales::ColorSource::Numeric(values) => {
148                crate::error::length("color", values.name(), expected, values.len())?;
149            }
150            crate::scales::ColorSource::Fixed(_) => {}
151            _ => return Err(binding("color", "unsupported native color source")),
152        }
153        Ok(self)
154    }
155}
156
157type Raw<T> = (String, Vec<Option<T>>);
158
159pub(crate) fn repeat<T: Clone>(
160    values: Vec<Option<T>>,
161    copies: usize,
162    role: &'static str,
163) -> BindingResult<Vec<Option<T>>> {
164    let len = values
165        .len()
166        .checked_mul(copies)
167        .ok_or_else(|| binding(role, "expanded slot count exceeds usize"))?;
168    let mut expanded = crate::snapshot::allocate(len, role)?;
169    expanded.extend(
170        values
171            .into_iter()
172            .flat_map(|value| std::iter::repeat_n(value, copies)),
173    );
174    Ok(expanded)
175}
176
177macro_rules! role_input {
178    ($trait:ident, $bind:ident, $raw:ident, $repeated:ident, $ty:ty, $native:ident, $bound:path, $supported:ident, $convert:expr, $column:ident, $construct:expr) => {
179        #[doc = concat!("Sealed ", stringify!($trait), " role: logical column index, foreign vector, validity pair or native values.")]
180        pub trait $trait: sealed::Sealed + Sized {
181            #[doc(hidden)] fn $raw(self, source: Option<&dyn ArraySource>, role: &'static str) -> BindingResult<Raw<$ty>>;
182            #[doc(hidden)] fn $bind(self, source: Option<&dyn ArraySource>, role: &'static str) -> BindingResult<$native> {
183                let (name, values) = self.$raw(source, role)?;
184                ($construct)(name, values)
185            }
186            #[doc(hidden)] fn $repeated(self, source: Option<&dyn ArraySource>, role: &'static str, copies: usize) -> BindingResult<$native> {
187                let (name, values) = self.$raw(source, role)?;
188                ($construct)(name, repeat(values, copies, role)?)
189            }
190        }
191        impl $trait for usize {
192            fn $raw(self, source: Option<&dyn ArraySource>, role: &'static str) -> BindingResult<Raw<$ty>> {
193                let source = crate::source::lookup(source, self, role)?;
194                let values = source.$column(self, role)?;
195                Ok((crate::source::identity(Some(source), self, role)?, values))
196            }
197        }
198        impl<T: ArrayElement + $bound> $trait for ArrayView1<'_, T> {
199            fn $raw(self, _: Option<&dyn ArraySource>, role: &'static str) -> BindingResult<Raw<$ty>> {
200                if !T::$supported { return Err(unsupported::<T>(role)); }
201                Ok((role.into(), crate::snapshot::values(self, None, $convert, role)?))
202            }
203        }
204        impl<T: ArrayElement + $bound> $trait for (ArrayView1<'_, T>, ArrayView1<'_, bool>) {
205            fn $raw(self, _: Option<&dyn ArraySource>, role: &'static str) -> BindingResult<Raw<$ty>> {
206                if !T::$supported { return Err(unsupported::<T>(role)); }
207                Ok((role.into(), crate::snapshot::values(self.0, Some(self.1), $convert, role)?))
208            }
209        }
210        impl $trait for $native {
211            fn $raw(self, _: Option<&dyn ArraySource>, role: &'static str) -> BindingResult<Raw<$ty>> { Err(binding(role, "use a foreign variable in this mapping role")) }
212            fn $bind(self, _: Option<&dyn ArraySource>, _: &'static str) -> BindingResult<$native> { Ok(self) }
213            fn $repeated(self, _: Option<&dyn ArraySource>, _: &'static str, _: usize) -> BindingResult<$native> { Ok(self) }
214        }
215    };
216}
217role_input!(
218    NumericInput,
219    bind_numeric,
220    raw_numeric,
221    bind_numeric_repeated,
222    f64,
223    NumericValues,
224    crate::binding::NumericElement,
225    NUMERIC,
226    ArrayElement::numeric,
227    numeric_column,
228    |name, values| Ok(NumericValues::nullable(name, values))
229);
230role_input!(
231    CategoryInput,
232    bind_category,
233    raw_category,
234    bind_category_repeated,
235    String,
236    CategoryValues,
237    crate::binding::CategoryElement,
238    CATEGORY,
239    |value| value.category().map(str::to_owned),
240    category_column,
241    |name, values| Ok(CategoryValues::nullable(name, values)?)
242);
243role_input!(
244    BooleanInput,
245    bind_boolean,
246    raw_boolean,
247    bind_boolean_repeated,
248    bool,
249    BooleanValues,
250    crate::binding::BooleanElement,
251    BOOLEAN,
252    ArrayElement::boolean,
253    boolean_column,
254    |name, values| Ok(BooleanValues::nullable(name, values))
255);
256
257/// Exact source IDs: integer vectors, same-shape cell grids or native IDs.
258pub trait SourceRowsInput: sealed::Sealed + Sized {
259    #[doc(hidden)]
260    fn raw_source_rows(
261        self,
262        _: Option<&dyn ArraySource>,
263        role: &'static str,
264    ) -> BindingResult<Vec<usize>> {
265        Err(binding(
266            role,
267            "use an integer foreign variable for a generated-column selector",
268        ))
269    }
270    #[doc(hidden)]
271    fn bind_source_rows(
272        self,
273        source: Option<&dyn ArraySource>,
274        role: &'static str,
275    ) -> BindingResult<SourceRows>;
276    #[doc(hidden)]
277    fn bind_source_rows_repeated(
278        self,
279        source: Option<&dyn ArraySource>,
280        role: &'static str,
281        copies: usize,
282    ) -> BindingResult<SourceRows> {
283        if copies != 1
284            && !self.native_slots()
285            && self.cell_shape().is_none()
286            && self.selected_columns().is_none()
287        {
288            return Err(binding(
289                role,
290                "provide unique per-cell IDs, not repeated row IDs",
291            ));
292        }
293        self.bind_source_rows(source, role)
294    }
295}
296impl SourceRowsInput for SourceRows {
297    fn bind_source_rows(
298        self,
299        _: Option<&dyn ArraySource>,
300        _: &'static str,
301    ) -> BindingResult<SourceRows> {
302        Ok(self)
303    }
304}
305impl SourceRowsInput for usize {
306    fn raw_source_rows(
307        self,
308        source: Option<&dyn ArraySource>,
309        role: &'static str,
310    ) -> BindingResult<Vec<usize>> {
311        crate::source::lookup(source, self, role)?.id_column(self, role)
312    }
313    fn bind_source_rows(
314        self,
315        source: Option<&dyn ArraySource>,
316        role: &'static str,
317    ) -> BindingResult<SourceRows> {
318        Ok(SourceRows::new(
319            crate::source::lookup(source, self, role)?.id_column(self, role)?,
320        )?)
321    }
322}
323
324pub(crate) fn ids<T: ArrayElement, D: Dimension>(
325    values: ArrayView<'_, T, D>,
326    present: Option<ArrayView<'_, bool, D>>,
327    role: &'static str,
328) -> BindingResult<Vec<usize>> {
329    if !T::ID {
330        return Err(unsupported::<T>(role));
331    }
332    let converted = crate::snapshot::values(values.view(), present, ArrayElement::id, role)?;
333    let mut result = crate::snapshot::allocate(values.len(), role)?;
334    for (slot, (value, id)) in values.iter().zip(converted).enumerate() {
335        result.push(id.ok_or_else(|| crate::AdapterError::SourceRow {
336            slot,
337            value: format!("{value:?}"),
338            column: None,
339        })?);
340    }
341    Ok(result)
342}
343macro_rules! source_ids {
344    ($dim:ty) => {
345        impl<T: ArrayElement> SourceRowsInput for ArrayView<'_, T, $dim> {
346            fn raw_source_rows(
347                self,
348                _: Option<&dyn ArraySource>,
349                role: &'static str,
350            ) -> BindingResult<Vec<usize>> {
351                ids(self, None, role)
352            }
353            fn bind_source_rows(
354                self,
355                _: Option<&dyn ArraySource>,
356                role: &'static str,
357            ) -> BindingResult<SourceRows> {
358                Ok(SourceRows::new(ids(self, None, role)?)?)
359            }
360        }
361        impl<T: ArrayElement> SourceRowsInput
362            for (ArrayView<'_, T, $dim>, ArrayView<'_, bool, $dim>)
363        {
364            fn raw_source_rows(
365                self,
366                _: Option<&dyn ArraySource>,
367                role: &'static str,
368            ) -> BindingResult<Vec<usize>> {
369                ids(self.0, Some(self.1), role)
370            }
371            fn bind_source_rows(
372                self,
373                _: Option<&dyn ArraySource>,
374                role: &'static str,
375            ) -> BindingResult<SourceRows> {
376                Ok(SourceRows::new(ids(self.0, Some(self.1), role)?)?)
377            }
378        }
379    };
380}
381source_ids!(Ix1);
382source_ids!(Ix2);
383impl<T: ArrayElement> BooleanInput for ArrayView2<'_, T> {
384    fn raw_boolean(
385        self,
386        _: Option<&dyn ArraySource>,
387        role: &'static str,
388    ) -> BindingResult<Raw<bool>> {
389        if !T::BOOLEAN {
390            return Err(unsupported::<T>(role));
391        }
392        Ok((
393            role.into(),
394            crate::snapshot::values(self, None, ArrayElement::boolean, role)?,
395        ))
396    }
397}
398impl<T: ArrayElement> BooleanInput for (ArrayView2<'_, T>, ArrayView2<'_, bool>) {
399    fn raw_boolean(
400        self,
401        _: Option<&dyn ArraySource>,
402        role: &'static str,
403    ) -> BindingResult<Raw<bool>> {
404        if !T::BOOLEAN {
405            return Err(unsupported::<T>(role));
406        }
407        Ok((
408            role.into(),
409            crate::snapshot::values(self.0, Some(self.1), ArrayElement::boolean, role)?,
410        ))
411    }
412}
413
414/// Numeric or categorical trajectory x; Boolean input is never a numeric coordinate.
415pub trait AxisInput: sealed::Sealed {
416    #[doc(hidden)]
417    fn bind_axis(
418        self,
419        source: Option<&dyn ArraySource>,
420        role: &'static str,
421    ) -> BindingResult<AxisValues>;
422}
423impl AxisInput for usize {
424    fn bind_axis(
425        self,
426        source: Option<&dyn ArraySource>,
427        role: &'static str,
428    ) -> BindingResult<AxisValues> {
429        crate::source::lookup(source, self, role)?.axis_column(self, role)
430    }
431}
432fn axis<T: ArrayElement>(
433    values: ArrayView1<'_, T>,
434    present: Option<ArrayView1<'_, bool>>,
435    role: &'static str,
436) -> BindingResult<AxisValues> {
437    if T::NUMERIC {
438        Ok(AxisValues::Numeric(NumericValues::nullable(
439            role,
440            crate::snapshot::values(values, present, ArrayElement::numeric, role)?,
441        )))
442    } else if T::CATEGORY {
443        Ok(AxisValues::Category(CategoryValues::nullable(
444            role,
445            crate::snapshot::values(
446                values,
447                present,
448                |value| value.category().map(str::to_owned),
449                role,
450            )?,
451        )?))
452    } else {
453        Err(unsupported::<T>(role))
454    }
455}
456impl<T: ArrayElement> AxisInput for ArrayView1<'_, T> {
457    fn bind_axis(
458        self,
459        _: Option<&dyn ArraySource>,
460        role: &'static str,
461    ) -> BindingResult<AxisValues> {
462        axis(self, None, role)
463    }
464}
465impl<T: ArrayElement> AxisInput for (ArrayView1<'_, T>, ArrayView1<'_, bool>) {
466    fn bind_axis(
467        self,
468        _: Option<&dyn ArraySource>,
469        role: &'static str,
470    ) -> BindingResult<AxisValues> {
471        axis(self.0, Some(self.1), role)
472    }
473}
474impl AxisInput for AxisValues {
475    fn bind_axis(self, _: Option<&dyn ArraySource>, _: &'static str) -> BindingResult<AxisValues> {
476        Ok(self)
477    }
478}
479impl AxisInput for NumericValues {
480    fn bind_axis(self, _: Option<&dyn ArraySource>, _: &'static str) -> BindingResult<AxisValues> {
481        Ok(AxisValues::Numeric(self))
482    }
483}
484impl AxisInput for CategoryValues {
485    fn bind_axis(self, _: Option<&dyn ArraySource>, _: &'static str) -> BindingResult<AxisValues> {
486        Ok(AxisValues::Category(self))
487    }
488}
489
490pub(crate) type Columns = (usize, Vec<(usize, Vec<Option<f64>>)>);
491pub(crate) type SeriesBinding = (NumericValues, Option<(usize, Vec<usize>, bool)>);
492
493/// Ordered logical source columns, `..`, or a direct matrix/validity pair.
494pub trait ColumnsInput: sealed::Sealed {
495    #[doc(hidden)]
496    fn local_identities(&self) -> bool {
497        false
498    }
499    #[doc(hidden)]
500    fn bind_columns(self, source: Option<&dyn ArraySource>) -> BindingResult<Columns>;
501}
502pub(crate) fn selected(
503    source: Option<&dyn ArraySource>,
504    indices: &[usize],
505) -> BindingResult<Columns> {
506    if indices.is_empty() {
507        return Err(binding("selected columns", "select at least one variable"));
508    }
509    let mut seen = HashSet::new();
510    let mut columns = crate::snapshot::allocate(indices.len(), "selected columns")?;
511    seen.try_reserve(indices.len())
512        .map_err(|source| crate::AdapterError::Allocation {
513            operation: "selection identities",
514            source,
515        })?;
516    let mut rows = 0;
517    for &index in indices {
518        if !seen.insert(index) {
519            return Err(binding(
520                "selected columns",
521                format!("duplicate column {index}"),
522            ));
523        }
524        let source = crate::source::lookup(source, index, "selected columns")?;
525        rows = source.shape().0;
526        columns.push((index, source.numeric_column(index, "selected columns")?));
527    }
528    Ok((rows, columns))
529}
530impl sealed::Sealed for &[usize] {
531    fn selected_columns(&self) -> Option<&[usize]> {
532        Some(self)
533    }
534}
535impl<const N: usize> sealed::Sealed for [usize; N] {
536    fn selected_columns(&self) -> Option<&[usize]> {
537        Some(self)
538    }
539}
540impl ColumnsInput for &[usize] {
541    fn bind_columns(self, source: Option<&dyn ArraySource>) -> BindingResult<Columns> {
542        selected(source, self)
543    }
544}
545impl<const N: usize> ColumnsInput for [usize; N] {
546    fn bind_columns(self, source: Option<&dyn ArraySource>) -> BindingResult<Columns> {
547        selected(source, &self)
548    }
549}
550impl ColumnsInput for RangeFull {
551    fn bind_columns(self, source: Option<&dyn ArraySource>) -> BindingResult<Columns> {
552        let source = source
553            .ok_or_else(|| binding("selected columns", "all columns require an array source"))?;
554        let mut indices = crate::snapshot::allocate(source.shape().1, "selected columns")?;
555        indices.extend(0..source.shape().1);
556        selected(Some(source), &indices)
557    }
558}
559pub(crate) struct NumericColumns;
560
561impl sealed::Sealed for NumericColumns {
562    fn numeric_only(&self) -> bool {
563        true
564    }
565}
566
567impl ColumnsInput for NumericColumns {
568    fn bind_columns(self, source: Option<&dyn ArraySource>) -> BindingResult<Columns> {
569        (..).bind_columns(source)
570    }
571}
572
573impl<T: ArrayElement> ColumnsInput for ArrayView2<'_, T> {
574    fn local_identities(&self) -> bool {
575        true
576    }
577    fn bind_columns(self, _: Option<&dyn ArraySource>) -> BindingResult<Columns> {
578        (..).bind_columns(Some(&self))
579    }
580}
581impl<T: ArrayElement> ColumnsInput for (ArrayView2<'_, T>, ArrayView2<'_, bool>) {
582    fn local_identities(&self) -> bool {
583        true
584    }
585    fn bind_columns(self, _: Option<&dyn ArraySource>) -> BindingResult<Columns> {
586        (..).bind_columns(Some(&self))
587    }
588}
589
590pub(crate) fn multiple(
591    (rows, columns): Columns,
592    local: bool,
593    role: &'static str,
594) -> BindingResult<SeriesBinding> {
595    let cells = rows
596        .checked_mul(columns.len())
597        .ok_or_else(|| binding(role, "expanded slot count exceeds usize"))?;
598    let mut values = crate::snapshot::allocate(cells, role)?;
599    for row in 0..rows {
600        for (_, column) in &columns {
601            length(role, role, rows, column.len())?;
602            values.push(column[row]);
603        }
604    }
605    Ok((
606        NumericValues::nullable(role, values),
607        Some((
608            rows,
609            columns.into_iter().map(|(index, _)| index).collect(),
610            local,
611        )),
612    ))
613}
614/// One numeric variable or explicit logical-column/matrix expansion.
615pub trait NumericSeriesInput: sealed::Sealed {
616    #[doc(hidden)]
617    fn bind_series(
618        self,
619        source: Option<&dyn ArraySource>,
620        role: &'static str,
621    ) -> BindingResult<SeriesBinding>;
622}
623impl NumericSeriesInput for usize {
624    fn bind_series(
625        self,
626        source: Option<&dyn ArraySource>,
627        role: &'static str,
628    ) -> BindingResult<SeriesBinding> {
629        Ok((self.bind_numeric(source, role)?, None))
630    }
631}
632impl NumericSeriesInput for NumericValues {
633    fn bind_series(
634        self,
635        _: Option<&dyn ArraySource>,
636        _: &'static str,
637    ) -> BindingResult<SeriesBinding> {
638        Ok((self, None))
639    }
640}
641macro_rules! one_series {
642    ($ty:ty) => {
643        impl<T: ArrayElement + crate::binding::NumericElement> NumericSeriesInput for $ty {
644            fn bind_series(
645                self,
646                source: Option<&dyn ArraySource>,
647                role: &'static str,
648            ) -> BindingResult<SeriesBinding> {
649                Ok((self.bind_numeric(source, role)?, None))
650            }
651        }
652    };
653}
654one_series!(ArrayView1<'_, T>);
655one_series!((ArrayView1<'_, T>, ArrayView1<'_, bool>));
656macro_rules! matrix_series {
657    ($ty:ty) => {
658        impl<T: ArrayElement> NumericSeriesInput for $ty {
659            fn bind_series(
660                self,
661                source: Option<&dyn ArraySource>,
662                role: &'static str,
663            ) -> BindingResult<SeriesBinding> {
664                multiple(self.bind_columns(source)?, true, role)
665            }
666        }
667    };
668}
669matrix_series!(ArrayView2<'_, T>);
670matrix_series!((ArrayView2<'_, T>, ArrayView2<'_, bool>));
671impl NumericSeriesInput for &[usize] {
672    fn bind_series(
673        self,
674        source: Option<&dyn ArraySource>,
675        role: &'static str,
676    ) -> BindingResult<SeriesBinding> {
677        multiple(self.bind_columns(source)?, false, role)
678    }
679}
680impl<const N: usize> NumericSeriesInput for [usize; N] {
681    fn bind_series(
682        self,
683        source: Option<&dyn ArraySource>,
684        role: &'static str,
685    ) -> BindingResult<SeriesBinding> {
686        multiple(self.bind_columns(source)?, false, role)
687    }
688}
689
690fn cell_columns<T: Clone>(
691    source: Option<&dyn ArraySource>,
692    indices: &[usize],
693    role: &'static str,
694    read: impl Fn(&dyn ArraySource, usize) -> BindingResult<Vec<T>>,
695) -> BindingResult<Vec<T>> {
696    let first = *indices
697        .first()
698        .ok_or_else(|| binding(role, "select at least one column"))?;
699    let source = crate::source::lookup(source, first, role)?;
700    let rows = source.shape().0;
701    let cells = rows
702        .checked_mul(indices.len())
703        .ok_or_else(|| binding(role, "cell count exceeds usize"))?;
704    let mut columns = crate::snapshot::allocate(indices.len(), role)?;
705    let mut seen = HashSet::new();
706    seen.try_reserve(indices.len())
707        .map_err(|source| crate::AdapterError::Allocation {
708            operation: role,
709            source,
710        })?;
711    for &index in indices {
712        if !seen.insert(index) {
713            return Err(binding(role, format!("duplicate column {index}")));
714        }
715        crate::source::lookup(Some(source), index, role)?;
716        columns.push(read(source, index)?);
717    }
718    let mut values = crate::snapshot::allocate(cells, role)?;
719    for row in 0..rows {
720        for column in &columns {
721            values.push(column[row].clone());
722        }
723    }
724    Ok(values)
725}
726impl BooleanInput for &[usize] {
727    fn raw_boolean(
728        self,
729        source: Option<&dyn ArraySource>,
730        role: &'static str,
731    ) -> BindingResult<Raw<bool>> {
732        Ok((
733            role.into(),
734            cell_columns(source, self, role, |source, index| {
735                source.boolean_column(index, role)
736            })?,
737        ))
738    }
739    fn bind_boolean_repeated(
740        self,
741        source: Option<&dyn ArraySource>,
742        role: &'static str,
743        _: usize,
744    ) -> BindingResult<BooleanValues> {
745        self.bind_boolean(source, role)
746    }
747}
748impl<const N: usize> BooleanInput for [usize; N] {
749    fn raw_boolean(
750        self,
751        source: Option<&dyn ArraySource>,
752        role: &'static str,
753    ) -> BindingResult<Raw<bool>> {
754        self.as_slice().raw_boolean(source, role)
755    }
756    fn bind_boolean_repeated(
757        self,
758        source: Option<&dyn ArraySource>,
759        role: &'static str,
760        _: usize,
761    ) -> BindingResult<BooleanValues> {
762        self.bind_boolean(source, role)
763    }
764}
765impl SourceRowsInput for &[usize] {
766    fn raw_source_rows(
767        self,
768        source: Option<&dyn ArraySource>,
769        role: &'static str,
770    ) -> BindingResult<Vec<usize>> {
771        cell_columns(source, self, role, |source, index| {
772            source.id_column(index, role)
773        })
774    }
775    fn bind_source_rows(
776        self,
777        source: Option<&dyn ArraySource>,
778        role: &'static str,
779    ) -> BindingResult<SourceRows> {
780        Ok(SourceRows::new(self.raw_source_rows(source, role)?)?)
781    }
782}
783impl<const N: usize> SourceRowsInput for [usize; N] {
784    fn raw_source_rows(
785        self,
786        source: Option<&dyn ArraySource>,
787        role: &'static str,
788    ) -> BindingResult<Vec<usize>> {
789        self.as_slice().raw_source_rows(source, role)
790    }
791    fn bind_source_rows(
792        self,
793        source: Option<&dyn ArraySource>,
794        role: &'static str,
795    ) -> BindingResult<SourceRows> {
796        self.as_slice().bind_source_rows(source, role)
797    }
798}