Skip to main content

ggplot_rs/data/
mod.rs

1mod dataframe;
2mod source;
3
4pub use dataframe::DataFrame;
5pub use source::GGData;
6
7/// Dynamic value type for DataFrame columns.
8#[derive(Clone, Debug)]
9pub enum Value {
10    Float(f64),
11    Integer(i64),
12    Str(String),
13    Bool(bool),
14    /// Seconds since Unix epoch (1970-01-01 00:00:00 UTC).
15    DateTime(i64),
16    Na,
17}
18
19impl Value {
20    /// Try to extract as f64, coercing integers and datetimes.
21    pub fn as_f64(&self) -> Option<f64> {
22        match self {
23            Value::Float(f) => Some(*f),
24            Value::Integer(i) => Some(*i as f64),
25            Value::DateTime(secs) => Some(*secs as f64),
26            _ => None,
27        }
28    }
29
30    /// Try to extract as string representation.
31    pub fn as_str(&self) -> Option<&str> {
32        match self {
33            Value::Str(s) => Some(s),
34            _ => None,
35        }
36    }
37
38    /// Check if this is NA/missing.
39    pub fn is_na(&self) -> bool {
40        matches!(self, Value::Na)
41    }
42
43    /// Check if this is a DateTime value.
44    pub fn is_datetime(&self) -> bool {
45        matches!(self, Value::DateTime(_))
46    }
47
48    /// Create a DateTime from seconds since Unix epoch.
49    pub fn from_timestamp(secs: i64) -> Self {
50        Value::DateTime(secs)
51    }
52
53    /// Convert to a string for display and discrete-scale level purposes.
54    ///
55    /// Note this is *not* injective: `Value::Na` and the string `"NA"` (and
56    /// `Float(1.0)`/`Integer(1)`/`Str("1")`) share a key. Use
57    /// [`group_key`](Self::group_key) to split rows into groups, and
58    /// [`key_str`](Self::key_str) for allocation-free lookups.
59    pub fn to_group_key(&self) -> String {
60        match self {
61            Value::Float(f) => format!("{f}"),
62            Value::Integer(i) => format!("{i}"),
63            Value::Str(s) => s.clone(),
64            Value::Bool(b) => format!("{b}"),
65            Value::DateTime(secs) => format_epoch_secs(*secs),
66            Value::Na => "NA".to_string(),
67        }
68    }
69}
70
71/// A grouping key for one value: [`Value::group_key`]. Unlike
72/// [`Value::to_group_key`] it keeps a missing value (`Na`) distinct from the
73/// literal string `"NA"`, and borrows string data instead of cloning it.
74#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
75pub enum GroupKey<'a> {
76    /// A missing value.
77    Na,
78    /// Any present value, keyed by its display string (so `Float(1.0)` and
79    /// `Integer(1)` still group together).
80    Key(std::borrow::Cow<'a, str>),
81}
82
83impl Value {
84    /// Same string as [`to_group_key`](Self::to_group_key), but borrowed for
85    /// `Str` values — use it for hot-path scale lookups.
86    pub fn key_str(&self) -> std::borrow::Cow<'_, str> {
87        match self {
88            Value::Str(s) => std::borrow::Cow::Borrowed(s.as_str()),
89            Value::Na => std::borrow::Cow::Borrowed("NA"),
90            other => std::borrow::Cow::Owned(other.to_group_key()),
91        }
92    }
93
94    /// Injective-on-missingness grouping key: `Na` never collides with the
95    /// string `"NA"`. Borrows `Str` data (no allocation).
96    pub fn group_key(&self) -> GroupKey<'_> {
97        match self {
98            Value::Na => GroupKey::Na,
99            other => GroupKey::Key(other.key_str()),
100        }
101    }
102}
103
104/// Format epoch seconds as a human-readable date/time string.
105pub fn format_epoch_secs(secs: i64) -> String {
106    // Simple UTC date/time formatting without external dependencies
107    const SECS_PER_DAY: i64 = 86400;
108    const SECS_PER_HOUR: i64 = 3600;
109    const SECS_PER_MINUTE: i64 = 60;
110
111    // Euclidean division: floor for negative timestamps, and total over the
112    // whole i64 range (no `secs - 86399` overflow at i64::MIN).
113    let mut days = secs.div_euclid(SECS_PER_DAY);
114    let rem = secs.rem_euclid(SECS_PER_DAY);
115
116    let hour = rem / SECS_PER_HOUR;
117    let minute = (rem % SECS_PER_HOUR) / SECS_PER_MINUTE;
118    let second = rem % SECS_PER_MINUTE;
119
120    // Days since 1970-01-01 to Y-M-D (civil calendar)
121    days += 719_468; // shift epoch from 1970-01-01 to 0000-03-01
122    let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
123    let doe = (days - era * 146_097) as u32;
124    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
125    let y = yoe as i64 + era * 400;
126    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
127    let mp = (5 * doy + 2) / 153;
128    let d = doy - (153 * mp + 2) / 5 + 1;
129    let m = if mp < 10 { mp + 3 } else { mp - 9 };
130    let y = if m <= 2 { y + 1 } else { y };
131
132    if hour == 0 && minute == 0 && second == 0 {
133        format!("{y:04}-{m:02}-{d:02}")
134    } else {
135        format!("{y:04}-{m:02}-{d:02} {hour:02}:{minute:02}:{second:02}")
136    }
137}
138
139impl PartialEq for Value {
140    fn eq(&self, other: &Self) -> bool {
141        match (self, other) {
142            (Value::Float(a), Value::Float(b)) => a.to_bits() == b.to_bits(),
143            (Value::Integer(a), Value::Integer(b)) => a == b,
144            (Value::Str(a), Value::Str(b)) => a == b,
145            (Value::Bool(a), Value::Bool(b)) => a == b,
146            (Value::DateTime(a), Value::DateTime(b)) => a == b,
147            (Value::Na, Value::Na) => true,
148            _ => false,
149        }
150    }
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156
157    #[test]
158    fn na_and_literal_na_have_distinct_group_keys() {
159        let na = Value::Na;
160        let lit = Value::Str("NA".to_string());
161        assert_ne!(na.group_key(), lit.group_key());
162        // Display/level keys stay "NA" for both (what an axis or legend shows).
163        assert_eq!(na.to_group_key(), "NA");
164        assert_eq!(lit.to_group_key(), "NA");
165        // Numeric types still group by value.
166        assert_eq!(Value::Float(1.0).group_key(), Value::Integer(1).group_key());
167        assert!(matches!(
168            Value::Str("x".into()).key_str(),
169            std::borrow::Cow::Borrowed("x")
170        ));
171    }
172
173    #[test]
174    fn format_epoch_secs_is_total() {
175        assert_eq!(format_epoch_secs(0), "1970-01-01");
176        assert_eq!(format_epoch_secs(-1), "1969-12-31 23:59:59");
177        assert_eq!(format_epoch_secs(-86_400), "1969-12-31");
178        assert_eq!(format_epoch_secs(951_782_400), "2000-02-29");
179        // Extremes must not overflow (they used to panic in debug builds).
180        let lo = format_epoch_secs(i64::MIN);
181        let hi = format_epoch_secs(i64::MAX);
182        assert!(lo.starts_with('-') && lo.contains(':'), "{lo}");
183        assert!(hi.contains(':'), "{hi}");
184    }
185}