lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
//! Native records of actual source captures and original selections.

use std::{
    fmt,
    hash::{Hash, Hasher},
    sync::Arc,
};

use super::{AxisValues, ExactInteger, RawKey};
use crate::{BooleanValues, CategoryValues, Error, NumericValues, Result};

/// An opaque logical source and a particular capture batch.
///
/// No foreign object or mutable data is retained. Cloning preserves both
/// identities; recapturing the same source preserves only its logical identity.
#[derive(Clone)]
pub struct DataSourceRef {
    logical: Arc<()>,
    capture: Arc<()>,
}

impl DataSourceRef {
    /// Allocate a source at the actual binding boundary.
    #[doc(hidden)]
    pub fn capture() -> Self {
        Self {
            logical: Arc::new(()),
            capture: Arc::new(()),
        }
    }

    /// Capture this same logical source in a subsequent binding operation.
    #[doc(hidden)]
    #[must_use]
    pub fn recapture(&self) -> Self {
        Self {
            logical: Arc::clone(&self.logical),
            capture: Arc::new(()),
        }
    }

    /// Whether two actual capture batches belong to the same logical source.
    pub fn same_source(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.logical, &other.logical)
    }
}

impl PartialEq for DataSourceRef {
    fn eq(&self, other: &Self) -> bool {
        self.same_source(other) && Arc::ptr_eq(&self.capture, &other.capture)
    }
}

impl Eq for DataSourceRef {}

impl Hash for DataSourceRef {
    fn hash<H: Hasher>(&self, state: &mut H) {
        Arc::as_ptr(&self.logical).hash(state);
        Arc::as_ptr(&self.capture).hash(state);
    }
}

impl fmt::Debug for DataSourceRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DataSourceRef").finish_non_exhaustive()
    }
}

/// The original kind of an actual field or collection selector.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BindingSelectorKind {
    /// Single key.
    Key,
    /// Ordered key collection.
    Keys,
    /// Signed logical index.
    Index,
    /// Ordered signed positions.
    Indices,
    /// Positional slice.
    Slice,
    /// All fields.
    All,
    /// Numeric discovery rule.
    NumericOnly,
    /// Whole object.
    Whole,
}

/// Original signed endpoints, with omission distinct from a bound.
/// The exact step also supports foreign integers larger than machine indices.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct BindingSlice {
    start: Option<isize>,
    stop: Option<isize>,
    step: ExactInteger,
}

impl BindingSlice {
    /// Capture the authored slice without normalizing its bounds or step.
    pub fn new(start: Option<isize>, end: Option<isize>, stride: ExactInteger) -> Result<Self> {
        if stride == ExactInteger::from(0) {
            return Err(Error::Data("binding slice step must not be zero".into()));
        }
        Ok(Self {
            start,
            stop: end,
            step: stride,
        })
    }

    /// Original start.
    pub const fn start(&self) -> Option<isize> {
        self.start
    }

    /// Original stop.
    pub const fn stop(&self) -> Option<isize> {
        self.stop
    }

    /// Exact signed step.
    pub const fn step(&self) -> &ExactInteger {
        &self.step
    }
}

/// A captured selection, distinct from its resolved field positions and keys.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BindingSelector {
    /// One complete original field key.
    Key(RawKey),
    /// Ordered complete field keys.
    Keys(Vec<RawKey>),
    /// One original signed index.
    Index(isize),
    /// Ordered original signed indices.
    Indices(Vec<isize>),
    /// Original slice.
    Slice(BindingSlice),
    /// Dynamic all-fields selection.
    All,
    /// Dynamic numerical-field discovery.
    NumericOnly,
    /// Entire object.
    Whole,
}

