lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Exact calendar, instant and elapsed-duration values used by source keys.

use crate::{Error, Result};

/// A proleptic Gregorian calendar day, without time or timezone.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Date {
    year: i32,
    month: u8,
    day: u8,
}

impl Date {
    /// Validate and capture a Gregorian date.
    pub fn new(year: i32, month: u8, day: u8) -> Result<Self> {
        let leap =
            year.rem_euclid(4) == 0 && (year.rem_euclid(100) != 0 || year.rem_euclid(400) == 0);
        let days = match month {
            1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
            4 | 6 | 9 | 11 => 30,
            2 if leap => 29,
            2 => 28,
            _ => 0,
        };
        if day == 0 || day > days {
            return Err(Error::Data("invalid Gregorian calendar date".into()));
        }
        Ok(Self { year, month, day })
    }
    /// Calendar year.
    pub const fn year(self) -> i32 {
        self.year
    }
    /// Month, 1 through 12.
    pub const fn month(self) -> u8 {
        self.month
    }
    /// Day of the month.
    pub const fn day(self) -> u8 {
        self.day
    }
}

/// An exact signed elapsed duration, in nanoseconds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Duration(i128);

impl Duration {
    /// Construct an exact nanosecond duration.
    pub const fn from_nanos(nanos: i128) -> Self {
        Self(nanos)
    }
    /// Construct from integral seconds.
    pub const fn from_secs(seconds: i64) -> Self {
        Self(seconds as i128 * 1_000_000_000)
    }
    /// The signed nanosecond count.
    pub const fn nanoseconds(self) -> i128 {
        self.0
    }
}

/// The declared identity of an instant's timezone, when present.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum TimeZone {
    /// A named IANA zone.
    Iana(String),
    /// A fixed UTC offset in seconds.
    FixedOffset(i32),
}

/// An instant with exact time and retained timezone/disambiguation metadata.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Timestamp {
    seconds: i64,
    nanos: u32,
    zone: Option<TimeZone>,
    offset_seconds: Option<i32>,
    fold: Option<u8>,
}

impl Timestamp {
    /// Construct a Unix instant with a nonnegative subsecond remainder.
    /// Offset/fold describe the original binding, independently of UTC time.
    pub fn new(
        seconds: i64,
        nanos: u32,
        zone: Option<TimeZone>,
        offset_seconds: Option<i32>,
        fold: Option<u8>,
    ) -> Result<Self> {
        let valid_offset = |offset: i32| (-86_399..=86_399).contains(&offset);
        if nanos >= 1_000_000_000
            || fold.is_some_and(|value| value > 1)
            || offset_seconds.is_some_and(|offset| !valid_offset(offset))
        {
            return Err(Error::Data(
                "invalid timestamp nanoseconds, offset or fold".into(),
            ));
        }
        match &zone {
            Some(TimeZone::Iana(name)) if name.is_empty() => {
                return Err(Error::Data("timezone name must not be empty".into()));
            }
            Some(TimeZone::FixedOffset(offset))
                if !valid_offset(*offset)
                    || offset_seconds.is_some_and(|original| original != *offset) =>
            {
                return Err(Error::Data("inconsistent fixed timezone offset".into()));
            }
            _ => {}
        }
        Ok(Self {
            seconds,
            nanos,
            zone,
            offset_seconds,
            fold,
        })
    }
    /// Whole Unix seconds, rounded toward negative infinity.
    pub const fn seconds(&self) -> i64 {
        self.seconds
    }
    /// Nanosecond remainder in the second.
    pub const fn nanos(&self) -> u32 {
        self.nanos
    }
    /// The exact Unix nanosecond count; no f64 or microsecond conversion.
    pub const fn unix_ns(&self) -> i128 {
        self.seconds as i128 * 1_000_000_000 + self.nanos as i128
    }
    /// Original timezone identity, if supplied.
    pub const fn zone(&self) -> Option<&TimeZone> {
        self.zone.as_ref()
    }
    /// Original offset in seconds, if known.
    pub const fn offset_seconds(&self) -> Option<i32> {
        self.offset_seconds
    }
    /// Original local ambiguity choice, if supplied.
    pub const fn fold(&self) -> Option<u8> {
        self.fold
    }
}

/// A timezone-free local timestamp key. It does not identify a UTC instant.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct LocalTimestamp {
    date: Date,
    hour: u8,
    minute: u8,
    second: u8,
    nanos: u32,
}

impl LocalTimestamp {
    /// Capture exact local calendar and wall-clock fields.
    pub fn new(date: Date, hour: u8, minute: u8, second: u8, nanos: u32) -> Result<Self> {
        if hour >= 24 || minute >= 60 || second >= 60 || nanos >= 1_000_000_000 {
            return Err(Error::Data("invalid local timestamp".into()));
        }
        Ok(Self {
            date,
            hour,
            minute,
            second,
            nanos,
        })
    }
    /// Local calendar date.
    pub const fn date(self) -> Date {
        self.date
    }
    /// Local hour.
    pub const fn hour(self) -> u8 {
        self.hour
    }
    /// Local minute.
    pub const fn minute(self) -> u8 {
        self.minute
    }
    /// Local second.
    pub const fn second(self) -> u8 {
        self.second
    }
    /// Nanosecond remainder in the second.
    pub const fn nanos(self) -> u32 {
        self.nanos
    }
}

