Skip to main content

datumesh_engine/
clock.rs

1//! The engine's one clock reading per request: [`Clock`] and [`SystemClock`].
2
3use std::time::{SystemTime, UNIX_EPOCH};
4
5/// Where the engine reads the time. It reads it once per request: that reading is the
6/// `issued` of every receipt the request signs, and the request's asof when none is given.
7pub trait Clock: Send + Sync {
8    /// The current time as an instant (SPEC 3.3, `YYYY-MM-DDTHH:MM:SS.ffffffZ`, UTC).
9    fn now(&self) -> String;
10}
11
12/// The system clock (UTC, microseconds).
13#[derive(Clone, Copy, Debug, Default)]
14pub struct SystemClock;
15
16impl Clock for SystemClock {
17    fn now(&self) -> String {
18        let micros = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_micros()).unwrap_or(0);
19        instant_from_unix_micros(micros)
20    }
21}
22
23/// An instant from microseconds since 1970-01-01T00:00:00Z (clamped to 9999-12-31).
24pub(crate) fn instant_from_unix_micros(micros: u128) -> String {
25    const MAX: u128 = 253_402_300_799_999_999; // 9999-12-31T23:59:59.999999Z
26    let micros = micros.min(MAX);
27    let secs = (micros / 1_000_000) as i64;
28    let frac = (micros % 1_000_000) as u32;
29    let days = secs.div_euclid(86_400);
30    let rem = secs.rem_euclid(86_400);
31    let (y, m, d) = civil_from_days(days);
32    format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.{frac:06}Z", rem / 3600, (rem % 3600) / 60, rem % 60)
33}
34
35/// Year, month, day of a day count since 1970-01-01 (Howard Hinnant's algorithm).
36pub(crate) fn civil_from_days(z: i64) -> (i64, u32, u32) {
37    let z = z + 719_468;
38    let era = z.div_euclid(146_097);
39    let doe = z.rem_euclid(146_097);
40    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
41    let y = yoe + era * 400;
42    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
43    let mp = (5 * doy + 2) / 153;
44    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
45    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
46    (if m <= 2 { y + 1 } else { y }, m, d)
47}
48
49#[cfg(test)]
50mod tests {
51    use super::*;
52
53    #[test]
54    fn instants() {
55        assert_eq!(instant_from_unix_micros(0), "1970-01-01T00:00:00.000000Z");
56        assert_eq!(instant_from_unix_micros(1_710_518_400_000_001), "2024-03-15T16:00:00.000001Z");
57        assert_eq!(instant_from_unix_micros(951_782_400_000_000), "2000-02-29T00:00:00.000000Z");
58        assert_eq!(instant_from_unix_micros(u128::MAX), "9999-12-31T23:59:59.999999Z");
59        let now = SystemClock.now();
60        datumesh_core::lexical::check_instant(&now, "$").unwrap();
61    }
62}