impl BindingSelector {
    /// Select one complete original key.
    pub fn key(value: impl Into<RawKey>) -> Self {
        Self::Key(value.into())
    }
    /// Select one signed position on the actual logical column axis.
    pub const fn index(value: isize) -> Self {
        Self::Index(value)
    }
    /// Select an ordered collection of original keys.
    pub fn keys(values: impl IntoIterator<Item = impl Into<RawKey>>) -> Self {
        Self::Keys(values.into_iter().map(Into::into).collect())
    }
    /// Select ordered signed logical positions.
    pub fn indices(values: impl IntoIterator<Item = isize>) -> Self {
        Self::Indices(values.into_iter().collect())
    }

    /// Discriminant of the actual selector.
    pub const fn kind(&self) -> BindingSelectorKind {
        match self {
            Self::Key(_) => BindingSelectorKind::Key,
            Self::Keys(_) => BindingSelectorKind::Keys,
            Self::Index(_) => BindingSelectorKind::Index,
            Self::Indices(_) => BindingSelectorKind::Indices,
            Self::Slice(_) => BindingSelectorKind::Slice,
            Self::All => BindingSelectorKind::All,
            Self::NumericOnly => BindingSelectorKind::NumericOnly,
            Self::Whole => BindingSelectorKind::Whole,
        }
    }

    /// Authored key, if selected by key.
    pub const fn get_key(&self) -> Option<&RawKey> {
        if let Self::Key(key) = self {
            Some(key)
        } else {
            None
        }
    }

    /// Authored ordered key collection.
    pub fn get_keys(&self) -> Option<&[RawKey]> {
        if let Self::Keys(keys) = self {
            Some(keys)
        } else {
            None
        }
    }

    /// Original signed index.
    pub const fn get_index(&self) -> Option<isize> {
        if let Self::Index(index) = self {
            Some(*index)
        } else {
            None
        }
    }

    /// Original ordered signed indices.
    pub fn get_indices(&self) -> Option<&[isize]> {
        if let Self::Indices(indices) = self {
            Some(indices)
        } else {
            None
        }
    }

    /// Original slice rule.
    pub const fn get_slice(&self) -> Option<&BindingSlice> {
        if let Self::Slice(slice) = self {
            Some(slice)
        } else {
            None
        }
    }
}

/// An explicit origin rule used to construct aligned input members.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BindingGeneration {
    /// Zero-based row position supplies the actual coordinate.
    RowPosition,
    /// Original selected columns supply categorical identities.
    ColumnNames,
    /// Logical grid positions supply coordinates.
    GridPosition,
    /// An ordered rectangular selection is expanded in row-major order.
    WideExpansion,
}

/// A real source capture, including the original selector and actual selected fields.
///
/// This metadata is immutable and has no connection to a foreign source's
/// subsequent values, names, dimensions or lifetime.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DataSourceInfo(Arc<SourceInfo>);

#[derive(Debug, Clone, PartialEq, Eq)]
struct SourceInfo {
    reference: DataSourceRef,
    binding_name: Option<String>,
    generation: Option<BindingGeneration>,
    relation_shape: Option<Vec<usize>>,
    grid_axis: Option<usize>,
    generated_columns: Option<GeneratedColumns>,
    column_key_source: Option<ColumnKeySource>,
    selector: Option<BindingSelector>,
    selected_keys: Option<Vec<RawKey>>,
    selected_names: Option<Vec<String>>,
    selected_indices: Option<Vec<usize>>,
    source_shape: Vec<usize>,
    selected_shape: Vec<usize>,
}

/// Actual generated-column field and its native projection, for the adapter bridges.
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GeneratedColumns {
    /// The actual generated field identity.
    pub field: String,
    /// Whether source identities are local column positions.
    pub local_positions: bool,
    /// Whether source display text is verbatim.
    pub verbatim_labels: bool,
    /// Current renderer identities in selected-column order.
    pub tokens: Vec<String>,
    /// Actual complete original identities in selected-column order.
    pub keys: Vec<RawKey>,
}