/// Explicit authored time unit for elapsed-duration values.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DurationUnit {
    /// Nanoseconds.
    Nanosecond,
    /// Microseconds.
    Microsecond,
    /// Milliseconds.
    Millisecond,
    /// Seconds.
    Second,
    /// Minutes.
    Minute,
    /// Hours.
    Hour,
    /// Fixed elapsed days of 86,400 seconds.
    Day,
    /// Fixed elapsed weeks of seven days.
    Week,
}

impl DurationUnit {
    /// Exact multiplier to nanoseconds.
    pub const fn nanoseconds(self) -> i128 {
        match self {
            Self::Nanosecond => 1,
            Self::Microsecond => 1_000,
            Self::Millisecond => 1_000_000,
            Self::Second => 1_000_000_000,
            Self::Minute => 60 * 1_000_000_000,
            Self::Hour => 3_600 * 1_000_000_000,
            Self::Day => 86_400 * 1_000_000_000,
            Self::Week => 604_800 * 1_000_000_000,
        }
    }
}

impl Duration {
    /// Capture an integer measurement in its explicitly supplied elapsed unit.
    pub fn from_units(value: i128, unit: DurationUnit) -> Result<Self> {
        value
            .checked_mul(unit.nanoseconds())
            .map(Self)
            .ok_or_else(|| Error::Data("elapsed duration exceeds exact nanosecond range".into()))
    }
}

macro_rules! temporal_column {
    ($name:ident, $element:ty, $read:ty, $read_value:expr, $doc:literal $(, $extra:ident: $extra_type:ty)*) => {
        #[doc = $doc]
        #[derive(Debug, Clone)]
        pub struct $name {
            name: std::sync::Arc<str>,
            values: std::sync::Arc<[Option<$element>]>,
            source: super::binding::VectorSource,
            $($extra: $extra_type,)*
        }

        impl $name {
            /// Capture complete exact values in supplied order.
            pub fn new(
                name: impl Into<String>,
                $($extra: $extra_type,)*
                values: impl IntoIterator<Item = $element>,
            ) -> Result<Self> {
                Self::nullable(name, $($extra,)* values.into_iter().map(Some))
            }

            /// Capture nullable exact values, preserving the original slots.
            pub fn nullable(
                name: impl Into<String>,
                $($extra: $extra_type,)*
                values: impl IntoIterator<Item = Option<$element>>,
            ) -> Result<Self> {
                let values = super::source::collect_source(values.into_iter().map(Ok))?;
                Ok(Self {
                    name: std::sync::Arc::from(name.into()),
                    source: super::binding::VectorSource::direct(values.len()),
                    values: values.into(),
                    $($extra,)*
                })
            }

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

            /// Original column name.
            pub fn name(&self) -> &str { &self.name }

            /// Number of logical slots, including missing values.
            pub fn len(&self) -> usize { self.values.len() }

            /// Whether this column has no slots.
            pub fn is_empty(&self) -> bool { self.values.is_empty() }

            /// Read one original temporal slot.
            pub fn get(&self, index: usize) -> Option<Option<$read>> {
                self.values.get(index).map($read_value)
            }

            /// Iterate actual values and missing slots in original order.
            pub fn iter(&self) -> impl ExactSizeIterator<Item = Option<$read>> + '_ {
                self.values.iter().map($read_value)
            }

            /// Actual validity of the original slot.
            pub fn is_valid(&self, index: usize) -> Option<bool> {
                self.values.get(index).map(Option::is_some)
            }
        }
        impl PartialEq for $name {
            fn eq(&self, other: &Self) -> bool {
                self.name == other.name && self.values == other.values $(&& self.$extra == other.$extra)*
            }
        }
        impl Eq for $name {}
    };
}

temporal_column!(
    DateValues,
    Date,
    Date,
    |value: &Option<Date>| *value,
    "An immutable nullable column of exact Gregorian dates."
);
temporal_column!(
    TimeValues,
    Timestamp,
    &Timestamp,
    Option::as_ref,
    "An immutable nullable column of exact instants and timezone metadata."
);
temporal_column!(DurationValues, Duration, Duration, |value: &Option<Duration>| *value, "An immutable nullable column of exact elapsed durations.", unit: DurationUnit);

impl DurationValues {
    /// Author's actual elapsed unit, independently of the exact nanosecond values.
    pub const fn unit(&self) -> DurationUnit {
        self.unit
    }
}

#[cfg(test)]
mod column_tests {
    use super::*;

    #[test]
    fn temporal_columns_keep_exact_original_values() {
        let date = Date::new(2000, 2, 29).unwrap();
        let dates = DateValues::nullable("date", [Some(date), None]).unwrap();
        assert_eq!(dates.get(0), Some(Some(date)));
        assert_eq!(dates.is_valid(1), Some(false));
        assert_eq!(dates.get(2), None);
        let instant = Timestamp::new(
            -1,
            999_999_999,
            Some(TimeZone::FixedOffset(0)),
            Some(0),
            None,
        )
        .unwrap();
        let times = TimeValues::nullable("time", [Some(instant), None]).unwrap();
        assert_eq!(times.get(0).flatten().unwrap().unix_ns(), -1);
        let duration = Duration::from_units(-17, DurationUnit::Microsecond).unwrap();
        let elapsed =
            DurationValues::nullable("elapsed", DurationUnit::Microsecond, [Some(duration), None])
                .unwrap();
        assert_eq!(elapsed.get(0).flatten().unwrap().nanoseconds(), -17_000);
        assert_eq!(elapsed.unit(), DurationUnit::Microsecond);
        assert!(Duration::from_units(i128::MAX, DurationUnit::Week).is_err());
    }
}