1use std::time::{SystemTime, UNIX_EPOCH};
4
5pub trait Clock: Send + Sync {
8 fn now(&self) -> String;
10}
11
12#[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
23pub(crate) fn instant_from_unix_micros(micros: u128) -> String {
25 const MAX: u128 = 253_402_300_799_999_999; 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
35pub(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}