/// Namespace of a supplied integer selector for a generated column dimension.
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ColumnKeyLookup {
    /// Resolve positions in the actual primary collection.
    Selected,
    /// An explicitly supplied logical column-identity namespace.
    Named(Arc<[(usize, RawKey)]>),
}

impl ColumnKeyLookup {
    pub(crate) fn resolve(&self, primary: &DataSourceInfo, index: usize) -> Result<RawKey> {
        let policy = primary.column_generation().ok_or_else(|| {
            Error::Data("column selectors require a generated column dimension".into())
        })?;
        if let Self::Named(names) = self {
            return names
                .iter()
                .find(|(position, _)| *position == index)
                .map(|(_, key)| key.clone())
                .ok_or_else(|| {
                    Error::Data(format!("no original identity for logical column {index}").into())
                });
        }
        let position = if policy.local_positions {
            Some(index)
        } else {
            primary.selected_indices().map_or(Some(index), |indices| {
                indices.iter().position(|&selected| selected == index)
            })
        };
        if let Some(key) = position.and_then(|position| policy.keys.get(position)) {
            return Ok(key.clone());
        }
        let key = RawKey::from(index);
        if policy.keys.contains(&key) {
            return Err(Error::Data(
                format!("unselected column {index} conflicts with an actual original key").into(),
            ));
        }
        // Positional selectors may include pooled keys outside the actual
        // selection, without acquiring another selected variable's identity.
        Ok(key)
    }
}

/// The original integer supply and its actual interpretation at adoption.
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ColumnKeySource {
    /// Original supplied integer slots, independent of their resolved keys.
    pub indices: Arc<[usize]>,
    /// Actual generator lookup rule.
    pub lookup: ColumnKeyLookup,
}

impl DataSourceInfo {
    /// Capture a direct value with its actual shape.
    #[doc(hidden)]
    pub fn direct(shape: Vec<usize>) -> Self {
        Self(Arc::new(SourceInfo {
            reference: DataSourceRef::capture(),
            binding_name: None,
            generation: None,
            relation_shape: None,
            grid_axis: None,
            generated_columns: None,
            column_key_source: None,
            selector: None,
            selected_keys: None,
            selected_names: None,
            selected_indices: None,
            source_shape: shape.clone(),
            selected_shape: shape,
        }))
    }

    /// Record the actual matched fields and shapes of a selection.
    #[doc(hidden)]
    pub fn selected(
        reference: DataSourceRef,
        selector: BindingSelector,
        keys: Option<Vec<RawKey>>,
        indices: Vec<usize>,
        source_shape: Vec<usize>,
        selected_shape: Vec<usize>,
    ) -> Self {
        Self::selected_optional(
            reference,
            selector,
            keys,
            Some(indices),
            source_shape,
            selected_shape,
        )
    }

    pub(crate) fn selected_optional(
        reference: DataSourceRef,
        selector: BindingSelector,
        keys: Option<Vec<RawKey>>,
        indices: Option<Vec<usize>>,
        source_shape: Vec<usize>,
        selected_shape: Vec<usize>,
    ) -> Self {
        Self(Arc::new(SourceInfo {
            reference,
            binding_name: None,
            generation: None,
            relation_shape: None,
            grid_axis: None,
            generated_columns: None,
            column_key_source: None,
            selector: Some(selector),
            selected_keys: keys,
            selected_names: None,
            selected_indices: indices,
            source_shape,
            selected_shape,
        }))
    }

    pub(crate) fn named(mut self, name: String) -> Self {
        Arc::make_mut(&mut self.0).binding_name = Some(name);
        self
    }

    /// Capture the fields of an independently supplied rectangular object.
    #[doc(hidden)]
    pub fn direct_fields(shape: Vec<usize>, keys: Option<Vec<RawKey>>) -> Self {
        let mut info = Self::direct(shape);
        Arc::make_mut(&mut info.0).selected_keys = keys;
        info
    }

