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
//! Immutable Rust-native values accepted by plot constructors.

use std::collections::{HashMap, HashSet};
use std::sync::Arc;

use crate::data::source::{collect_source, copy_source_string, reserve_source};
use crate::data::{binding::VectorSource, DataSourceInfo, RawKey};
use crate::Error;

/// Original source-row identities attached once to a plot's aligned values.
#[derive(Debug, Clone)]
pub struct SourceRows {
    rows: Arc<[usize]>,
    source: VectorSource,
}

impl SourceRows {
    /// Construct unique source-row identities.
    pub fn new(rows: impl IntoIterator<Item = usize>) -> Result<Self, Error> {
        let rows = collect_source(rows.into_iter().map(Ok))?;
        let mut seen = HashSet::new();
        crate::operation::check()?;
        seen.try_reserve(rows.len())
            .map_err(|error| Error::Data(format!("source-row identity storage: {error}").into()))?;
        for &row in &rows {
            crate::operation::check()?;
            if !seen.insert(row) {
                return Err(Error::Data(
                    format!("source-row identities must be unique; found duplicate {row}").into(),
                ));
            }
        }
        crate::operation::check()?;
        Ok(Self {
            source: VectorSource::direct(rows.len()),
            rows: rows.into(),
        })
    }

    /// Retain the real source of the exact identity column or rectangle.
    #[doc(hidden)]
    pub fn with_source(mut self, source: DataSourceInfo) -> crate::Result<Self> {
        self.source = VectorSource::repeated(source, 1, self.len())?;
        Ok(self)
    }

    /// Original captured identity source.
    #[doc(hidden)]
    pub fn get_source(&self) -> &DataSourceInfo {
        self.source.info()
    }

    pub(crate) fn vector_source(&self) -> &VectorSource {
        &self.source
    }

    /// Number of represented rows.
    #[must_use]
    pub fn len(&self) -> usize {
        self.rows.len()
    }

    /// Whether no rows are represented.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.rows.is_empty()
    }

    /// Borrow the original source identifiers in their supplied order.
    #[must_use]
    pub fn as_slice(&self) -> &[usize] {
        &self.rows
    }

    /// Read one source identifier by its logical slot.
    #[must_use]
    pub fn get(&self, index: usize) -> Option<usize> {
        self.rows.get(index).copied()
    }

    /// Iterate the actual source identifiers, without substituting row positions.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = usize> + '_ {
        self.rows.iter().copied()
    }
}

impl PartialEq for SourceRows {
    fn eq(&self, other: &Self) -> bool {
        self.rows == other.rows
    }
}

impl Eq for SourceRows {}

#[derive(Debug, Clone, PartialEq, Eq)]
enum Validity {
    All,
    Bitmap(Arc<[u64]>),
}

impl Validity {
    fn from_flags(flags: &[bool]) -> Self {
        if flags.iter().all(|valid| *valid) {
            return Self::All;
        }
        Self::bitmap(flags, vec![0_u64; flags.len().div_ceil(64)])
    }

    fn try_from_flags(flags: &[bool]) -> crate::Result<Self> {
        crate::operation::check()?;
        if flags.iter().filter(|&&valid| valid).count() == flags.len() {
            return Ok(Self::All);
        }
        let count = flags.len().div_ceil(64);
        let mut words = Vec::new();
        reserve_source(&mut words, count)?;
        words.resize(count, 0);
        crate::operation::check()?;
        Ok(Self::bitmap(flags, words))
    }

    fn bitmap(flags: &[bool], mut words: Vec<u64>) -> Self {
        for (index, valid) in flags.iter().copied().enumerate() {
            if valid {
                words[index / 64] |= 1_u64 << (index % 64);
            }
        }
        Self::Bitmap(words.into())
    }

    fn is_valid(&self, index: usize) -> bool {
        match self {
            Self::All => true,
            Self::Bitmap(words) => words
                .get(index / 64)
                .is_some_and(|word| word & (1_u64 << (index % 64)) != 0),
        }
    }
}

