Skip to main content

khagole_engine/
instant.rs

1//! UTC instants with microsecond resolution, mirroring the Python `datetime` behaviour
2//! the reference implementation relies on (ISO formatting, float-day arithmetic).
3
4use std::fmt;
5
6use crate::time::julian_day;
7
8const US_PER_SECOND: i64 = 1_000_000;
9const US_PER_DAY: i64 = 86_400 * US_PER_SECOND;
10/// Latest year [`UtcInstant::parse`] accepts: past every JPL kernel (DE441 ends in 17191)
11/// and far from overflowing the microsecond count.
12const MAX_YEAR: i32 = 200_000;
13
14/// A UTC instant, as microseconds since 1970-01-01T00:00:00Z.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
16pub struct UtcInstant {
17    micros: i64,
18}
19
20/// Days since 1970-01-01 of a proleptic-Gregorian date (H. Hinnant, `days_from_civil`).
21fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
22    let y = if month <= 2 { year - 1 } else { year };
23    let era = y.div_euclid(400);
24    let yoe = y - era * 400;
25    let mp = (month + 9) % 12;
26    let doy = (153 * mp + 2) / 5 + day - 1;
27    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
28    era * 146_097 + doe - 719_468
29}
30
31pub fn days_in_month(year: i32, month: u32) -> u32 {
32    match month {
33        2 if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) => 29,
34        2 => 28,
35        4 | 6 | 9 | 11 => 30,
36        _ => 31,
37    }
38}
39
40fn civil_from_days(z: i64) -> (i64, i64, i64) {
41    let z = z + 719_468;
42    let era = z.div_euclid(146_097);
43    let doe = z - era * 146_097;
44    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
45    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
46    let mp = (5 * doy + 2) / 153;
47    let day = doy - (153 * mp + 2) / 5 + 1;
48    let month = if mp < 10 { mp + 3 } else { mp - 9 };
49    let year = yoe + era * 400 + i64::from(month <= 2);
50    (year, month, day)
51}
52
53/// The text given to [`UtcInstant::parse`] is not a supported date-time.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct ParseError(pub String);
56
57impl fmt::Display for ParseError {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        write!(f, "invalid UTC date-time: {}", self.0)
60    }
61}
62
63impl std::error::Error for ParseError {}
64
65impl UtcInstant {
66    /// 2000-01-01T12:00:00Z.
67    pub const J2000: UtcInstant = UtcInstant {
68        micros: 946_728_000 * US_PER_SECOND,
69    };
70
71    /// From microseconds since the Unix epoch.
72    pub fn from_micros(micros: i64) -> Self {
73        UtcInstant { micros }
74    }
75
76    /// From UT Julian day number.
77    pub fn from_julian_day(jd: f64) -> Self {
78        let days = jd - 2_440_587.5;
79        let micros = (days * 86_400.0 * 1_000_000.0).round() as i64;
80        UtcInstant { micros }
81    }
82
83    /// Microseconds since the Unix epoch.
84    pub fn micros(&self) -> i64 {
85        self.micros
86    }
87
88    /// From proleptic-Gregorian calendar fields (UTC). Out-of-range fields roll over
89    /// (day 32 is the next month's first); the result saturates instead of overflowing.
90    pub fn from_civil(
91        year: i32,
92        month: u32,
93        day: u32,
94        hour: u32,
95        minute: u32,
96        second: u32,
97        microsecond: u32,
98    ) -> Self {
99        let days = days_from_civil(year as i64, month as i64, day as i64);
100        let secs = hour as i64 * 3600 + minute as i64 * 60 + second as i64;
101        UtcInstant {
102            micros: days
103                .saturating_mul(US_PER_DAY)
104                .saturating_add(secs * US_PER_SECOND + microsecond as i64),
105        }
106    }
107
108    /// (year, month, day, hour, minute, second, microsecond)
109    pub fn civil(&self) -> (i32, u32, u32, u32, u32, u32, u32) {
110        let days = self.micros.div_euclid(US_PER_DAY);
111        let rem = self.micros.rem_euclid(US_PER_DAY);
112        let (y, m, d) = civil_from_days(days);
113        let secs = rem / US_PER_SECOND;
114        (
115            y as i32,
116            m as u32,
117            d as u32,
118            (secs / 3600) as u32,
119            (secs % 3600 / 60) as u32,
120            (secs % 60) as u32,
121            (rem % US_PER_SECOND) as u32,
122        )
123    }
124
125    /// Python `datetime.weekday()`: Monday is 0.
126    pub fn weekday(&self) -> u32 {
127        // 1970-01-01 was a Thursday (3).
128        (self.micros.div_euclid(US_PER_DAY) + 3).rem_euclid(7) as u32
129    }
130
131    /// Julian day as the reference computes it from calendar fields.
132    pub fn julian_day(&self) -> f64 {
133        let (y, m, d, hh, mm, ss, us) = self.civil();
134        let hour =
135            hh as f64 + (mm as f64 / 60.0) + (ss as f64 / 3600.0) + (us as f64 / 3_600_000_000.0);
136        julian_day(y, m, d, hour)
137    }
138
139    /// Seconds from `other` to `self`, like Python `(self - other).total_seconds()`.
140    pub fn seconds_since(&self, other: &UtcInstant) -> f64 {
141        (self.micros - other.micros) as f64 / US_PER_SECOND as f64
142    }
143
144    /// `micros` microseconds later (earlier if negative), saturating at the ends of the
145    /// representable range.
146    pub fn add_micros(&self, micros: i64) -> Self {
147        UtcInstant {
148            micros: self.micros.saturating_add(micros),
149        }
150    }
151
152    /// `self + timedelta(days=days)`, with CPython's rounding of float days to
153    /// microseconds (whole days exact, fraction rounded half to even).
154    pub fn plus_days(&self, days: f64) -> Self {
155        self.add_micros(timedelta_days_to_micros(days))
156    }
157
158    /// Same day at another time of day (Python `dt.replace(hour=…, minute=…)`).
159    pub fn with_time(&self, hour: u32, minute: u32, second: u32, microsecond: u32) -> Self {
160        let (y, m, d, ..) = self.civil();
161        UtcInstant::from_civil(y, m, d, hour, minute, second, microsecond)
162    }
163
164    /// Python `datetime.isoformat()` of an aware UTC datetime.
165    pub fn isoformat(&self) -> String {
166        let (y, m, d, hh, mm, ss, us) = self.civil();
167        let fraction = if us == 0 {
168            String::new()
169        } else {
170            format!(".{us:06}")
171        };
172        format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}{fraction}+00:00")
173    }
174
175    /// Parse `YYYY-MM-DDTHH:MM[:SS[.ffffff]]` with an optional `Z` or `+00:00` suffix.
176    /// The date must exist (no 31 February) and the year be at most 200 000.
177    pub fn parse(text: &str) -> Result<Self, ParseError> {
178        let err = || ParseError(text.to_string());
179        let body = text
180            .strip_suffix('Z')
181            .or_else(|| text.strip_suffix("+00:00"))
182            .unwrap_or(text);
183        let (date, time) = body.split_once(['T', ' ']).ok_or_else(err)?;
184        let mut d = date.split('-');
185        let year: i32 = d.next().and_then(|v| v.parse().ok()).ok_or_else(err)?;
186        let month: u32 = d.next().and_then(|v| v.parse().ok()).ok_or_else(err)?;
187        let day: u32 = d.next().and_then(|v| v.parse().ok()).ok_or_else(err)?;
188        let mut t = time.split(':');
189        let hour: u32 = t.next().and_then(|v| v.parse().ok()).ok_or_else(err)?;
190        let minute: u32 = t.next().and_then(|v| v.parse().ok()).ok_or_else(err)?;
191        let (second, micro) = match t.next() {
192            None => (0, 0),
193            Some(s) => {
194                let (whole, frac) = s.split_once('.').unwrap_or((s, ""));
195                let second: u32 = whole.parse().map_err(|_| err())?;
196                let micro = if frac.is_empty() {
197                    0
198                } else {
199                    let digits: String = frac.chars().chain("000000".chars()).take(6).collect();
200                    digits.parse().map_err(|_| err())?
201                };
202                (second, micro)
203            }
204        };
205        if !(0..=MAX_YEAR).contains(&year)
206            || !(1..=12).contains(&month)
207            || day == 0
208            || day > days_in_month(year, month)
209            || hour > 23
210            || minute > 59
211            || second > 59
212        {
213            return Err(err());
214        }
215        Ok(UtcInstant::from_civil(
216            year, month, day, hour, minute, second, micro,
217        ))
218    }
219}
220
221/// CPython `timedelta(days=x)` for a float `x`, in microseconds.
222fn timedelta_days_to_micros(days: f64) -> i64 {
223    let int_part = days.trunc();
224    let frac_part = days - int_part;
225    let mut total = int_part as i64 * US_PER_DAY;
226    if frac_part == 0.0 {
227        return total;
228    }
229    let scaled = US_PER_DAY as f64 * frac_part;
230    let scaled_int = scaled.trunc();
231    let leftover = scaled - scaled_int;
232    total += scaled_int as i64;
233    if leftover != 0.0 {
234        let mut whole = leftover.round();
235        if (whole - leftover).abs() == 0.5 {
236            // Half-way: round so that the total is even.
237            let odd = f64::from(total.rem_euclid(2) == 1);
238            whole = 2.0 * ((leftover + odd) * 0.5).round() - odd;
239        }
240        total += whole as i64;
241    }
242    total
243}
244
245impl fmt::Display for UtcInstant {
246    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
247        f.write_str(&self.isoformat())
248    }
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254
255    #[test]
256    fn civil_round_trip_and_weekday() {
257        let t = UtcInstant::from_civil(2024, 2, 29, 23, 59, 59, 123_456);
258        assert_eq!(t.civil(), (2024, 2, 29, 23, 59, 59, 123_456));
259        assert_eq!(t.isoformat(), "2024-02-29T23:59:59.123456+00:00");
260        assert_eq!(t.weekday(), 3); // Thursday
261        assert_eq!(UtcInstant::J2000.isoformat(), "2000-01-01T12:00:00+00:00");
262        assert_eq!(UtcInstant::J2000.weekday(), 5); // Saturday
263        let old = UtcInstant::from_civil(1850, 1, 2, 0, 0, 0, 0);
264        assert_eq!(old.civil(), (1850, 1, 2, 0, 0, 0, 0));
265    }
266
267    #[test]
268    fn parses_iso() {
269        let t = UtcInstant::parse("1987-03-20T21:52:00").unwrap();
270        assert_eq!(t, UtcInstant::from_civil(1987, 3, 20, 21, 52, 0, 0));
271        let t = UtcInstant::parse("2000-01-01T05:59:33.272404+00:00").unwrap();
272        assert_eq!(t.civil().6, 272_404);
273        assert!(UtcInstant::parse("2000-13-01T00:00").is_err());
274        assert!(UtcInstant::parse("2001-02-29T00:00").is_err());
275        assert!(UtcInstant::parse("2023-04-31T00:00").is_err());
276        assert!(UtcInstant::parse("2000-02-29T00:00").is_ok());
277        assert!(UtcInstant::parse("1900-02-29T00:00").is_err());
278        assert!(UtcInstant::parse("2147483647-01-01T00:00").is_err());
279        assert!(UtcInstant::parse("17191-01-01T00:00").is_ok());
280    }
281
282    #[test]
283    fn julian_day_matches_formula() {
284        assert_eq!(UtcInstant::J2000.julian_day(), 2_451_545.0);
285    }
286
287    #[test]
288    fn float_days_round_like_python() {
289        // Python: timedelta(days=0.5) == 12 h; timedelta(days=1/3) == 8:00:00
290        assert_eq!(timedelta_days_to_micros(0.5), US_PER_DAY / 2);
291        assert_eq!(timedelta_days_to_micros(1.0 / 3.0), 28_800_000_000);
292        assert_eq!(timedelta_days_to_micros(-0.25), -US_PER_DAY / 4);
293    }
294}