    /// Record the actual generation rule and the shape of its supply domain.
    #[doc(hidden)]
    #[must_use]
    pub fn generated(mut self, generation: BindingGeneration, shape: Vec<usize>) -> Self {
        let info = Arc::make_mut(&mut self.0);
        info.generation = Some(generation);
        info.relation_shape = Some(shape);
        self
    }

    /// Retain the actual selected-column identity and label policy of an expansion.
    #[doc(hidden)]
    #[must_use]
    pub fn generated_columns(
        mut self,
        field: &str,
        local_positions: bool,
        verbatim_labels: bool,
        tokens: Vec<String>,
        keys: Vec<RawKey>,
    ) -> Self {
        self = self.generated(BindingGeneration::ColumnNames, vec![tokens.len()]);
        Arc::make_mut(&mut self.0).generated_columns = Some(GeneratedColumns {
            field: field.to_owned(),
            local_positions,
            verbatim_labels,
            tokens,
            keys,
        });
        self
    }

    /// Inspect the actual generated-column declaration.
    #[doc(hidden)]
    pub fn column_generation(&self) -> Option<&GeneratedColumns> {
        self.0.generated_columns.as_ref()
    }

    /// Retain an integer selector's original supply and column lookup rule.
    #[doc(hidden)]
    pub fn with_column_key_source(
        mut self,
        indices: impl Into<Arc<[usize]>>,
        lookup: ColumnKeyLookup,
    ) -> Result<Self> {
        let indices = indices.into();
        if self.selected_shape() != [indices.len()] {
            return Err(Error::Data(
                "column selectors must be an exact supplied vector".into(),
            ));
        }
        Arc::make_mut(&mut self.0).column_key_source = Some(ColumnKeySource { indices, lookup });
        Ok(self)
    }

    /// Actual input relation of a projected integer column selector.
    #[doc(hidden)]
    pub fn column_key_source(&self) -> Option<&ColumnKeySource> {
        self.0.column_key_source.as_ref()
    }

    /// Restore the same actual column projection from the primary rectangular capture.
    #[doc(hidden)]
    pub fn generated_column_values(&self) -> Result<crate::CategoryValues> {
        let policy = self
            .column_generation()
            .ok_or_else(|| Error::Data("no generated column dimension".into()))?;
        let [rows, width] = self.selected_shape() else {
            return Err(Error::Data(
                "generated columns require an actual rectangle".into(),
            ));
        };
        if policy.tokens.len() != *width || policy.keys.len() != *width {
            return Err(Error::Data(
                "generated identities must align on the column axis".into(),
            ));
        }
        let values = crate::CategoryValues::new(
            &policy.field,
            (0..*rows).flat_map(|_| policy.tokens.iter().cloned()),
        )?;
        let values = if policy
            .keys
            .iter()
            .zip(&policy.tokens)
            .all(|(raw, token)| matches!(raw,RawKey::String(value) if value==token))
        {
            values
        } else {
            values.with_key_values(super::KeyValues::repeated_keys(
                &policy.field,
                &policy.keys,
                *rows,
            )?)?
        };
        values.with_cycled_source(
            self.clone()
                .generated(BindingGeneration::ColumnNames, vec![*width]),
        )
    }

    /// Retain the generated-column policy alongside the actual primary collection.
    #[doc(hidden)]
    #[must_use]
    pub fn with_column_generation_from(mut self, source: &Self) -> Self {
        Arc::make_mut(&mut self.0)
            .generated_columns
            .clone_from(&source.0.generated_columns);
        self
    }

    pub(crate) fn with_column_generation(mut self, policy: GeneratedColumns) -> Self {
        Arc::make_mut(&mut self.0).generated_columns = Some(policy);
        self
    }

