Skip to main content

lichtung_plot/data/
temporal.rs

1//! Exact calendar, instant and elapsed-duration values used by source keys.
2
3use crate::{Error, Result};
4
5/// A proleptic Gregorian calendar day, without time or timezone.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
7pub struct Date {
8    year: i32,
9    month: u8,
10    day: u8,
11}
12
13impl Date {
14    /// Validate and capture a Gregorian date.
15    pub fn new(year: i32, month: u8, day: u8) -> Result<Self> {
16        let leap =
17            year.rem_euclid(4) == 0 && (year.rem_euclid(100) != 0 || year.rem_euclid(400) == 0);
18        let days = match month {
19            1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
20            4 | 6 | 9 | 11 => 30,
21            2 if leap => 29,
22            2 => 28,
23            _ => 0,
24        };
25        if day == 0 || day > days {
26            return Err(Error::Data("invalid Gregorian calendar date".into()));
27        }
28        Ok(Self { year, month, day })
29    }
30    /// Calendar year.
31    pub const fn year(self) -> i32 {
32        self.year
33    }
34    /// Month, 1 through 12.
35    pub const fn month(self) -> u8 {
36        self.month
37    }
38    /// Day of the month.
39    pub const fn day(self) -> u8 {
40        self.day
41    }
42}
43
44/// An exact signed elapsed duration, in nanoseconds.
45#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
46pub struct Duration(i128);
47
48impl Duration {
49    /// Construct an exact nanosecond duration.
50    pub const fn from_nanos(nanos: i128) -> Self {
51        Self(nanos)
52    }
53    /// Construct from integral seconds.
54    pub const fn from_secs(seconds: i64) -> Self {
55        Self(seconds as i128 * 1_000_000_000)
56    }
57    /// The signed nanosecond count.
58    pub const fn nanoseconds(self) -> i128 {
59        self.0
60    }
61}
62
63/// The declared identity of an instant's timezone, when present.
64#[derive(Debug, Clone, PartialEq, Eq, Hash)]
65#[non_exhaustive]
66pub enum TimeZone {
67    /// A named IANA zone.
68    Iana(String),
69    /// A fixed UTC offset in seconds.
70    FixedOffset(i32),
71}
72
73/// An instant with exact time and retained timezone/disambiguation metadata.
74#[derive(Debug, Clone, PartialEq, Eq, Hash)]
75pub struct Timestamp {
76    seconds: i64,
77    nanos: u32,
78    zone: Option<TimeZone>,
79    offset_seconds: Option<i32>,
80    fold: Option<u8>,
81}
82
83impl Timestamp {
84    /// Construct a Unix instant with a nonnegative subsecond remainder.
85    /// Offset/fold describe the original binding, independently of UTC time.
86    pub fn new(
87        seconds: i64,
88        nanos: u32,
89        zone: Option<TimeZone>,
90        offset_seconds: Option<i32>,
91        fold: Option<u8>,
92    ) -> Result<Self> {
93        let valid_offset = |offset: i32| (-86_399..=86_399).contains(&offset);
94        if nanos >= 1_000_000_000
95            || fold.is_some_and(|value| value > 1)
96            || offset_seconds.is_some_and(|offset| !valid_offset(offset))
97        {
98            return Err(Error::Data(
99                "invalid timestamp nanoseconds, offset or fold".into(),
100            ));
101        }
102        match &zone {
103            Some(TimeZone::Iana(name)) if name.is_empty() => {
104                return Err(Error::Data("timezone name must not be empty".into()));
105            }
106            Some(TimeZone::FixedOffset(offset))
107                if !valid_offset(*offset)
108                    || offset_seconds.is_some_and(|original| original != *offset) =>
109            {
110                return Err(Error::Data("inconsistent fixed timezone offset".into()));
111            }
112            _ => {}
113        }
114        Ok(Self {
115            seconds,
116            nanos,
117            zone,
118            offset_seconds,
119            fold,
120        })
121    }
122    /// Whole Unix seconds, rounded toward negative infinity.
123    pub const fn seconds(&self) -> i64 {
124        self.seconds
125    }
126    /// Nanosecond remainder in the second.
127    pub const fn nanos(&self) -> u32 {
128        self.nanos
129    }
130    /// The exact Unix nanosecond count; no f64 or microsecond conversion.
131    pub const fn unix_ns(&self) -> i128 {
132        self.seconds as i128 * 1_000_000_000 + self.nanos as i128
133    }
134    /// Original timezone identity, if supplied.
135    pub const fn zone(&self) -> Option<&TimeZone> {
136        self.zone.as_ref()
137    }
138    /// Original offset in seconds, if known.
139    pub const fn offset_seconds(&self) -> Option<i32> {
140        self.offset_seconds
141    }
142    /// Original local ambiguity choice, if supplied.
143    pub const fn fold(&self) -> Option<u8> {
144        self.fold
145    }
146}
147
148/// A timezone-free local timestamp key. It does not identify a UTC instant.
149#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
150pub struct LocalTimestamp {
151    date: Date,
152    hour: u8,
153    minute: u8,
154    second: u8,
155    nanos: u32,
156}
157
158impl LocalTimestamp {
159    /// Capture exact local calendar and wall-clock fields.
160    pub fn new(date: Date, hour: u8, minute: u8, second: u8, nanos: u32) -> Result<Self> {
161        if hour >= 24 || minute >= 60 || second >= 60 || nanos >= 1_000_000_000 {
162            return Err(Error::Data("invalid local timestamp".into()));
163        }
164        Ok(Self {
165            date,
166            hour,
167            minute,
168            second,
169            nanos,
170        })
171    }
172    /// Local calendar date.
173    pub const fn date(self) -> Date {
174        self.date
175    }
176    /// Local hour.
177    pub const fn hour(self) -> u8 {
178        self.hour
179    }
180    /// Local minute.
181    pub const fn minute(self) -> u8 {
182        self.minute
183    }
184    /// Local second.
185    pub const fn second(self) -> u8 {
186        self.second
187    }
188    /// Nanosecond remainder in the second.
189    pub const fn nanos(self) -> u32 {
190        self.nanos
191    }
192}
193
194/// Explicit authored time unit for elapsed-duration values.
195#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
196#[non_exhaustive]
197pub enum DurationUnit {
198    /// Nanoseconds.
199    Nanosecond,
200    /// Microseconds.
201    Microsecond,
202    /// Milliseconds.
203    Millisecond,
204    /// Seconds.
205    Second,
206    /// Minutes.
207    Minute,
208    /// Hours.
209    Hour,
210    /// Fixed elapsed days of 86,400 seconds.
211    Day,
212    /// Fixed elapsed weeks of seven days.
213    Week,
214}
215
216impl DurationUnit {
217    /// Exact multiplier to nanoseconds.
218    pub const fn nanoseconds(self) -> i128 {
219        match self {
220            Self::Nanosecond => 1,
221            Self::Microsecond => 1_000,
222            Self::Millisecond => 1_000_000,
223            Self::Second => 1_000_000_000,
224            Self::Minute => 60 * 1_000_000_000,
225            Self::Hour => 3_600 * 1_000_000_000,
226            Self::Day => 86_400 * 1_000_000_000,
227            Self::Week => 604_800 * 1_000_000_000,
228        }
229    }
230}
231
232impl Duration {
233    /// Capture an integer measurement in its explicitly supplied elapsed unit.
234    pub fn from_units(value: i128, unit: DurationUnit) -> Result<Self> {
235        value
236            .checked_mul(unit.nanoseconds())
237            .map(Self)
238            .ok_or_else(|| Error::Data("elapsed duration exceeds exact nanosecond range".into()))
239    }
240}
241
242macro_rules! temporal_column {
243    ($name:ident, $element:ty, $read:ty, $read_value:expr, $doc:literal $(, $extra:ident: $extra_type:ty)*) => {
244        #[doc = $doc]
245        #[derive(Debug, Clone)]
246        pub struct $name {
247            name: std::sync::Arc<str>,
248            values: std::sync::Arc<[Option<$element>]>,
249            source: super::binding::VectorSource,
250            $($extra: $extra_type,)*
251        }
252
253        impl $name {
254            /// Capture complete exact values in supplied order.
255            pub fn new(
256                name: impl Into<String>,
257                $($extra: $extra_type,)*
258                values: impl IntoIterator<Item = $element>,
259            ) -> Result<Self> {
260                Self::nullable(name, $($extra,)* values.into_iter().map(Some))
261            }
262
263            /// Capture nullable exact values, preserving the original slots.
264            pub fn nullable(
265                name: impl Into<String>,
266                $($extra: $extra_type,)*
267                values: impl IntoIterator<Item = Option<$element>>,
268            ) -> Result<Self> {
269                let values = super::source::collect_source(values.into_iter().map(Ok))?;
270                Ok(Self {
271                    name: std::sync::Arc::from(name.into()),
272                    source: super::binding::VectorSource::direct(values.len()),
273                    values: values.into(),
274                    $($extra,)*
275                })
276            }
277
278            /// Original captured source.
279            #[doc(hidden)]
280            pub fn get_source(&self) -> &super::DataSourceInfo { self.source.info() }
281
282            /// Original column name.
283            pub fn name(&self) -> &str { &self.name }
284
285            /// Number of logical slots, including missing values.
286            pub fn len(&self) -> usize { self.values.len() }
287
288            /// Whether this column has no slots.
289            pub fn is_empty(&self) -> bool { self.values.is_empty() }
290
291            /// Read one original temporal slot.
292            pub fn get(&self, index: usize) -> Option<Option<$read>> {
293                self.values.get(index).map($read_value)
294            }
295
296            /// Iterate actual values and missing slots in original order.
297            pub fn iter(&self) -> impl ExactSizeIterator<Item = Option<$read>> + '_ {
298                self.values.iter().map($read_value)
299            }
300
301            /// Actual validity of the original slot.
302            pub fn is_valid(&self, index: usize) -> Option<bool> {
303                self.values.get(index).map(Option::is_some)
304            }
305        }
306        impl PartialEq for $name {
307            fn eq(&self, other: &Self) -> bool {
308                self.name == other.name && self.values == other.values $(&& self.$extra == other.$extra)*
309            }
310        }
311        impl Eq for $name {}
312    };
313}
314
315temporal_column!(
316    DateValues,
317    Date,
318    Date,
319    |value: &Option<Date>| *value,
320    "An immutable nullable column of exact Gregorian dates."
321);
322temporal_column!(
323    TimeValues,
324    Timestamp,
325    &Timestamp,
326    Option::as_ref,
327    "An immutable nullable column of exact instants and timezone metadata."
328);
329temporal_column!(DurationValues, Duration, Duration, |value: &Option<Duration>| *value, "An immutable nullable column of exact elapsed durations.", unit: DurationUnit);
330
331impl DurationValues {
332    /// Author's actual elapsed unit, independently of the exact nanosecond values.
333    pub const fn unit(&self) -> DurationUnit {
334        self.unit
335    }
336}
337
338#[cfg(test)]
339mod column_tests {
340    use super::*;
341
342    #[test]
343    fn temporal_columns_keep_exact_original_values() {
344        let date = Date::new(2000, 2, 29).unwrap();
345        let dates = DateValues::nullable("date", [Some(date), None]).unwrap();
346        assert_eq!(dates.get(0), Some(Some(date)));
347        assert_eq!(dates.is_valid(1), Some(false));
348        assert_eq!(dates.get(2), None);
349        let instant = Timestamp::new(
350            -1,
351            999_999_999,
352            Some(TimeZone::FixedOffset(0)),
353            Some(0),
354            None,
355        )
356        .unwrap();
357        let times = TimeValues::nullable("time", [Some(instant), None]).unwrap();
358        assert_eq!(times.get(0).flatten().unwrap().unix_ns(), -1);
359        let duration = Duration::from_units(-17, DurationUnit::Microsecond).unwrap();
360        let elapsed =
361            DurationValues::nullable("elapsed", DurationUnit::Microsecond, [Some(duration), None])
362                .unwrap();
363        assert_eq!(elapsed.get(0).flatten().unwrap().nanoseconds(), -17_000);
364        assert_eq!(elapsed.unit(), DurationUnit::Microsecond);
365        assert!(Duration::from_units(i128::MAX, DurationUnit::Week).is_err());
366    }
367}