/// Named nullable numeric values stored as immutable native `f64` data.
#[derive(Debug, Clone)]
pub struct NumericValues {
    name: Arc<str>,
    values: Arc<[f64]>,
    validity: Validity,
    field_key: Option<Arc<(RawKey, Arc<str>)>>,
    source: VectorSource,
}

impl NumericValues {
    pub(crate) fn with_value_name(mut self, name: &str) -> Self {
        self.name = Arc::from(name);
        self.field_key = None;
        self
    }
    /// Construct complete numeric values.
    #[must_use]
    pub fn new(name: impl Into<String>, values: impl IntoIterator<Item = f64>) -> Self {
        let values = values.into_iter().collect::<Vec<_>>();
        Self {
            name: Arc::from(name.into()),
            source: VectorSource::direct(values.len()),
            values: values.into(),
            validity: Validity::All,
            field_key: None,
        }
    }

    /// Construct nullable numeric values without conflating nulls with `NaN`.
    #[must_use]
    pub fn nullable(
        name: impl Into<String>,
        values: impl IntoIterator<Item = Option<f64>>,
    ) -> Self {
        let values = values.into_iter().collect::<Vec<_>>();
        let validity =
            Validity::from_flags(&values.iter().map(Option::is_some).collect::<Vec<_>>());
        let values = values
            .into_iter()
            .map(|value| value.unwrap_or(0.0))
            .collect::<Vec<_>>();
        Self {
            name: Arc::from(name.into()),
            source: VectorSource::direct_nullable(
                values.len(),
                !matches!(&validity, Validity::All),
            ),
            values: values.into(),
            validity,
            field_key: None,
        }
    }

    /// Semantic value name used for inferred labels and diagnostics.
    #[must_use]
    pub fn name(&self) -> &str {
        self.field_key
            .as_deref()
            .map_or(&self.name, |(_, name)| name)
    }

    /// Renderer field name retained by the native binding.
    #[doc(hidden)]
    pub fn raw_name(&self) -> &str {
        &self.name
    }

    pub(crate) fn raw_field(&self) -> crate::data::category::RawField {
        let key = self
            .field_key()
            .cloned()
            .unwrap_or_else(|| RawKey::from(self.raw_name()));
        crate::data::category::RawField::from_key(Arc::clone(&self.name), key)
    }

    /// Attach the actual original field identity, independently of its renderer key.
    #[doc(hidden)]
    #[must_use]
    pub fn with_field_key(mut self, key: RawKey, name: impl Into<String>) -> Self {
        self.field_key = Some(Arc::new((key, Arc::from(name.into()))));
        self
    }

    /// Original field key, if this variable has one.
    #[doc(hidden)]
    pub fn field_key(&self) -> Option<&RawKey> {
        self.field_key.as_deref().map(|(key, _)| key)
    }

    /// Attach the actual source selection at the binding boundary.
    #[doc(hidden)]
    pub fn with_source(self, source: DataSourceInfo) -> crate::Result<Self> {
        self.with_repeated_source(source, 1)
    }

    /// Retain the original row relation for a row-major repeated binding.
    #[doc(hidden)]
    pub fn with_repeated_source(
        mut self,
        source: DataSourceInfo,
        copies: usize,
    ) -> crate::Result<Self> {
        self.source = VectorSource::repeated(source, copies, self.len())?.with_original_validity(
            self.len(),
            self.has_nulls(),
            |slot| self.validity.is_valid(slot),
        )?;
        Ok(self)
    }

    /// Attach a verified logical selection of original source slots.
    #[doc(hidden)]
    pub fn with_source_slots(
        mut self,
        source: DataSourceInfo,
        slots: Vec<usize>,
    ) -> crate::Result<Self> {
        self.source = VectorSource::gathered(source, slots, self.len())?.with_original_validity(
            self.len(),
            self.has_nulls(),
            |slot| self.validity.is_valid(slot),
        )?;
        Ok(self)
    }

    /// Borrow the original source selection.
    #[doc(hidden)]
    pub fn get_source(&self) -> &DataSourceInfo {
        self.source.info()
    }

    pub(crate) fn with_row_scope(mut self) -> Self {
        self.source.mark_rows();
        self
    }