    /// Retain the actual row (0) or column (1) axis of generated grid positions.
    #[doc(hidden)]
    #[must_use]
    pub fn generated_grid_axis(mut self, axis: usize, extent: usize) -> Self {
        let info = Arc::make_mut(&mut self.0);
        info.generation = Some(BindingGeneration::GridPosition);
        info.grid_axis = Some(axis);
        info.relation_shape = Some(vec![extent]);
        self
    }

    pub(crate) fn grid_axis(&self) -> Option<usize> {
        self.0.grid_axis
    }

    /// The explicit logical binding name, when declared.
    pub fn binding_name(&self) -> Option<&str> {
        self.0.binding_name.as_deref()
    }

    /// The actual logical keys of this binding (before any display mapping).
    pub fn logical_keys(&self) -> Option<&[RawKey]> {
        self.selected_keys()
    }

    /// The actual generation rule, when this input was generated.
    pub fn generation(&self) -> Option<BindingGeneration> {
        self.0.generation
    }

    /// Opaque actual source capture.
    pub fn reference(&self) -> &DataSourceRef {
        &self.0.reference
    }

    /// Authored selector, absent for direct variables.
    pub fn selector(&self) -> Option<&BindingSelector> {
        self.0.selector.as_ref()
    }

    /// Retain the original author-visible names separately from exact field keys.
    #[doc(hidden)]
    pub fn with_selected_names(mut self, names: Vec<String>) -> Result<Self> {
        if self.0.selected_keys.as_ref().map(Vec::len) != Some(names.len()) {
            return Err(Error::Data(
                "captured field names must match their actual keys".into(),
            ));
        }
        Arc::make_mut(&mut self.0).selected_names = Some(names);
        Ok(self)
    }

    /// Exact display names retained by a captured host selection.
    #[doc(hidden)]
    pub fn selected_names(&self) -> Option<&[String]> {
        self.0.selected_names.as_deref()
    }

    /// Original field identity and its author-visible name.
    #[doc(hidden)]
    pub fn field(&self, position: usize) -> Option<(RawKey, String)> {
        let key = self.0.selected_keys.as_ref()?.get(position)?;
        let name = if let Some(names) = &self.0.selected_names {
            names.get(position)?.clone()
        } else if let RawKey::String(name) = key {
            name.clone()
        } else {
            return None;
        };
        Some((key.clone(), name))
    }

    /// Actual selected field keys, when the source has them.
    pub fn selected_keys(&self) -> Option<&[RawKey]> {
        self.0.selected_keys.as_deref()
    }

    /// Actual zero-based selected field positions.
    pub fn selected_indices(&self) -> Option<&[usize]> {
        self.0.selected_indices.as_deref()
    }

    /// Original logical source shape.
    pub fn source_shape(&self) -> &[usize] {
        &self.0.source_shape
    }

    /// Actual selected shape before any further projection.
    pub fn selected_shape(&self) -> &[usize] {
        &self.0.selected_shape
    }

    pub(crate) fn member_shape(&self) -> &[usize] {
        self.0
            .relation_shape
            .as_deref()
            .unwrap_or(&self.0.selected_shape)
    }

    fn selected_count(&self) -> Option<usize> {
        self.member_shape()
            .iter()
            .try_fold(1usize, |n, &size| n.checked_mul(size))
    }
}

/// Original source and actual source-row relation of a native vector.
#[derive(Debug, Clone)]
pub(crate) struct VectorSource {
    info: DataSourceInfo,
    projection: Option<Arc<SourceProjection>>,
}

#[derive(Debug, Clone)]
enum SlotProjection {
    Identity,
    Repeated(usize),
    Cycled(usize),
    Gathered(Arc<[usize]>),
}

#[derive(Debug, Clone)]
struct SourceProjection {
    slots: SlotProjection,
    original_nulls: bool,
    field_nulls: Option<Arc<[bool]>>,
    distinct_rows: bool,
    field_axis_keys: Option<Arc<super::RawKeyValues>>,
}

