Skip to main content

lichtung_plot/data/
binding.rs

1//! Native records of actual source captures and original selections.
2
3use std::{
4    fmt,
5    hash::{Hash, Hasher},
6    sync::Arc,
7};
8
9use super::{AxisValues, ExactInteger, RawKey};
10use crate::{BooleanValues, CategoryValues, Error, NumericValues, Result};
11
12/// An opaque logical source and a particular capture batch.
13///
14/// No foreign object or mutable data is retained. Cloning preserves both
15/// identities; recapturing the same source preserves only its logical identity.
16#[derive(Clone)]
17pub struct DataSourceRef {
18    logical: Arc<()>,
19    capture: Arc<()>,
20}
21
22impl DataSourceRef {
23    /// Allocate a source at the actual binding boundary.
24    #[doc(hidden)]
25    pub fn capture() -> Self {
26        Self {
27            logical: Arc::new(()),
28            capture: Arc::new(()),
29        }
30    }
31
32    /// Capture this same logical source in a subsequent binding operation.
33    #[doc(hidden)]
34    #[must_use]
35    pub fn recapture(&self) -> Self {
36        Self {
37            logical: Arc::clone(&self.logical),
38            capture: Arc::new(()),
39        }
40    }
41
42    /// Whether two actual capture batches belong to the same logical source.
43    pub fn same_source(&self, other: &Self) -> bool {
44        Arc::ptr_eq(&self.logical, &other.logical)
45    }
46}
47
48impl PartialEq for DataSourceRef {
49    fn eq(&self, other: &Self) -> bool {
50        self.same_source(other) && Arc::ptr_eq(&self.capture, &other.capture)
51    }
52}
53
54impl Eq for DataSourceRef {}
55
56impl Hash for DataSourceRef {
57    fn hash<H: Hasher>(&self, state: &mut H) {
58        Arc::as_ptr(&self.logical).hash(state);
59        Arc::as_ptr(&self.capture).hash(state);
60    }
61}
62
63impl fmt::Debug for DataSourceRef {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        f.debug_struct("DataSourceRef").finish_non_exhaustive()
66    }
67}
68
69/// The original kind of an actual field or collection selector.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
71#[non_exhaustive]
72pub enum BindingSelectorKind {
73    /// Single key.
74    Key,
75    /// Ordered key collection.
76    Keys,
77    /// Signed logical index.
78    Index,
79    /// Ordered signed positions.
80    Indices,
81    /// Positional slice.
82    Slice,
83    /// All fields.
84    All,
85    /// Numeric discovery rule.
86    NumericOnly,
87    /// Whole object.
88    Whole,
89}
90
91/// Original signed endpoints, with omission distinct from a bound.
92/// The exact step also supports foreign integers larger than machine indices.
93#[derive(Debug, Clone, PartialEq, Eq, Hash)]
94pub struct BindingSlice {
95    start: Option<isize>,
96    stop: Option<isize>,
97    step: ExactInteger,
98}
99
100impl BindingSlice {
101    /// Capture the authored slice without normalizing its bounds or step.
102    pub fn new(start: Option<isize>, end: Option<isize>, stride: ExactInteger) -> Result<Self> {
103        if stride == ExactInteger::from(0) {
104            return Err(Error::Data("binding slice step must not be zero".into()));
105        }
106        Ok(Self {
107            start,
108            stop: end,
109            step: stride,
110        })
111    }
112
113    /// Original start.
114    pub const fn start(&self) -> Option<isize> {
115        self.start
116    }
117
118    /// Original stop.
119    pub const fn stop(&self) -> Option<isize> {
120        self.stop
121    }
122
123    /// Exact signed step.
124    pub const fn step(&self) -> &ExactInteger {
125        &self.step
126    }
127}
128
129/// A captured selection, distinct from its resolved field positions and keys.
130#[derive(Debug, Clone, PartialEq, Eq, Hash)]
131#[non_exhaustive]
132pub enum BindingSelector {
133    /// One complete original field key.
134    Key(RawKey),
135    /// Ordered complete field keys.
136    Keys(Vec<RawKey>),
137    /// One original signed index.
138    Index(isize),
139    /// Ordered original signed indices.
140    Indices(Vec<isize>),
141    /// Original slice.
142    Slice(BindingSlice),
143    /// Dynamic all-fields selection.
144    All,
145    /// Dynamic numerical-field discovery.
146    NumericOnly,
147    /// Entire object.
148    Whole,
149}
150
151impl BindingSelector {
152    /// Select one complete original key.
153    pub fn key(value: impl Into<RawKey>) -> Self {
154        Self::Key(value.into())
155    }
156    /// Select one signed position on the actual logical column axis.
157    pub const fn index(value: isize) -> Self {
158        Self::Index(value)
159    }
160    /// Select an ordered collection of original keys.
161    pub fn keys(values: impl IntoIterator<Item = impl Into<RawKey>>) -> Self {
162        Self::Keys(values.into_iter().map(Into::into).collect())
163    }
164    /// Select ordered signed logical positions.
165    pub fn indices(values: impl IntoIterator<Item = isize>) -> Self {
166        Self::Indices(values.into_iter().collect())
167    }
168
169    /// Discriminant of the actual selector.
170    pub const fn kind(&self) -> BindingSelectorKind {
171        match self {
172            Self::Key(_) => BindingSelectorKind::Key,
173            Self::Keys(_) => BindingSelectorKind::Keys,
174            Self::Index(_) => BindingSelectorKind::Index,
175            Self::Indices(_) => BindingSelectorKind::Indices,
176            Self::Slice(_) => BindingSelectorKind::Slice,
177            Self::All => BindingSelectorKind::All,
178            Self::NumericOnly => BindingSelectorKind::NumericOnly,
179            Self::Whole => BindingSelectorKind::Whole,
180        }
181    }
182
183    /// Authored key, if selected by key.
184    pub const fn get_key(&self) -> Option<&RawKey> {
185        if let Self::Key(key) = self {
186            Some(key)
187        } else {
188            None
189        }
190    }
191
192    /// Authored ordered key collection.
193    pub fn get_keys(&self) -> Option<&[RawKey]> {
194        if let Self::Keys(keys) = self {
195            Some(keys)
196        } else {
197            None
198        }
199    }
200
201    /// Original signed index.
202    pub const fn get_index(&self) -> Option<isize> {
203        if let Self::Index(index) = self {
204            Some(*index)
205        } else {
206            None
207        }
208    }
209
210    /// Original ordered signed indices.
211    pub fn get_indices(&self) -> Option<&[isize]> {
212        if let Self::Indices(indices) = self {
213            Some(indices)
214        } else {
215            None
216        }
217    }
218
219    /// Original slice rule.
220    pub const fn get_slice(&self) -> Option<&BindingSlice> {
221        if let Self::Slice(slice) = self {
222            Some(slice)
223        } else {
224            None
225        }
226    }
227}
228
229/// An explicit origin rule used to construct aligned input members.
230#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
231#[non_exhaustive]
232pub enum BindingGeneration {
233    /// Zero-based row position supplies the actual coordinate.
234    RowPosition,
235    /// Original selected columns supply categorical identities.
236    ColumnNames,
237    /// Logical grid positions supply coordinates.
238    GridPosition,
239    /// An ordered rectangular selection is expanded in row-major order.
240    WideExpansion,
241}
242
243/// A real source capture, including the original selector and actual selected fields.
244///
245/// This metadata is immutable and has no connection to a foreign source's
246/// subsequent values, names, dimensions or lifetime.
247#[derive(Debug, Clone, PartialEq, Eq)]
248pub struct DataSourceInfo(Arc<SourceInfo>);
249
250#[derive(Debug, Clone, PartialEq, Eq)]
251struct SourceInfo {
252    reference: DataSourceRef,
253    binding_name: Option<String>,
254    generation: Option<BindingGeneration>,
255    relation_shape: Option<Vec<usize>>,
256    grid_axis: Option<usize>,
257    generated_columns: Option<GeneratedColumns>,
258    column_key_source: Option<ColumnKeySource>,
259    selector: Option<BindingSelector>,
260    selected_keys: Option<Vec<RawKey>>,
261    selected_names: Option<Vec<String>>,
262    selected_indices: Option<Vec<usize>>,
263    source_shape: Vec<usize>,
264    selected_shape: Vec<usize>,
265}
266
267/// Actual generated-column field and its native projection, for the adapter bridges.
268#[doc(hidden)]
269#[derive(Debug, Clone, PartialEq, Eq)]
270pub struct GeneratedColumns {
271    /// The actual generated field identity.
272    pub field: String,
273    /// Whether source identities are local column positions.
274    pub local_positions: bool,
275    /// Whether source display text is verbatim.
276    pub verbatim_labels: bool,
277    /// Current renderer identities in selected-column order.
278    pub tokens: Vec<String>,
279    /// Actual complete original identities in selected-column order.
280    pub keys: Vec<RawKey>,
281}
282
283/// Namespace of a supplied integer selector for a generated column dimension.
284#[doc(hidden)]
285#[derive(Debug, Clone, PartialEq, Eq)]
286pub enum ColumnKeyLookup {
287    /// Resolve positions in the actual primary collection.
288    Selected,
289    /// An explicitly supplied logical column-identity namespace.
290    Named(Arc<[(usize, RawKey)]>),
291}
292
293impl ColumnKeyLookup {
294    pub(crate) fn resolve(&self, primary: &DataSourceInfo, index: usize) -> Result<RawKey> {
295        let policy = primary.column_generation().ok_or_else(|| {
296            Error::Data("column selectors require a generated column dimension".into())
297        })?;
298        if let Self::Named(names) = self {
299            return names
300                .iter()
301                .find(|(position, _)| *position == index)
302                .map(|(_, key)| key.clone())
303                .ok_or_else(|| {
304                    Error::Data(format!("no original identity for logical column {index}").into())
305                });
306        }
307        let position = if policy.local_positions {
308            Some(index)
309        } else {
310            primary.selected_indices().map_or(Some(index), |indices| {
311                indices.iter().position(|&selected| selected == index)
312            })
313        };
314        if let Some(key) = position.and_then(|position| policy.keys.get(position)) {
315            return Ok(key.clone());
316        }
317        let key = RawKey::from(index);
318        if policy.keys.contains(&key) {
319            return Err(Error::Data(
320                format!("unselected column {index} conflicts with an actual original key").into(),
321            ));
322        }
323        // Positional selectors may include pooled keys outside the actual
324        // selection, without acquiring another selected variable's identity.
325        Ok(key)
326    }
327}
328
329/// The original integer supply and its actual interpretation at adoption.
330#[doc(hidden)]
331#[derive(Debug, Clone, PartialEq, Eq)]
332pub struct ColumnKeySource {
333    /// Original supplied integer slots, independent of their resolved keys.
334    pub indices: Arc<[usize]>,
335    /// Actual generator lookup rule.
336    pub lookup: ColumnKeyLookup,
337}
338
339impl DataSourceInfo {
340    /// Capture a direct value with its actual shape.
341    #[doc(hidden)]
342    pub fn direct(shape: Vec<usize>) -> Self {
343        Self(Arc::new(SourceInfo {
344            reference: DataSourceRef::capture(),
345            binding_name: None,
346            generation: None,
347            relation_shape: None,
348            grid_axis: None,
349            generated_columns: None,
350            column_key_source: None,
351            selector: None,
352            selected_keys: None,
353            selected_names: None,
354            selected_indices: None,
355            source_shape: shape.clone(),
356            selected_shape: shape,
357        }))
358    }
359
360    /// Record the actual matched fields and shapes of a selection.
361    #[doc(hidden)]
362    pub fn selected(
363        reference: DataSourceRef,
364        selector: BindingSelector,
365        keys: Option<Vec<RawKey>>,
366        indices: Vec<usize>,
367        source_shape: Vec<usize>,
368        selected_shape: Vec<usize>,
369    ) -> Self {
370        Self::selected_optional(
371            reference,
372            selector,
373            keys,
374            Some(indices),
375            source_shape,
376            selected_shape,
377        )
378    }
379
380    pub(crate) fn selected_optional(
381        reference: DataSourceRef,
382        selector: BindingSelector,
383        keys: Option<Vec<RawKey>>,
384        indices: Option<Vec<usize>>,
385        source_shape: Vec<usize>,
386        selected_shape: Vec<usize>,
387    ) -> Self {
388        Self(Arc::new(SourceInfo {
389            reference,
390            binding_name: None,
391            generation: None,
392            relation_shape: None,
393            grid_axis: None,
394            generated_columns: None,
395            column_key_source: None,
396            selector: Some(selector),
397            selected_keys: keys,
398            selected_names: None,
399            selected_indices: indices,
400            source_shape,
401            selected_shape,
402        }))
403    }
404
405    pub(crate) fn named(mut self, name: String) -> Self {
406        Arc::make_mut(&mut self.0).binding_name = Some(name);
407        self
408    }
409
410    /// Capture the fields of an independently supplied rectangular object.
411    #[doc(hidden)]
412    pub fn direct_fields(shape: Vec<usize>, keys: Option<Vec<RawKey>>) -> Self {
413        let mut info = Self::direct(shape);
414        Arc::make_mut(&mut info.0).selected_keys = keys;
415        info
416    }
417
418    /// Record the actual generation rule and the shape of its supply domain.
419    #[doc(hidden)]
420    #[must_use]
421    pub fn generated(mut self, generation: BindingGeneration, shape: Vec<usize>) -> Self {
422        let info = Arc::make_mut(&mut self.0);
423        info.generation = Some(generation);
424        info.relation_shape = Some(shape);
425        self
426    }
427
428    /// Retain the actual selected-column identity and label policy of an expansion.
429    #[doc(hidden)]
430    #[must_use]
431    pub fn generated_columns(
432        mut self,
433        field: &str,
434        local_positions: bool,
435        verbatim_labels: bool,
436        tokens: Vec<String>,
437        keys: Vec<RawKey>,
438    ) -> Self {
439        self = self.generated(BindingGeneration::ColumnNames, vec![tokens.len()]);
440        Arc::make_mut(&mut self.0).generated_columns = Some(GeneratedColumns {
441            field: field.to_owned(),
442            local_positions,
443            verbatim_labels,
444            tokens,
445            keys,
446        });
447        self
448    }
449
450    /// Inspect the actual generated-column declaration.
451    #[doc(hidden)]
452    pub fn column_generation(&self) -> Option<&GeneratedColumns> {
453        self.0.generated_columns.as_ref()
454    }
455
456    /// Retain an integer selector's original supply and column lookup rule.
457    #[doc(hidden)]
458    pub fn with_column_key_source(
459        mut self,
460        indices: impl Into<Arc<[usize]>>,
461        lookup: ColumnKeyLookup,
462    ) -> Result<Self> {
463        let indices = indices.into();
464        if self.selected_shape() != [indices.len()] {
465            return Err(Error::Data(
466                "column selectors must be an exact supplied vector".into(),
467            ));
468        }
469        Arc::make_mut(&mut self.0).column_key_source = Some(ColumnKeySource { indices, lookup });
470        Ok(self)
471    }
472
473    /// Actual input relation of a projected integer column selector.
474    #[doc(hidden)]
475    pub fn column_key_source(&self) -> Option<&ColumnKeySource> {
476        self.0.column_key_source.as_ref()
477    }
478
479    /// Restore the same actual column projection from the primary rectangular capture.
480    #[doc(hidden)]
481    pub fn generated_column_values(&self) -> Result<crate::CategoryValues> {
482        let policy = self
483            .column_generation()
484            .ok_or_else(|| Error::Data("no generated column dimension".into()))?;
485        let [rows, width] = self.selected_shape() else {
486            return Err(Error::Data(
487                "generated columns require an actual rectangle".into(),
488            ));
489        };
490        if policy.tokens.len() != *width || policy.keys.len() != *width {
491            return Err(Error::Data(
492                "generated identities must align on the column axis".into(),
493            ));
494        }
495        let values = crate::CategoryValues::new(
496            &policy.field,
497            (0..*rows).flat_map(|_| policy.tokens.iter().cloned()),
498        )?;
499        let values = if policy
500            .keys
501            .iter()
502            .zip(&policy.tokens)
503            .all(|(raw, token)| matches!(raw,RawKey::String(value) if value==token))
504        {
505            values
506        } else {
507            values.with_key_values(super::KeyValues::repeated_keys(
508                &policy.field,
509                &policy.keys,
510                *rows,
511            )?)?
512        };
513        values.with_cycled_source(
514            self.clone()
515                .generated(BindingGeneration::ColumnNames, vec![*width]),
516        )
517    }
518
519    /// Retain the generated-column policy alongside the actual primary collection.
520    #[doc(hidden)]
521    #[must_use]
522    pub fn with_column_generation_from(mut self, source: &Self) -> Self {
523        Arc::make_mut(&mut self.0)
524            .generated_columns
525            .clone_from(&source.0.generated_columns);
526        self
527    }
528
529    pub(crate) fn with_column_generation(mut self, policy: GeneratedColumns) -> Self {
530        Arc::make_mut(&mut self.0).generated_columns = Some(policy);
531        self
532    }
533
534    /// Retain the actual row (0) or column (1) axis of generated grid positions.
535    #[doc(hidden)]
536    #[must_use]
537    pub fn generated_grid_axis(mut self, axis: usize, extent: usize) -> Self {
538        let info = Arc::make_mut(&mut self.0);
539        info.generation = Some(BindingGeneration::GridPosition);
540        info.grid_axis = Some(axis);
541        info.relation_shape = Some(vec![extent]);
542        self
543    }
544
545    pub(crate) fn grid_axis(&self) -> Option<usize> {
546        self.0.grid_axis
547    }
548
549    /// The explicit logical binding name, when declared.
550    pub fn binding_name(&self) -> Option<&str> {
551        self.0.binding_name.as_deref()
552    }
553
554    /// The actual logical keys of this binding (before any display mapping).
555    pub fn logical_keys(&self) -> Option<&[RawKey]> {
556        self.selected_keys()
557    }
558
559    /// The actual generation rule, when this input was generated.
560    pub fn generation(&self) -> Option<BindingGeneration> {
561        self.0.generation
562    }
563
564    /// Opaque actual source capture.
565    pub fn reference(&self) -> &DataSourceRef {
566        &self.0.reference
567    }
568
569    /// Authored selector, absent for direct variables.
570    pub fn selector(&self) -> Option<&BindingSelector> {
571        self.0.selector.as_ref()
572    }
573
574    /// Retain the original author-visible names separately from exact field keys.
575    #[doc(hidden)]
576    pub fn with_selected_names(mut self, names: Vec<String>) -> Result<Self> {
577        if self.0.selected_keys.as_ref().map(Vec::len) != Some(names.len()) {
578            return Err(Error::Data(
579                "captured field names must match their actual keys".into(),
580            ));
581        }
582        Arc::make_mut(&mut self.0).selected_names = Some(names);
583        Ok(self)
584    }
585
586    /// Exact display names retained by a captured host selection.
587    #[doc(hidden)]
588    pub fn selected_names(&self) -> Option<&[String]> {
589        self.0.selected_names.as_deref()
590    }
591
592    /// Original field identity and its author-visible name.
593    #[doc(hidden)]
594    pub fn field(&self, position: usize) -> Option<(RawKey, String)> {
595        let key = self.0.selected_keys.as_ref()?.get(position)?;
596        let name = if let Some(names) = &self.0.selected_names {
597            names.get(position)?.clone()
598        } else if let RawKey::String(name) = key {
599            name.clone()
600        } else {
601            return None;
602        };
603        Some((key.clone(), name))
604    }
605
606    /// Actual selected field keys, when the source has them.
607    pub fn selected_keys(&self) -> Option<&[RawKey]> {
608        self.0.selected_keys.as_deref()
609    }
610
611    /// Actual zero-based selected field positions.
612    pub fn selected_indices(&self) -> Option<&[usize]> {
613        self.0.selected_indices.as_deref()
614    }
615
616    /// Original logical source shape.
617    pub fn source_shape(&self) -> &[usize] {
618        &self.0.source_shape
619    }
620
621    /// Actual selected shape before any further projection.
622    pub fn selected_shape(&self) -> &[usize] {
623        &self.0.selected_shape
624    }
625
626    pub(crate) fn member_shape(&self) -> &[usize] {
627        self.0
628            .relation_shape
629            .as_deref()
630            .unwrap_or(&self.0.selected_shape)
631    }
632
633    fn selected_count(&self) -> Option<usize> {
634        self.member_shape()
635            .iter()
636            .try_fold(1usize, |n, &size| n.checked_mul(size))
637    }
638}
639
640/// Original source and actual source-row relation of a native vector.
641#[derive(Debug, Clone)]
642pub(crate) struct VectorSource {
643    info: DataSourceInfo,
644    projection: Option<Arc<SourceProjection>>,
645}
646
647#[derive(Debug, Clone)]
648enum SlotProjection {
649    Identity,
650    Repeated(usize),
651    Cycled(usize),
652    Gathered(Arc<[usize]>),
653}
654
655#[derive(Debug, Clone)]
656struct SourceProjection {
657    slots: SlotProjection,
658    original_nulls: bool,
659    field_nulls: Option<Arc<[bool]>>,
660    distinct_rows: bool,
661    field_axis_keys: Option<Arc<super::RawKeyValues>>,
662}
663
664impl Default for SourceProjection {
665    fn default() -> Self {
666        Self {
667            slots: SlotProjection::Identity,
668            original_nulls: false,
669            field_nulls: None,
670            distinct_rows: true,
671            field_axis_keys: None,
672        }
673    }
674}
675
676impl VectorSource {
677    pub(crate) fn direct(len: usize) -> Self {
678        Self::new(DataSourceInfo::direct(vec![len]))
679    }
680
681    pub(crate) fn direct_nullable(len: usize, has_nulls: bool) -> Self {
682        let mut source = Self::direct(len);
683        if has_nulls {
684            source.projection_mut().original_nulls = true;
685        }
686        source
687    }
688
689    pub(crate) fn new(info: DataSourceInfo) -> Self {
690        Self {
691            info,
692            projection: None,
693        }
694    }
695
696    fn projection_mut(&mut self) -> &mut SourceProjection {
697        Arc::make_mut(
698            self.projection
699                .get_or_insert_with(|| Arc::new(SourceProjection::default())),
700        )
701    }
702
703    pub(crate) fn repeated(info: DataSourceInfo, copies: usize, len: usize) -> Result<Self> {
704        if copies == 0 || info.selected_count().and_then(|n| n.checked_mul(copies)) != Some(len) {
705            return Err(Error::Data(
706                "captured source shape and repetition must match the actual value count".into(),
707            ));
708        }
709        let mut source = Self::new(info);
710        if copies != 1 {
711            let projection = source.projection_mut();
712            projection.slots = SlotProjection::Repeated(copies);
713            projection.distinct_rows = false;
714        }
715        Ok(source)
716    }
717
718    pub(crate) fn cycled(info: DataSourceInfo, len: usize) -> Result<Self> {
719        let count = info.selected_count().unwrap_or(0);
720        if count == 0 || !len.is_multiple_of(count) {
721            return Err(Error::Data(
722                "captured column identity count must divide the actual value count".into(),
723            ));
724        }
725        let field_axis_keys = complete_field_axis(&info)?;
726        Ok(Self {
727            info,
728            projection: Some(super::source::source_arc(SourceProjection {
729                slots: SlotProjection::Cycled(count),
730                distinct_rows: false,
731                field_axis_keys,
732                ..SourceProjection::default()
733            })?),
734        })
735    }
736
737    pub(crate) fn gathered(info: DataSourceInfo, slots: Vec<usize>, len: usize) -> Result<Self> {
738        if slots.len() != len
739            || !info
740                .selected_count()
741                .is_some_and(|count| slots.iter().all(|&slot| slot < count))
742        {
743            return Err(Error::Data(
744                "captured source slots must match the actual value domain".into(),
745            ));
746        }
747        let distinct_rows = info.member_shape().len() == 1 && distinct_slots(&slots)?;
748        let field_axis_keys = complete_field_axis(&info)?;
749        Ok(Self {
750            info,
751            projection: Some(super::source::source_arc(SourceProjection {
752                slots: SlotProjection::Gathered(slots.into()),
753                distinct_rows,
754                field_axis_keys,
755                ..SourceProjection::default()
756            })?),
757        })
758    }
759
760    pub(crate) fn info(&self) -> &DataSourceInfo {
761        &self.info
762    }
763
764    pub(crate) fn slot(&self, index: usize) -> usize {
765        match self
766            .projection
767            .as_deref()
768            .map(|projection| &projection.slots)
769        {
770            None | Some(SlotProjection::Identity) => index,
771            Some(SlotProjection::Repeated(copies)) => index / copies,
772            Some(SlotProjection::Cycled(count)) => index % count,
773            Some(SlotProjection::Gathered(slots)) => slots[index],
774        }
775    }
776
777    pub(crate) fn column_cycle(&self) -> Option<usize> {
778        match &self.projection.as_deref()?.slots {
779            SlotProjection::Cycled(columns) => Some(*columns),
780            _ => None,
781        }
782    }
783
784    pub(crate) fn row_repetition(&self) -> Option<usize> {
785        match &self.projection.as_deref()?.slots {
786            SlotProjection::Repeated(copies) => Some(*copies),
787            _ => None,
788        }
789    }
790
791    pub(crate) fn mark_rows(&mut self) {
792        if self.is_identity() {
793            self.projection_mut().slots = SlotProjection::Repeated(1);
794        }
795    }
796
797    pub(crate) fn is_identity(&self) -> bool {
798        self.projection
799            .as_deref()
800            .is_none_or(|entry| matches!(entry.slots, SlotProjection::Identity))
801    }
802
803    pub(crate) fn has_distinct_rows(&self) -> bool {
804        self.info.member_shape().len() == 1
805            && self
806                .projection
807                .as_deref()
808                .is_none_or(|entry| entry.distinct_rows)
809    }
810
811    pub(crate) fn field_axis_keys(&self) -> Option<&super::RawKeyValues> {
812        self.projection.as_deref()?.field_axis_keys.as_deref()
813    }
814
815    /// Retain captured presence before selection or interleaving can hide
816    /// which original field actually contained missing values.
817    pub(crate) fn with_original_validity(
818        mut self,
819        length: usize,
820        has_nulls: bool,
821        is_valid: impl Fn(usize) -> bool,
822    ) -> Result<Self> {
823        if !has_nulls && self.projection.is_none() {
824            return Ok(self);
825        }
826        let mut field_nulls = None;
827        if has_nulls && self.info.selected_keys().is_some() {
828            if let [_, width] = self.info.member_shape() {
829                let mut fields = Vec::new();
830                super::source::reserve_source(&mut fields, *width)?;
831                fields.resize(*width, false);
832                crate::operation::check()?;
833                for slot in 0..length {
834                    if !is_valid(slot) {
835                        fields[self.slot(slot) % width] = true;
836                    }
837                }
838                field_nulls = Some(fields.into());
839            }
840        }
841        let projection = self.projection_mut();
842        projection.original_nulls = has_nulls;
843        projection.field_nulls = field_nulls;
844        Ok(self)
845    }
846
847    pub(crate) fn original_has_nulls(&self, field: Option<usize>) -> bool {
848        let Some(projection) = self.projection.as_deref() else {
849            return false;
850        };
851        field
852            .and_then(|field| projection.field_nulls.as_ref()?.get(field).copied())
853            .unwrap_or(projection.original_nulls)
854    }
855
856    pub(crate) fn retain_original_validity(&mut self, source: &Self) {
857        if let Some(original) = source.projection.as_deref() {
858            let projection = self.projection_mut();
859            projection.original_nulls = original.original_nulls;
860            projection.field_nulls.clone_from(&original.field_nulls);
861            projection.distinct_rows &= original.distinct_rows;
862            projection
863                .field_axis_keys
864                .clone_from(&original.field_axis_keys);
865        }
866    }
867
868    pub(crate) fn select(&self, indices: &[usize]) -> Result<Self> {
869        let slots =
870            super::source::collect_source(indices.iter().map(|&index| Ok(self.slot(index))))?;
871        let distinct_rows = self.has_distinct_rows() && distinct_slots(&slots)?;
872        let mut projection = self.projection.as_deref().cloned().unwrap_or_default();
873        projection.slots = SlotProjection::Gathered(slots.into());
874        projection.distinct_rows = distinct_rows;
875        Ok(Self {
876            info: self.info.clone(),
877            projection: Some(super::source::source_arc(projection)?),
878        })
879    }
880}
881
882fn complete_field_axis(info: &DataSourceInfo) -> Result<Option<Arc<super::RawKeyValues>>> {
883    if info.generation() != Some(BindingGeneration::ColumnNames) && info.grid_axis() != Some(1) {
884        return Ok(None);
885    }
886    let (Some(keys), Some(&width)) = (info.selected_keys(), info.source_shape().get(1)) else {
887        return Ok(None);
888    };
889    if keys.len() != width {
890        // Unselected fields have no captured keys.
891        return Ok(None);
892    }
893    let mut ordered = Vec::new();
894    super::source::reserve_source(&mut ordered, width)?;
895    ordered.resize(width, None);
896    for (slot, key) in keys.iter().enumerate() {
897        let position = info
898            .selected_indices()
899            .and_then(|indices| indices.get(slot))
900            .copied()
901            .unwrap_or(slot);
902        let Some(target) = ordered.get_mut(position) else {
903            return Ok(None);
904        };
905        if target.replace(key.clone()).is_some() {
906            return Ok(None);
907        }
908    }
909    Ok(Some(Arc::new(super::RawKeyValues::nullable(
910        "field", ordered,
911    )?)))
912}
913
914fn distinct_slots(slots: &[usize]) -> Result<bool> {
915    crate::operation::check()?;
916    if slots.windows(2).all(|pair| pair[0] < pair[1]) {
917        return Ok(true);
918    }
919    let mut sorted = super::source::collect_source(slots.iter().copied().map(Ok))?;
920    super::source::sort_source_by(&mut sorted, usize::cmp)?;
921    Ok(sorted.windows(2).all(|pair| pair[0] != pair[1]))
922}
923
924/// Native value bridge for attaching a verified adapter source capture.
925#[doc(hidden)]
926pub trait CapturedValue: Sized {
927    /// Length of the actual captured vector.
928    fn len(&self) -> usize;
929    /// Whether this vector is empty.
930    fn is_empty(&self) -> bool {
931        self.len() == 0
932    }
933    /// Retain an explicit row-scoped adoption, even when it currently has one column.
934    #[must_use]
935    fn row_scoped(self) -> Self;
936    /// Attach the verified source selection and row relation.
937    fn retain(
938        self,
939        source: DataSourceInfo,
940        copies: usize,
941        field: Option<(RawKey, String)>,
942    ) -> Result<Self>;
943}
944
945macro_rules! captured_values {
946    ($($ty:ident),+) => {$(
947        impl CapturedValue for $ty {
948            fn len(&self) -> usize { self.len() }
949
950            fn row_scoped(self) -> Self {
951                self.with_row_scope()
952            }
953
954            fn retain(
955                self, source: DataSourceInfo, copies: usize, field: Option<(RawKey, String)>,
956            ) -> Result<Self> {
957                let value = self.with_repeated_source(source, copies)?;
958                Ok(if let Some((key, name)) = field {
959                    value.with_field_key(key, name)
960                } else {
961                    value
962                })
963            }
964        }
965    )+};
966}
967captured_values!(NumericValues, CategoryValues, BooleanValues);
968
969impl CapturedValue for super::SourceRows {
970    fn len(&self) -> usize {
971        self.len()
972    }
973
974    fn row_scoped(self) -> Self {
975        self
976    }
977
978    fn retain(
979        self,
980        source: DataSourceInfo,
981        copies: usize,
982        _: Option<(RawKey, String)>,
983    ) -> Result<Self> {
984        if copies != 1 {
985            return Err(Error::Data(
986                "source row identities cannot be repeated".into(),
987            ));
988        }
989        self.with_source(source)
990    }
991}
992
993impl CapturedValue for super::RawKeyValues {
994    fn len(&self) -> usize {
995        self.len()
996    }
997
998    fn row_scoped(self) -> Self {
999        let mut source = self.vector_source().clone();
1000        source.mark_rows();
1001        self.with_vector_source(source)
1002    }
1003
1004    fn retain(
1005        self,
1006        source: DataSourceInfo,
1007        copies: usize,
1008        _: Option<(RawKey, String)>,
1009    ) -> Result<Self> {
1010        let len = self.len();
1011        let source = VectorSource::repeated(source, copies, len)?.with_original_validity(
1012            len,
1013            self.has_nulls(),
1014            |slot| self.is_valid(slot) == Some(true),
1015        )?;
1016        Ok(self.with_vector_source(source))
1017    }
1018}
1019
1020impl CapturedValue for AxisValues {
1021    fn len(&self) -> usize {
1022        self.len()
1023    }
1024
1025    fn row_scoped(self) -> Self {
1026        match self {
1027            Self::Numeric(values) => Self::Numeric(values.row_scoped()),
1028            Self::Category(values) => Self::Category(values.row_scoped()),
1029            Self::Keys(values) => Self::Keys(values.row_scoped()),
1030        }
1031    }
1032
1033    fn retain(
1034        self,
1035        source: DataSourceInfo,
1036        copies: usize,
1037        field: Option<(RawKey, String)>,
1038    ) -> Result<Self> {
1039        Ok(match self {
1040            Self::Numeric(values) => Self::Numeric(values.retain(source, copies, field)?),
1041            Self::Category(values) => Self::Category(values.retain(source, copies, field)?),
1042            Self::Keys(values) => Self::Keys(values.retain(source, copies, field)?),
1043        })
1044    }
1045}