    pub(crate) fn vector_source(&self) -> &VectorSource {
        &self.source
    }

    pub(crate) fn has_nulls(&self) -> bool {
        !matches!(self.validity, Validity::All)
    }

    /// Original source-row relation for an actual logical slot.
    #[doc(hidden)]
    pub fn source_slot(&self, index: usize) -> Option<usize> {
        (index < self.len()).then(|| self.source.slot(index))
    }

    pub(crate) fn select(&self, indices: &[usize]) -> crate::Result<Self> {
        let values = collect_source(indices.iter().map(|&index| {
            self.values.get(index).copied().ok_or_else(|| {
                Error::Data(format!("numeric selection index {index} is out of bounds").into())
            })
        }))?;
        let validity = if matches!(self.validity, Validity::All) {
            Validity::All
        } else {
            let flags = collect_source(
                indices
                    .iter()
                    .map(|&index| Ok(self.validity.is_valid(index))),
            )?;
            Validity::try_from_flags(&flags)?
        };
        crate::operation::check()?;
        Ok(Self {
            name: self.name.clone(),
            values: values.into(),
            validity,
            field_key: self.field_key.clone(),
            source: self.source.select(indices)?,
        })
    }

    /// Number of values, including nulls.
    #[must_use]
    pub fn len(&self) -> usize {
        self.values.len()
    }

    /// Whether no values are present.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }

    /// Read one original numeric slot; outer None is out of bounds, and inner
    /// None is missing. Present NaN, infinity and signed zero are retained.
    #[must_use]
    pub fn get(&self, row: usize) -> Option<Option<f64>> {
        self.values
            .get(row)
            .map(|value| self.validity.is_valid(row).then_some(*value))
    }

    /// Iterate the original slots, including missing entries.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = Option<f64>> + '_ {
        (0..self.len()).map(|row| self.get(row).expect("in-bounds source slot"))
    }

    /// Query the actual validity bit independently of numerical finiteness.
    #[must_use]
    pub fn is_valid(&self, row: usize) -> Option<bool> {
        (row < self.len()).then(|| self.validity.is_valid(row))
    }
}

impl PartialEq for NumericValues {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
            && self.field_key == other.field_key
            && self.len() == other.len()
            && self
                .iter()
                .map(|value| value.map(f64::to_bits))
                .eq(other.iter().map(|value| value.map(f64::to_bits)))
    }
}

impl Eq for NumericValues {}

/// Named nullable categorical values stored with stable dictionary encoding.
#[derive(Debug, Clone)]
pub struct CategoryValues {
    name: Arc<str>,
    levels: Arc<[String]>,
    codes: Arc<[u32]>,
    validity: Validity,
    original_keys: Option<Arc<crate::data::KeyValues>>,
    field_key: Option<Arc<(RawKey, Arc<str>)>>,
    source: VectorSource,
}

impl CategoryValues {
    /// Construct complete categorical values in first-observed level order.
    pub fn new<S>(
        name: impl Into<String>,
        values: impl IntoIterator<Item = S>,
    ) -> Result<Self, Error>
    where
        S: Into<String>,
    {
        Self::from_optional(
            name.into(),
            values.into_iter().map(|value| Ok(Some(value.into()))),
        )
    }

    /// Construct nullable categorical values in first-observed level order.
    pub fn nullable<S>(
        name: impl Into<String>,
        values: impl IntoIterator<Item = Option<S>>,
    ) -> Result<Self, Error>
    where
        S: Into<String>,
    {
        Self::from_optional(
            name.into(),
            values.into_iter().map(|value| Ok(value.map(Into::into))),
        )
    }