impl Default for SourceProjection {
    fn default() -> Self {
        Self {
            slots: SlotProjection::Identity,
            original_nulls: false,
            field_nulls: None,
            distinct_rows: true,
            field_axis_keys: None,
        }
    }
}

impl VectorSource {
    pub(crate) fn direct(len: usize) -> Self {
        Self::new(DataSourceInfo::direct(vec![len]))
    }

    pub(crate) fn direct_nullable(len: usize, has_nulls: bool) -> Self {
        let mut source = Self::direct(len);
        if has_nulls {
            source.projection_mut().original_nulls = true;
        }
        source
    }

    pub(crate) fn new(info: DataSourceInfo) -> Self {
        Self {
            info,
            projection: None,
        }
    }

    fn projection_mut(&mut self) -> &mut SourceProjection {
        Arc::make_mut(
            self.projection
                .get_or_insert_with(|| Arc::new(SourceProjection::default())),
        )
    }

    pub(crate) fn repeated(info: DataSourceInfo, copies: usize, len: usize) -> Result<Self> {
        if copies == 0 || info.selected_count().and_then(|n| n.checked_mul(copies)) != Some(len) {
            return Err(Error::Data(
                "captured source shape and repetition must match the actual value count".into(),
            ));
        }
        let mut source = Self::new(info);
        if copies != 1 {
            let projection = source.projection_mut();
            projection.slots = SlotProjection::Repeated(copies);
            projection.distinct_rows = false;
        }
        Ok(source)
    }

    pub(crate) fn cycled(info: DataSourceInfo, len: usize) -> Result<Self> {
        let count = info.selected_count().unwrap_or(0);
        if count == 0 || !len.is_multiple_of(count) {
            return Err(Error::Data(
                "captured column identity count must divide the actual value count".into(),
            ));
        }
        let field_axis_keys = complete_field_axis(&info)?;
        Ok(Self {
            info,
            projection: Some(super::source::source_arc(SourceProjection {
                slots: SlotProjection::Cycled(count),
                distinct_rows: false,
                field_axis_keys,
                ..SourceProjection::default()
            })?),
        })
    }

    pub(crate) fn gathered(info: DataSourceInfo, slots: Vec<usize>, len: usize) -> Result<Self> {
        if slots.len() != len
            || !info
                .selected_count()
                .is_some_and(|count| slots.iter().all(|&slot| slot < count))
        {
            return Err(Error::Data(
                "captured source slots must match the actual value domain".into(),
            ));
        }
        let distinct_rows = info.member_shape().len() == 1 && distinct_slots(&slots)?;
        let field_axis_keys = complete_field_axis(&info)?;
        Ok(Self {
            info,
            projection: Some(super::source::source_arc(SourceProjection {
                slots: SlotProjection::Gathered(slots.into()),
                distinct_rows,
                field_axis_keys,
                ..SourceProjection::default()
            })?),
        })
    }

    pub(crate) fn info(&self) -> &DataSourceInfo {
        &self.info
    }

    pub(crate) fn slot(&self, index: usize) -> usize {
        match self
            .projection
            .as_deref()
            .map(|projection| &projection.slots)
        {
            None | Some(SlotProjection::Identity) => index,
            Some(SlotProjection::Repeated(copies)) => index / copies,
            Some(SlotProjection::Cycled(count)) => index % count,
            Some(SlotProjection::Gathered(slots)) => slots[index],
        }
    }

    pub(crate) fn column_cycle(&self) -> Option<usize> {
        match &self.projection.as_deref()?.slots {
            SlotProjection::Cycled(columns) => Some(*columns),
            _ => None,
        }
    }

    pub(crate) fn row_repetition(&self) -> Option<usize> {
        match &self.projection.as_deref()?.slots {
            SlotProjection::Repeated(copies) => Some(*copies),
            _ => None,
        }
    }

    pub(crate) fn mark_rows(&mut self) {
        if self.is_identity() {
            self.projection_mut().slots = SlotProjection::Repeated(1);
        }
    }

