Skip to main content

lichtung_plot/data/
key.rs

1//! Complete raw keys and ordered key columns, independent of display aliases.
2
3use std::{
4    hash::{Hash, Hasher},
5    sync::{
6        atomic::{AtomicU64, Ordering},
7        Arc,
8    },
9};
10
11use super::{
12    binding::VectorSource, DataSourceInfo, Date, Duration, ExactInteger, LocalTimestamp, Timestamp,
13};
14mod encoding;
15use crate::{
16    errors::{Diagnostic, DiagnosticKind, ErrorContext, OperationPhase},
17    CategoryValues, Error, Result,
18};
19pub(crate) use encoding::key_bytes;
20
21/// The original identity of a bound external or native key.
22#[derive(Debug, Clone)]
23#[non_exhaustive]
24pub enum RawKey {
25    /// A complete string, without display normalization.
26    String(String),
27    /// An exact integer of arbitrary magnitude.
28    Integer(ExactInteger),
29    /// A Boolean, independent of integer positions.
30    Boolean(bool),
31    /// An original floating-point key with exact binary64 bits.
32    Float(f64),
33    /// A complete, possibly nested tuple key.
34    Tuple(Vec<RawKey>),
35    /// A calendar day.
36    Date(Date),
37    /// An exact instant.
38    Instant(Timestamp),
39    /// An elapsed duration.
40    Duration(Duration),
41    /// A local timestamp with no timezone interpretation.
42    LocalTimestamp(LocalTimestamp),
43    /// A complete interval key.
44    Interval(IntervalKey),
45    /// A captured identity whose external key cannot be transferred exactly.
46    Unavailable(UnavailableKey),
47}
48
49impl From<String> for RawKey {
50    fn from(value: String) -> Self {
51        Self::String(value)
52    }
53}
54impl From<&str> for RawKey {
55    fn from(value: &str) -> Self {
56        Self::String(value.to_owned())
57    }
58}
59
60impl From<&String> for RawKey {
61    fn from(value: &String) -> Self {
62        Self::String(value.clone())
63    }
64}
65
66impl From<ExactInteger> for RawKey {
67    fn from(value: ExactInteger) -> Self {
68        Self::Integer(value)
69    }
70}
71macro_rules! integer_keys {
72    ($($type:ty),+) => {$(
73        impl From<$type> for RawKey {
74            fn from(value:$type)->Self {Self::Integer(value.into())}
75        }
76    )+};
77}
78integer_keys!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize);
79impl From<bool> for RawKey {
80    fn from(value: bool) -> Self {
81        Self::Boolean(value)
82    }
83}
84impl From<f64> for RawKey {
85    fn from(value: f64) -> Self {
86        Self::Float(value)
87    }
88}
89impl<A: Into<RawKey>, B: Into<RawKey>> From<(A, B)> for RawKey {
90    fn from((first, second): (A, B)) -> Self {
91        Self::Tuple(vec![first.into(), second.into()])
92    }
93}
94
95impl PartialEq for RawKey {
96    fn eq(&self, other: &Self) -> bool {
97        match (self, other) {
98            (Self::String(a), Self::String(b)) => a == b,
99            (Self::Integer(a), Self::Integer(b)) => a == b,
100            (Self::Boolean(a), Self::Boolean(b)) => a == b,
101            (Self::Float(a), Self::Float(b)) => a.to_bits() == b.to_bits(),
102            (Self::Tuple(a), Self::Tuple(b)) => a == b,
103            (Self::Date(a), Self::Date(b)) => a == b,
104            (Self::Instant(a), Self::Instant(b)) => a == b,
105            (Self::Duration(a), Self::Duration(b)) => a == b,
106            (Self::LocalTimestamp(a), Self::LocalTimestamp(b)) => a == b,
107            (Self::Interval(a), Self::Interval(b)) => a == b,
108            (Self::Unavailable(a), Self::Unavailable(b)) => a == b,
109            _ => false,
110        }
111    }
112}
113
114impl Eq for RawKey {}
115
116impl Hash for RawKey {
117    fn hash<H: Hasher>(&self, state: &mut H) {
118        std::mem::discriminant(self).hash(state);
119        match self {
120            Self::String(value) => value.hash(state),
121            Self::Integer(value) => value.hash(state),
122            Self::Boolean(value) => value.hash(state),
123            Self::Float(value) => value.to_bits().hash(state),
124            Self::Tuple(value) => value.hash(state),
125            Self::Date(value) => value.hash(state),
126            Self::Instant(value) => value.hash(state),
127            Self::Duration(value) => value.hash(state),
128            Self::LocalTimestamp(value) => value.hash(state),
129            Self::Interval(value) => value.hash(state),
130            Self::Unavailable(value) => value.hash(state),
131        }
132    }
133}
134
135/// Which endpoints of an interval key are included.
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
137pub enum IntervalClosed {
138    /// Left endpoint only.
139    Left,
140    /// Right endpoint only.
141    Right,
142    /// Both endpoints.
143    Both,
144    /// Neither endpoint.
145    Neither,
146}
147
148/// A complete interval identity with exact endpoints and closure.
149#[derive(Debug, Clone, PartialEq, Eq, Hash)]
150pub struct IntervalKey {
151    left: Box<RawKey>,
152    right: Box<RawKey>,
153    closed: IntervalClosed,
154}
155
156impl IntervalKey {
157    /// Capture the endpoints of a validated external interval.
158    pub fn new(left: RawKey, right: RawKey, closed: IntervalClosed) -> Result<Self> {
159        let ordered = match (&left, &right) {
160            (RawKey::Integer(a), RawKey::Integer(b)) => a <= b,
161            (RawKey::Float(a), RawKey::Float(b)) => a <= b,
162            (RawKey::Date(a), RawKey::Date(b)) => a <= b,
163            (RawKey::Duration(a), RawKey::Duration(b)) => a <= b,
164            (RawKey::LocalTimestamp(a), RawKey::LocalTimestamp(b)) => a <= b,
165            (RawKey::Instant(a), RawKey::Instant(b)) => a.unix_ns() <= b.unix_ns(),
166            _ => false,
167        };
168        if !ordered {
169            return Err(Error::Data(
170                "interval key requires compatible ordered endpoints".into(),
171            ));
172        }
173        Ok(Self {
174            left: Box::new(left),
175            right: Box::new(right),
176            closed,
177        })
178    }
179    /// Original left endpoint.
180    pub fn left(&self) -> &RawKey {
181        &self.left
182    }
183    /// Original right endpoint.
184    pub fn right(&self) -> &RawKey {
185        &self.right
186    }
187    /// Original endpoint closure.
188    pub const fn closed(&self) -> IntervalClosed {
189        self.closed
190    }
191}
192
193static NEXT_UNAVAILABLE_KEY: AtomicU64 = AtomicU64::new(0);
194
195/// An immutable identity for an actually bound, non-transferable key.
196#[derive(Debug, Clone, PartialEq, Eq, Hash)]
197pub struct UnavailableKey {
198    identity: u64,
199    reason: Arc<str>,
200}
201
202impl UnavailableKey {
203    /// Capture one unavailable key's identity at the actual binding boundary.
204    #[doc(hidden)]
205    pub fn new(reason: impl Into<String>) -> Result<Self> {
206        let identity = NEXT_UNAVAILABLE_KEY
207            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
208                value.checked_add(1)
209            })
210            .map_err(|_| Error::Data("raw key identity space exhausted".into()))?;
211        Ok(Self {
212            identity,
213            reason: Arc::from(reason.into()),
214        })
215    }
216    pub(crate) fn identity(&self) -> u64 {
217        self.identity
218    }
219
220    /// Why this actual key cannot be transferred.
221    pub fn reason(&self) -> &str {
222        &self.reason
223    }
224}
225
226/// A nullable, owned vector of complete raw keys.
227#[derive(Debug, Clone)]
228pub struct RawKeyValues {
229    name: Arc<str>,
230    codes: Arc<[Option<u32>]>,
231    levels: Arc<[RawKey]>,
232    source: VectorSource,
233}
234
235impl RawKeyValues {
236    /// Capture complete keys in original slot order.
237    pub fn new(name: impl Into<String>, values: impl IntoIterator<Item = RawKey>) -> Result<Self> {
238        Self::nullable(name, values.into_iter().map(Some))
239    }
240
241    /// Capture nullable keys in original slot order.
242    pub fn nullable(
243        name: impl Into<String>,
244        values: impl IntoIterator<Item = Option<RawKey>>,
245    ) -> Result<Self> {
246        let name = name.into();
247        let mut levels = Vec::new();
248        let mut indices = std::collections::HashMap::new();
249        let codes = super::source::collect_source(values.into_iter().map(|value| {
250            let Some(value) = value else { return Ok(None) };
251            if let Some(&index) = indices.get(&value) {
252                return Ok(Some(index));
253            }
254            let index = u32::try_from(levels.len()).map_err(|_| {
255                Error::Data(
256                    format!("raw key column {name:?} exceeds the distinct-key limit").into(),
257                )
258            })?;
259            super::source::reserve_source(&mut levels, 1)?;
260            crate::operation::check()?;
261            indices.try_reserve(1).map_err(|error| {
262                Error::Data(format!("raw key dictionary storage: {error}").into())
263            })?;
264            indices.insert(value.clone(), index);
265            levels.push(value);
266            Ok(Some(index))
267        }))?;
268        crate::operation::check()?;
269        Ok(Self {
270            name: Arc::from(name),
271            source: VectorSource::direct_nullable(codes.len(), codes.iter().any(Option::is_none)),
272            codes: codes.into(),
273            levels: levels.into(),
274        })
275    }
276    /// Semantic column name.
277    pub fn name(&self) -> &str {
278        &self.name
279    }
280    pub(crate) fn with_name(mut self, name: &str) -> Self {
281        self.name = Arc::from(name);
282        self
283    }
284    /// Number of original slots.
285    pub fn len(&self) -> usize {
286        self.codes.len()
287    }
288    /// Whether no slots were supplied.
289    pub fn is_empty(&self) -> bool {
290        self.codes.is_empty()
291    }
292    /// Read a slot without conflating missing and out of bounds.
293    pub fn get(&self, index: usize) -> Option<Option<&RawKey>> {
294        self.codes
295            .get(index)
296            .map(|code| code.and_then(|code| self.levels.get(code as usize)))
297    }
298    /// Iterate the actual original keys and missing slots.
299    pub fn iter(&self) -> impl ExactSizeIterator<Item = Option<&RawKey>> + '_ {
300        (0..self.len()).map(|index| self.get(index).expect("in-bounds raw key slot"))
301    }
302    /// Original validity.
303    pub fn is_valid(&self, index: usize) -> Option<bool> {
304        self.codes.get(index).map(Option::is_some)
305    }
306    /// Retain the actual original selected source of this key variable.
307    #[doc(hidden)]
308    pub fn with_source(mut self, source: DataSourceInfo) -> Result<Self> {
309        self.source = VectorSource::repeated(source, 1, self.len())?.with_original_validity(
310            self.len(),
311            self.has_nulls(),
312            |slot| self.codes[slot].is_some(),
313        )?;
314        Ok(self)
315    }
316
317    pub(crate) fn with_vector_source(mut self, source: VectorSource) -> Self {
318        self.source = source;
319        self
320    }
321
322    /// Original captured source.
323    #[doc(hidden)]
324    pub fn get_source(&self) -> &DataSourceInfo {
325        self.source.info()
326    }
327
328    pub(crate) fn vector_source(&self) -> &VectorSource {
329        &self.source
330    }
331
332    pub(crate) fn has_nulls(&self) -> bool {
333        self.codes.iter().any(Option::is_none)
334    }
335
336    /// Original source member corresponding to a logical slot.
337    #[doc(hidden)]
338    pub fn source_slot(&self, index: usize) -> Option<usize> {
339        (index < self.len()).then(|| self.source.slot(index))
340    }
341
342    pub(crate) fn select(&self, indices: &[usize]) -> Result<Self> {
343        let mut selected = Self::nullable(
344            self.name(),
345            indices.iter().map(|&index| {
346                self.get(index)
347                    .expect("validated raw key selection")
348                    .cloned()
349            }),
350        )?;
351        selected.source = self.source.select(indices)?;
352        Ok(selected)
353    }
354
355    /// Distinct keys in first-observed order.
356    pub fn levels(&self) -> &[RawKey] {
357        &self.levels
358    }
359}
360
361impl PartialEq for RawKeyValues {
362    fn eq(&self, other: &Self) -> bool {
363        self.name == other.name && self.codes == other.codes && self.levels == other.levels
364    }
365}
366impl Eq for RawKeyValues {}
367
368/// An actual string or raw-key column.
369#[derive(Debug, Clone, PartialEq, Eq)]
370#[non_exhaustive]
371pub enum KeyValues {
372    /// An actual string category column.
373    Strings(CategoryValues),
374    /// A column of complete raw keys.
375    Raw(RawKeyValues),
376}
377impl KeyValues {
378    pub(crate) fn key_at(&self, slot: usize) -> Option<RawKey> {
379        match self {
380            Self::Strings(values) => values.get(slot).flatten().map(RawKey::from),
381            Self::Raw(values) => values.get(slot).flatten().cloned(),
382        }
383    }
384
385    pub(crate) fn select(&self, indices: &[usize]) -> crate::Result<Self> {
386        Ok(match self {
387            Self::Strings(values) => Self::Strings(values.select(indices)?),
388            Self::Raw(values) => Self::Raw(values.select(indices)?),
389        })
390    }
391
392    /// Construct the true logical column of generated identities, preserving
393    /// string categories when every supplied identity is a string.
394    #[doc(hidden)]
395    pub fn repeated_keys(name: &str, keys: &[RawKey], rows: usize) -> Result<Self> {
396        if keys.iter().all(|key| matches!(key, RawKey::String(_))) {
397            Ok(Self::Strings(CategoryValues::new(
398                name,
399                (0..rows).flat_map(|_| {
400                    keys.iter().map(|key| match key {
401                        RawKey::String(value) => value.as_str(),
402                        _ => unreachable!("all keys are strings"),
403                    })
404                }),
405            )?))
406        } else {
407            Ok(Self::Raw(RawKeyValues::new(
408                name,
409                (0..rows).flat_map(|_| keys.iter().cloned()),
410            )?))
411        }
412    }
413
414    /// Read an actual string category column.
415    pub const fn get_strings(&self) -> Option<&CategoryValues> {
416        if let Self::Strings(values) = self {
417            Some(values)
418        } else {
419            None
420        }
421    }
422    /// Read an actual raw-key column.
423    pub const fn get_raw(&self) -> Option<&RawKeyValues> {
424        if let Self::Raw(values) = self {
425            Some(values)
426        } else {
427            None
428        }
429    }
430    /// Number of original slots.
431    pub fn len(&self) -> usize {
432        match self {
433            Self::Strings(values) => values.len(),
434            Self::Raw(values) => values.len(),
435        }
436    }
437    /// Whether no original slots were supplied.
438    pub fn is_empty(&self) -> bool {
439        self.len() == 0
440    }
441    /// Actual slot validity, independent of key type.
442    pub fn is_valid(&self, index: usize) -> Option<bool> {
443        match self {
444            Self::Strings(values) => values.is_valid(index),
445            Self::Raw(values) => values.is_valid(index),
446        }
447    }
448}
449
450/// One named key column; the complete field key is independent of its values.
451#[derive(Debug, Clone, PartialEq, Eq)]
452pub struct NamedKeyValues {
453    /// The actual field identity.
454    pub key: RawKey,
455    /// The actual original column.
456    pub values: KeyValues,
457}
458
459/// An ordered collection of aligned key columns.
460#[derive(Debug, Clone, PartialEq, Eq)]
461pub struct KeyColumns(Arc<[NamedKeyValues]>);
462
463impl KeyColumns {
464    /// Capture aligned columns, preserving the supplied field order.
465    pub fn new(columns: Vec<NamedKeyValues>) -> Result<Self> {
466        let length = columns.first().map_or(0, |column| column.values.len());
467        let mut fields = std::collections::HashSet::new();
468        for column in &columns {
469            if column.values.len() != length {
470                return Err(Error::Data(
471                    Diagnostic::new(
472                        DiagnosticKind::ShapeMismatch {
473                            expected: vec![length],
474                            actual: vec![column.values.len()],
475                        },
476                        "key columns must have the same length",
477                    )
478                    .with_context(
479                        ErrorContext::new()
480                            .with_operation(OperationPhase::Bind)
481                            .with_binding(column.key.clone()),
482                    ),
483                ));
484            }
485            if !fields.insert(&column.key) {
486                return Err(Error::Data("duplicate key column identity".into()));
487            }
488        }
489        Ok(Self(columns.into()))
490    }
491    /// The actual ordered fields and values.
492    pub fn columns(&self) -> &[NamedKeyValues] {
493        &self.0
494    }
495    /// Number of key columns.
496    pub fn len(&self) -> usize {
497        self.0.len()
498    }
499    /// Whether no key columns were supplied.
500    pub fn is_empty(&self) -> bool {
501        self.0.is_empty()
502    }
503    pub(crate) fn row_keys(&self, index: usize) -> Option<Vec<RawKey>> {
504        self.0
505            .iter()
506            .map(|column| match &column.values {
507                KeyValues::Strings(values) => values.get(index)?.map(RawKey::from),
508                KeyValues::Raw(values) => values.get(index)?.cloned(),
509            })
510            .collect()
511    }
512
513    /// Find a column by its complete field key.
514    pub fn get(&self, key: &RawKey) -> Result<&KeyValues> {
515        self.0
516            .iter()
517            .find(|column| &column.key == key)
518            .map(|column| &column.values)
519            .ok_or_else(|| {
520                Error::Data(
521                    Diagnostic::new(
522                        DiagnosticKind::UnknownKey {
523                            key: Some(key.clone()),
524                        },
525                        format!("no key column {key:?}"),
526                    )
527                    .with_context(ErrorContext::new().with_operation(OperationPhase::Check)),
528                )
529            })
530    }
531}