Skip to main content

tui_chart/
timeaxis.rs

1//! Time-aware axis helpers: unix-timestamp (seconds) formatting and tick steps.
2//!
3//! No external crates: dates use Howard Hinnant's civil-from-days algorithm
4//! (proleptic Gregorian, UTC). The `fn(f64) -> String` formatters plug directly into
5//! [`Axis::formatter`](crate::Axis::formatter).
6
7/// Days since 1970-01-01 → `(year, month 1..=12, day 1..=31)`.
8pub fn civil_from_days(z: i64) -> (i64, u32, u32) {
9    let z = z + 719_468;
10    let era = z.div_euclid(146_097);
11    let doe = z.rem_euclid(146_097);
12    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
13    let y = yoe + era * 400;
14    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
15    let mp = (5 * doy + 2) / 153;
16    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
17    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
18    (if m <= 2 { y + 1 } else { y }, m, d)
19}
20
21/// `(year, month, day)` → days since 1970-01-01 (inverse of [`civil_from_days`]).
22pub fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
23    let y = if m <= 2 { y - 1 } else { y };
24    let era = y.div_euclid(400);
25    let yoe = y.rem_euclid(400);
26    let mp = (m as i64 + 9) % 12;
27    let doy = (153 * mp + 2) / 5 + d as i64 - 1;
28    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
29    era * 146_097 + doe - 719_468
30}
31
32/// Split a timestamp into `(y, m, d, hh, mm, ss)`; non-finite maps to the epoch.
33fn split(ts: f64) -> (i64, u32, u32, u32, u32, u32) {
34    let s = if ts.is_finite() {
35        ts.clamp(-1e15, 1e15).floor() as i64
36    } else {
37        0
38    };
39    let days = s.div_euclid(86_400);
40    let rem = s.rem_euclid(86_400) as u32;
41    let (y, m, d) = civil_from_days(days);
42    (y, m, d, rem / 3600, rem % 3600 / 60, rem % 60)
43}
44
45/// Format as `HH:MM:SS` (UTC).
46pub fn time_hms(ts: f64) -> String {
47    let (_, _, _, h, m, s) = split(ts);
48    format!("{h:02}:{m:02}:{s:02}")
49}
50
51/// Format as `HH:MM` (UTC).
52pub fn time_hm(ts: f64) -> String {
53    let (_, _, _, h, m, _) = split(ts);
54    format!("{h:02}:{m:02}")
55}
56
57/// Format as `YYYY-MM-DD` (UTC).
58pub fn date_ymd(ts: f64) -> String {
59    let (y, m, d, ..) = split(ts);
60    format!("{y:04}-{m:02}-{d:02}")
61}
62
63/// Format as `MM-DD` (UTC).
64pub fn date_md(ts: f64) -> String {
65    let (_, m, d, ..) = split(ts);
66    format!("{m:02}-{d:02}")
67}
68
69/// Format as `YYYY-MM-DD HH:MM:SS` (UTC).
70pub fn datetime(ts: f64) -> String {
71    format!("{} {}", date_ymd(ts), time_hms(ts))
72}
73
74const FIXED_STEPS: [f64; 22] = [
75    1.0,
76    2.0,
77    5.0,
78    10.0,
79    15.0,
80    30.0,
81    60.0,
82    120.0,
83    300.0,
84    600.0,
85    900.0,
86    1800.0,
87    3600.0,
88    7200.0,
89    10_800.0,
90    21_600.0,
91    43_200.0,
92    86_400.0,
93    172_800.0,
94    604_800.0,
95    1_209_600.0,
96    2_592_000.0,
97];
98/// Calendar steps in months (1 month .. 10 years); above these, years are scaled by 10x.
99const MONTH_STEPS: [u32; 6] = [1, 3, 6, 12, 24, 60];
100
101/// A nice time-aware step in seconds for covering `span` with about `count` ticks
102/// (1 s, 5 s, 1 min, 1 h, 1 day, 1 week, ... up to 30 days; beyond that month/year
103/// steps are returned as 30.44-day multiples, see [`time_ticks`] for calendar alignment).
104pub fn time_nice_step(span: f64, count: usize) -> f64 {
105    let raw = if span.is_finite() && span > 0.0 {
106        span / count.max(1) as f64
107    } else {
108        1.0
109    };
110    if let Some(&s) = FIXED_STEPS.iter().find(|&&s| s >= raw) {
111        return s;
112    }
113    let month = 2_629_746.0;
114    for m in MONTH_STEPS {
115        if m as f64 * month >= raw {
116            return m as f64 * month;
117        }
118    }
119    let mut y = 10.0;
120    loop {
121        for k in [1.0, 2.0, 5.0] {
122            if y * k * 12.0 * month >= raw {
123                return y * k * 12.0 * month;
124            }
125        }
126        y *= 10.0;
127        if y > 1e9 {
128            return raw;
129        }
130    }
131}
132
133/// Tick timestamps within `[min, max]`, about `count` of them. Sub-month steps
134/// align to multiples of the step (days align to UTC midnight); month/year steps
135/// align to calendar month/year starts.
136pub fn time_ticks(min: f64, max: f64, count: usize) -> Vec<f64> {
137    if !min.is_finite() || !max.is_finite() || max < min {
138        return vec![];
139    }
140    let step = time_nice_step(max - min, count);
141    if step < 2_592_000.0 + 1.0 {
142        let first = (min / step).ceil();
143        let n = ((max / step).floor() - first) as i64;
144        return (0..=n.clamp(-1, 10_000))
145            .map(|i| (first + i as f64) * step)
146            .collect();
147    }
148    let months = (step / 2_629_746.0).round().clamp(1.0, 1e9) as i64;
149    let (y, m, ..) = split(min);
150    let mut idx = y * 12 + (m as i64 - 1);
151    idx = (idx + months - 1).div_euclid(months) * months;
152    let mut out = vec![];
153    // Bounded iterations: with a huge `min` (clamped in `split`) no tick ever
154    // lands in range and `idx` would otherwise grow until it overflows.
155    let mut guard = 0u32;
156    while out.len() < 10_000 && guard < 100_000 {
157        guard += 1;
158        let (yy, mm) = (idx.div_euclid(12), idx.rem_euclid(12) as u32 + 1);
159        let t = days_from_civil(yy, mm, 1) as f64 * 86_400.0;
160        if t > max {
161            break;
162        }
163        if t >= min {
164            out.push(t);
165        }
166        idx += months;
167    }
168    out
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174
175    #[test]
176    fn civil_roundtrip_and_known_dates() {
177        assert_eq!(civil_from_days(0), (1970, 1, 1));
178        assert_eq!(civil_from_days(19_782), (2024, 2, 29));
179        assert_eq!(civil_from_days(-1), (1969, 12, 31));
180        for d in (-800_000..800_000).step_by(997) {
181            let (y, m, dd) = civil_from_days(d);
182            assert_eq!(days_from_civil(y, m, dd), d);
183        }
184    }
185
186    #[test]
187    fn formatters() {
188        assert_eq!(time_hms(3661.0), "01:01:01");
189        assert_eq!(time_hm(3661.0), "01:01");
190        assert_eq!(date_ymd(1_709_164_800.0), "2024-02-29");
191        assert_eq!(date_md(1_709_164_800.0), "02-29");
192        assert_eq!(datetime(1_709_164_800.0 + 45_296.0), "2024-02-29 12:34:56");
193        assert_eq!(date_ymd(-86_400.0), "1969-12-31");
194        assert_eq!(time_hms(f64::NAN), "00:00:00");
195        assert_eq!(time_hms(-1.0), "23:59:59");
196        let _ = datetime(f64::INFINITY);
197    }
198
199    #[test]
200    fn nice_steps() {
201        assert_eq!(time_nice_step(10.0, 10), 1.0);
202        assert_eq!(time_nice_step(3600.0, 6), 600.0);
203        assert_eq!(time_nice_step(86_400.0, 6), 21_600.0);
204        assert!(time_nice_step(1e10, 5) > 2_592_000.0);
205        assert_eq!(time_nice_step(f64::NAN, 0), 1.0);
206    }
207
208    #[test]
209    fn ticks_aligned_and_bounded() {
210        let t = time_ticks(0.0, 3600.0, 6);
211        assert_eq!(t.first(), Some(&0.0));
212        assert!(t.iter().all(|&x| (0.0..=3600.0).contains(&x)));
213        assert!(t.windows(2).all(|w| w[1] - w[0] == 600.0));
214        let year = 365.0 * 86_400.0;
215        let m = time_ticks(1_700_000_000.0, 1_700_000_000.0 + 3.0 * year, 6);
216        assert!(m.len() >= 2);
217        assert!(m.iter().all(|&x| date_ymd(x).ends_with("-01")));
218        assert!(time_ticks(5.0, 1.0, 5).is_empty());
219        assert!(time_ticks(f64::NAN, 1.0, 5).is_empty());
220        let _ = time_ticks(7.0, 7.0, 5);
221    }
222}