    pub(crate) fn is_identity(&self) -> bool {
        self.projection
            .as_deref()
            .is_none_or(|entry| matches!(entry.slots, SlotProjection::Identity))
    }

    pub(crate) fn has_distinct_rows(&self) -> bool {
        self.info.member_shape().len() == 1
            && self
                .projection
                .as_deref()
                .is_none_or(|entry| entry.distinct_rows)
    }

    pub(crate) fn field_axis_keys(&self) -> Option<&super::RawKeyValues> {
        self.projection.as_deref()?.field_axis_keys.as_deref()
    }

    /// Retain captured presence before selection or interleaving can hide
    /// which original field actually contained missing values.
    pub(crate) fn with_original_validity(
        mut self,
        length: usize,
        has_nulls: bool,
        is_valid: impl Fn(usize) -> bool,
    ) -> Result<Self> {
        if !has_nulls && self.projection.is_none() {
            return Ok(self);
        }
        let mut field_nulls = None;
        if has_nulls && self.info.selected_keys().is_some() {
            if let [_, width] = self.info.member_shape() {
                let mut fields = Vec::new();
                super::source::reserve_source(&mut fields, *width)?;
                fields.resize(*width, false);
                crate::operation::check()?;
                for slot in 0..length {
                    if !is_valid(slot) {
                        fields[self.slot(slot) % width] = true;
                    }
                }
                field_nulls = Some(fields.into());
            }
        }
        let projection = self.projection_mut();
        projection.original_nulls = has_nulls;
        projection.field_nulls = field_nulls;
        Ok(self)
    }

    pub(crate) fn original_has_nulls(&self, field: Option<usize>) -> bool {
        let Some(projection) = self.projection.as_deref() else {
            return false;
        };
        field
            .and_then(|field| projection.field_nulls.as_ref()?.get(field).copied())
            .unwrap_or(projection.original_nulls)
    }

    pub(crate) fn retain_original_validity(&mut self, source: &Self) {
        if let Some(original) = source.projection.as_deref() {
            let projection = self.projection_mut();
            projection.original_nulls = original.original_nulls;
            projection.field_nulls.clone_from(&original.field_nulls);
            projection.distinct_rows &= original.distinct_rows;
            projection
                .field_axis_keys
                .clone_from(&original.field_axis_keys);
        }
    }

    pub(crate) fn select(&self, indices: &[usize]) -> Result<Self> {
        let slots =
            super::source::collect_source(indices.iter().map(|&index| Ok(self.slot(index))))?;
        let distinct_rows = self.has_distinct_rows() && distinct_slots(&slots)?;
        let mut projection = self.projection.as_deref().cloned().unwrap_or_default();
        projection.slots = SlotProjection::Gathered(slots.into());
        projection.distinct_rows = distinct_rows;
        Ok(Self {
            info: self.info.clone(),
            projection: Some(super::source::source_arc(projection)?),
        })
    }
}

fn complete_field_axis(info: &DataSourceInfo) -> Result<Option<Arc<super::RawKeyValues>>> {
    if info.generation() != Some(BindingGeneration::ColumnNames) && info.grid_axis() != Some(1) {
        return Ok(None);
    }
    let (Some(keys), Some(&width)) = (info.selected_keys(), info.source_shape().get(1)) else {
        return Ok(None);
    };
    if keys.len() != width {
        // Unselected fields have no captured keys.
        return Ok(None);
    }
    let mut ordered = Vec::new();
    super::source::reserve_source(&mut ordered, width)?;
    ordered.resize(width, None);
    for (slot, key) in keys.iter().enumerate() {
        let position = info
            .selected_indices()
            .and_then(|indices| indices.get(slot))
            .copied()
            .unwrap_or(slot);
        let Some(target) = ordered.get_mut(position) else {
            return Ok(None);
        };
        if target.replace(key.clone()).is_some() {
            return Ok(None);
        }
    }
    Ok(Some(Arc::new(super::RawKeyValues::nullable(
        "field", ordered,
    )?)))
}

