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