    fn from_optional(
        name: String,
        values: impl IntoIterator<Item = Result<Option<String>, Error>>,
    ) -> Result<Self, Error> {
        let values = collect_source(values.into_iter())?;
        let mut levels = Vec::new();
        let mut indices = HashMap::new();
        let mut codes = Vec::new();
        let mut valid = Vec::new();
        reserve_source(&mut codes, values.len())?;
        reserve_source(&mut valid, values.len())?;
        for value in values {
            crate::operation::check()?;
            let Some(value) = value else {
                valid.push(false);
                codes.push(0);
                continue;
            };
            valid.push(true);
            let code = if let Some(code) = indices.get(&value).copied() {
                code
            } else {
                let code = u32::try_from(levels.len()).map_err(|_| {
                    Error::Data(
                        format!(
                            "categorical values {name:?} exceed the supported distinct-level count"
                        )
                        .into(),
                    )
                })?;
                reserve_source(&mut levels, 1)?;
                crate::operation::check()?;
                indices.try_reserve(1).map_err(|error| {
                    Error::Data(format!("category dictionary storage: {error}").into())
                })?;
                indices.insert(copy_source_string(&value)?, code);
                levels.push(value);
                code
            };
            codes.push(code);
        }
        let validity = Validity::try_from_flags(&valid)?;
        crate::operation::check()?;
        Ok(Self {
            name: Arc::from(name),
            levels: levels.into(),
            source: VectorSource::direct_nullable(codes.len(), !matches!(validity, Validity::All)),
            codes: codes.into(),
            validity,
            original_keys: None,
            field_key: None,
        })
    }

    /// Semantic value name used for inferred labels and diagnostics.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Number of values, including nulls.
    #[must_use]
    pub fn len(&self) -> usize {
        self.codes.len()
    }