fn distinct_slots(slots: &[usize]) -> Result<bool> {
    crate::operation::check()?;
    if slots.windows(2).all(|pair| pair[0] < pair[1]) {
        return Ok(true);
    }
    let mut sorted = super::source::collect_source(slots.iter().copied().map(Ok))?;
    super::source::sort_source_by(&mut sorted, usize::cmp)?;
    Ok(sorted.windows(2).all(|pair| pair[0] != pair[1]))
}

/// Native value bridge for attaching a verified adapter source capture.
#[doc(hidden)]
pub trait CapturedValue: Sized {
    /// Length of the actual captured vector.
    fn len(&self) -> usize;
    /// Whether this vector is empty.
    fn is_empty(&self) -> bool {
        self.len() == 0
    }
    /// Retain an explicit row-scoped adoption, even when it currently has one column.
    #[must_use]
    fn row_scoped(self) -> Self;
    /// Attach the verified source selection and row relation.
    fn retain(
        self,
        source: DataSourceInfo,
        copies: usize,
        field: Option<(RawKey, String)>,
    ) -> Result<Self>;
}

macro_rules! captured_values {
    ($($ty:ident),+) => {$(
        impl CapturedValue for $ty {
            fn len(&self) -> usize { self.len() }

            fn row_scoped(self) -> Self {
                self.with_row_scope()
            }

            fn retain(
                self, source: DataSourceInfo, copies: usize, field: Option<(RawKey, String)>,
            ) -> Result<Self> {
                let value = self.with_repeated_source(source, copies)?;
                Ok(if let Some((key, name)) = field {
                    value.with_field_key(key, name)
                } else {
                    value
                })
            }
        }
    )+};
}
captured_values!(NumericValues, CategoryValues, BooleanValues);

impl CapturedValue for super::SourceRows {
    fn len(&self) -> usize {
        self.len()
    }

    fn row_scoped(self) -> Self {
        self
    }

    fn retain(
        self,
        source: DataSourceInfo,
        copies: usize,
        _: Option<(RawKey, String)>,
    ) -> Result<Self> {
        if copies != 1 {
            return Err(Error::Data(
                "source row identities cannot be repeated".into(),
            ));
        }
        self.with_source(source)
    }
}

impl CapturedValue for super::RawKeyValues {
    fn len(&self) -> usize {
        self.len()
    }

    fn row_scoped(self) -> Self {
        let mut source = self.vector_source().clone();
        source.mark_rows();
        self.with_vector_source(source)
    }

    fn retain(
        self,
        source: DataSourceInfo,
        copies: usize,
        _: Option<(RawKey, String)>,
    ) -> Result<Self> {
        let len = self.len();
        let source = VectorSource::repeated(source, copies, len)?.with_original_validity(
            len,
            self.has_nulls(),
            |slot| self.is_valid(slot) == Some(true),
        )?;
        Ok(self.with_vector_source(source))
    }
}

impl CapturedValue for AxisValues {
    fn len(&self) -> usize {
        self.len()
    }

    fn row_scoped(self) -> Self {
        match self {
            Self::Numeric(values) => Self::Numeric(values.row_scoped()),
            Self::Category(values) => Self::Category(values.row_scoped()),
            Self::Keys(values) => Self::Keys(values.row_scoped()),
        }
    }

    fn retain(
        self,
        source: DataSourceInfo,
        copies: usize,
        field: Option<(RawKey, String)>,
    ) -> Result<Self> {
        Ok(match self {
            Self::Numeric(values) => Self::Numeric(values.retain(source, copies, field)?),
            Self::Category(values) => Self::Category(values.retain(source, copies, field)?),
            Self::Keys(values) => Self::Keys(values.retain(source, copies, field)?),
        })
    }
}