    /// Whether no values are present.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.codes.is_empty()
    }

    /// Read one original categorical slot, distinguishing missing values from
    /// an out-of-bounds slot and from a present empty string.
    #[must_use]
    pub fn get(&self, row: usize) -> Option<Option<&str>> {
        self.codes.get(row).map(|code| {
            if !self.validity.is_valid(row) {
                return None;
            }
            usize::try_from(*code)
                .ok()
                .and_then(|index| self.levels.get(index))
                .map(String::as_str)
        })
    }

    /// Iterate the original categorical slots, not internal dictionary codes.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = Option<&str>> + '_ {
        (0..self.len()).map(|row| self.get(row).expect("in-bounds source slot"))
    }

    /// Query the original validity bit.
    #[must_use]
    pub fn is_valid(&self, row: usize) -> Option<bool> {
        (row < self.len()).then(|| self.validity.is_valid(row))
    }

    /// Distinct present categories in first-observed order.
    #[must_use]
    pub fn levels(&self) -> &[String] {
        &self.levels
    }

    /// Retain the complete non-string source identities for a generated
    /// categorical binding. The string projection remains the renderer's
    /// matching identity, not the raw value returned to a caller.
    #[doc(hidden)]
    pub fn with_key_values(mut self, keys: crate::data::KeyValues) -> Result<Self, Error> {
        if self.len() != keys.len()
            || (0..self.len()).any(|index| self.is_valid(index) != keys.is_valid(index))
        {
            return Err(Error::Data(
                "raw keys must align with their category projection".into(),
            ));
        }
        let key_count = match &keys {
            crate::data::KeyValues::Strings(values) => values.levels().len(),
            crate::data::KeyValues::Raw(values) => values.levels().len(),
        };
        let mut first_slots = Vec::new();
        reserve_source(&mut first_slots, self.levels.len())?;
        first_slots.resize(self.levels.len(), None);
        // Each projected level denotes exactly one original identity, and
        // distinct levels must denote distinct identities.
        let aligned = key_count == self.levels.len()
            && self.codes.iter().enumerate().all(|(row, &code)| {
                if !self.validity.is_valid(row) {
                    return true;
                }
                let first = *first_slots[code as usize].get_or_insert(row);
                match &keys {
                    crate::data::KeyValues::Strings(values) => values.get(first) == values.get(row),
                    crate::data::KeyValues::Raw(values) => values.get(first) == values.get(row),
                }
            });
        if !aligned {
            return Err(Error::Data(
                "category projection must preserve the distinct original keys".into(),
            ));
        }
        let source = match &keys {
            crate::data::KeyValues::Strings(values) => values.vector_source(),
            crate::data::KeyValues::Raw(values) => values.vector_source(),
        };
        if self.source.info() == source.info() {
            self.source.retain_original_validity(source);
        }
        self.original_keys = Some(Arc::new(keys));
        Ok(self)
    }

    /// Retain the original field key and its author-visible name when the
    /// adapter uses an internal matching identity.
    #[doc(hidden)]
    #[must_use]
    pub fn with_field_key(mut self, key: crate::data::RawKey, name: impl Into<String>) -> Self {
        self.field_key = Some(Arc::new((key, Arc::from(name.into()))));
        self
    }

    /// Borrow the original human-authored field name.
    #[doc(hidden)]
    pub fn original_name(&self) -> &str {
        self.field_key
            .as_deref()
            .map_or(&self.name, |(_, name)| name)
    }

    /// Original field key, if this variable has one.
    #[doc(hidden)]
    pub fn field_key(&self) -> Option<&RawKey> {
        self.field_key.as_deref().map(|(key, _)| key)
    }

    /// Attach the actual source selection at binding.
    #[doc(hidden)]
    pub fn with_source(self, source: DataSourceInfo) -> crate::Result<Self> {
        self.with_repeated_source(source, 1)
    }

    /// Retain the original row relation for a row-major repeated binding.
    #[doc(hidden)]
    pub fn with_repeated_source(
        mut self,
        source: DataSourceInfo,
        copies: usize,
    ) -> crate::Result<Self> {
        self.source = VectorSource::repeated(source, copies, self.len())?.with_original_validity(
            self.len(),
            self.has_nulls(),
            |slot| self.validity.is_valid(slot),
        )?;
        Ok(self)
    }

    /// Attach a verified logical selection of original source slots.
    #[doc(hidden)]
    pub fn with_source_slots(
        mut self,
        source: DataSourceInfo,
        slots: Vec<usize>,
    ) -> crate::Result<Self> {
        self.source = VectorSource::gathered(source, slots, self.len())?.with_original_validity(
            self.len(),
            self.has_nulls(),
            |slot| self.validity.is_valid(slot),
        )?;
        Ok(self)
    }

    /// Retain the actual repeating selected-column identity relation.
    #[doc(hidden)]
    pub fn with_cycled_source(mut self, source: DataSourceInfo) -> crate::Result<Self> {
        self.source = VectorSource::cycled(source, self.len())?.with_original_validity(
            self.len(),
            self.has_nulls(),
            |slot| self.validity.is_valid(slot),
        )?;
        Ok(self)
    }

    /// Borrow the originally captured source selection.
    #[doc(hidden)]
    pub fn get_source(&self) -> &DataSourceInfo {
        self.source.info()
    }

    pub(crate) fn with_row_scope(mut self) -> Self {
        self.source.mark_rows();
        self
    }

    pub(crate) fn vector_source(&self) -> &VectorSource {
        &self.source
    }

    pub(crate) fn has_nulls(&self) -> bool {
        !matches!(self.validity, Validity::All)
    }

    /// Original source row for a logical slot.
    #[doc(hidden)]
    pub fn source_slot(&self, index: usize) -> Option<usize> {
        (index < self.len()).then(|| self.source.slot(index))
    }

    pub(crate) fn select(&self, indices: &[usize]) -> crate::Result<Self> {
        let mut values = Self::from_optional(
            copy_source_string(self.name())?,
            indices.iter().map(|&index| {
                let value = self.get(index).ok_or_else(|| {
                    Error::Data(format!("category selection index {index} is out of bounds").into())
                })?;
                value.map(copy_source_string).transpose()
            }),
        )?;
        values.field_key.clone_from(&self.field_key);
        values.source = self.source.select(indices)?;
        values.original_keys = self
            .original_keys
            .as_ref()
            .map(|keys| keys.select(indices).map(Arc::new))
            .transpose()?;
        Ok(values)
    }

    pub(crate) fn original_field(&self) -> crate::data::RawKey {
        self.field_key.as_deref().map_or_else(
            || crate::data::RawKey::from(self.name()),
            |(key, _)| key.clone(),
        )
    }

    /// Assign the semantic field name while retaining its actual key values.
    #[doc(hidden)]
    #[must_use]
    pub fn with_field_name(mut self, name: &str) -> Self {
        if self.name() != name {
            self.name = Arc::from(name);
        }
        self.field_key = None;
        self
    }

    /// Read the actual original category binding. Generated non-string fields
    /// expose their original keys rather than private category projections.
    #[must_use]
    pub fn key_values(&self) -> crate::data::KeyValues {
        if let Some(keys) = &self.original_keys {
            return match keys.as_ref() {
                crate::data::KeyValues::Strings(values) => {
                    let mut values = values.clone();
                    values.source = self.source.clone();
                    values.field_key.clone_from(&self.field_key);
                    crate::data::KeyValues::Strings(values)
                }
                crate::data::KeyValues::Raw(values) => crate::data::KeyValues::Raw(
                    values
                        .clone()
                        .with_name(self.original_name())
                        .with_vector_source(self.source.clone()),
                ),
            };
        }
        let mut values = self.clone();
        if let Some((_, name)) = values.field_key.as_deref() {
            values.name = Arc::clone(name);
        }
        crate::data::KeyValues::Strings(values)
    }

    /// Resolve a renderer level to its actual original category identity.
    pub(crate) fn key_for_level(&self, level: &str) -> Option<RawKey> {
        if self.original_keys.is_none() {
            return self
                .levels()
                .iter()
                .any(|value| value == level)
                .then(|| RawKey::from(level));
        }
        self.key_at(self.iter().position(|value| value == Some(level))?)
    }

    pub(crate) fn key_at(&self, slot: usize) -> Option<RawKey> {
        match self.original_keys.as_deref() {
            None => self.get(slot)?.map(RawKey::from),
            Some(crate::data::KeyValues::Strings(values)) => values.get(slot)?.map(RawKey::from),
            Some(crate::data::KeyValues::Raw(values)) => values.get(slot)?.cloned(),
        }
    }

    pub(crate) fn raw_field(&self) -> crate::data::category::RawField {
        crate::data::category::RawField::from_key(Arc::clone(&self.name), self.original_field())
    }

    pub(crate) fn same_level_key(&self, level: &str, other: &Self, other_level: &str) -> bool {
        if self.original_keys.is_none() && other.original_keys.is_none() {
            level == other_level
        } else {
            self.key_for_level(level) == other.key_for_level(other_level)
        }
    }

    pub(crate) fn raw_category(
        &self,
        level: &str,
    ) -> crate::Result<crate::data::category::RawCategory> {
        use crate::data::category::{shared_text, RawCategory};
        let key = self.key_for_level(level).ok_or_else(|| {
            Error::Render(format!("guide level {level:?} has no original category").into())
        })?;
        if matches!(&key, RawKey::String(value) if value == level) {
            RawCategory::new(level)
        } else {
            Ok(RawCategory::from_key(shared_text(level)?, key))
        }
    }
}

impl PartialEq for CategoryValues {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
            && self.levels == other.levels
            && self.codes == other.codes
            && self.validity == other.validity
            && self.original_keys == other.original_keys
            && self.field_key == other.field_key
    }
}

impl Eq for CategoryValues {}

/// Named nullable Boolean values.
#[derive(Debug, Clone)]
pub struct BooleanValues {
    name: Arc<str>,
    values: Arc<[bool]>,
    validity: Validity,
    field_key: Option<Arc<(RawKey, Arc<str>)>>,
    source: VectorSource,
}

impl BooleanValues {
    pub(crate) fn with_value_name(mut self, name: &str) -> Self {
        self.name = Arc::from(name);
        self.field_key = None;
        self
    }
    /// Construct complete Boolean values.
    #[must_use]
    pub fn new(name: impl Into<String>, values: impl IntoIterator<Item = bool>) -> Self {
        let values = values.into_iter().collect::<Vec<_>>();
        Self {
            name: Arc::from(name.into()),
            field_key: None,
            source: VectorSource::direct(values.len()),
            values: values.into(),
            validity: Validity::All,
        }
    }

    /// Construct nullable Boolean values.
    #[must_use]
    pub fn nullable(
        name: impl Into<String>,
        values: impl IntoIterator<Item = Option<bool>>,
    ) -> Self {
        let values = values.into_iter().collect::<Vec<_>>();
        let validity =
            Validity::from_flags(&values.iter().map(Option::is_some).collect::<Vec<_>>());
        let values = values
            .into_iter()
            .map(|value| value.unwrap_or(false))
            .collect::<Vec<_>>();
        Self {
            name: Arc::from(name.into()),
            field_key: None,
            source: VectorSource::direct_nullable(
                values.len(),
                !matches!(&validity, Validity::All),
            ),
            values: values.into(),
            validity,
        }
    }

    /// Semantic value name used for diagnostics.
    #[must_use]
    pub fn name(&self) -> &str {
        self.field_key
            .as_deref()
            .map_or(&self.name, |(_, name)| name)
    }

    /// Retain the original Boolean field's author-visible identity.
    #[doc(hidden)]
    #[must_use]
    pub fn with_field_key(mut self, key: RawKey, name: impl Into<String>) -> Self {
        self.field_key = Some(Arc::new((key, Arc::from(name.into()))));
        self
    }

    /// Original field key, if selected from a named source.
    #[doc(hidden)]
    pub fn field_key(&self) -> Option<&RawKey> {
        self.field_key.as_deref().map(|(key, _)| key)
    }

    /// Attach the actual source selection at binding.
    #[doc(hidden)]
    pub fn with_source(self, source: DataSourceInfo) -> crate::Result<Self> {
        self.with_repeated_source(source, 1)
    }

    /// Retain the original row relation for a row-major repeated binding.
    #[doc(hidden)]
    pub fn with_repeated_source(
        mut self,
        source: DataSourceInfo,
        copies: usize,
    ) -> crate::Result<Self> {
        self.source = VectorSource::repeated(source, copies, self.len())?.with_original_validity(
            self.len(),
            self.has_nulls(),
            |slot| self.validity.is_valid(slot),
        )?;
        Ok(self)
    }

    /// Attach a verified logical selection of original source slots.
    #[doc(hidden)]
    pub fn with_source_slots(
        mut self,
        source: DataSourceInfo,
        slots: Vec<usize>,
    ) -> crate::Result<Self> {
        self.source = VectorSource::gathered(source, slots, self.len())?.with_original_validity(
            self.len(),
            self.has_nulls(),
            |slot| self.validity.is_valid(slot),
        )?;
        Ok(self)
    }

    /// Borrow the originally captured source selection.
    #[doc(hidden)]
    pub fn get_source(&self) -> &DataSourceInfo {
        self.source.info()
    }

    pub(crate) fn with_row_scope(mut self) -> Self {
        self.source.mark_rows();
        self
    }

    pub(crate) fn vector_source(&self) -> &VectorSource {
        &self.source
    }

    pub(crate) fn has_nulls(&self) -> bool {
        !matches!(self.validity, Validity::All)
    }

    /// Original source row for a logical slot.
    #[doc(hidden)]
    pub fn source_slot(&self, index: usize) -> Option<usize> {
        (index < self.len()).then(|| self.source.slot(index))
    }

    /// Number of values, including nulls.
    #[must_use]
    pub fn len(&self) -> usize {
        self.values.len()
    }

    /// Whether no values are present.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }

    /// Read one original Boolean slot; missing is distinct from false.
    #[must_use]
    pub fn get(&self, row: usize) -> Option<Option<bool>> {
        self.values
            .get(row)
            .map(|value| self.validity.is_valid(row).then_some(*value))
    }

    /// Iterate the original Boolean slots.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = Option<bool>> + '_ {
        (0..self.len()).map(|row| self.get(row).expect("in-bounds source slot"))
    }

    /// Query the original validity bit.
    #[must_use]
    pub fn is_valid(&self, row: usize) -> Option<bool> {
        (row < self.len()).then(|| self.validity.is_valid(row))
    }
}

impl PartialEq for BooleanValues {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name && self.values == other.values && self.validity == other.validity
    }
}

impl Eq for BooleanValues {}