Skip to main content

loadmaster_probe/
time.rs

1//! UTC timestamps for the write boundary (SQLite rows, lockfile verdicts). Nothing else in
2//! the probe reads the clock.
3
4use std::time::{SystemTime, UNIX_EPOCH};
5
6/// `YYYY-MM-DDTHH:MM:SSZ` for a Unix time.
7pub fn rfc3339(unix_secs: u64) -> String {
8    let days = (unix_secs / 86_400) as i64;
9    let secs = unix_secs % 86_400;
10    // Civil date from days since 1970-01-01 (H. Hinnant, "chrono-Compatible Low-Level Date
11    // Algorithms").
12    let z = days + 719_468;
13    let era = z.div_euclid(146_097);
14    let doe = z.rem_euclid(146_097);
15    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
16    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
17    let mp = (5 * doy + 2) / 153;
18    let d = doy - (153 * mp + 2) / 5 + 1;
19    let m = if mp < 10 { mp + 3 } else { mp - 9 };
20    let y = yoe + era * 400 + i64::from(m <= 2);
21    format!(
22        "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z",
23        secs / 3600,
24        secs / 60 % 60,
25        secs % 60
26    )
27}
28
29pub fn now() -> String {
30    rfc3339(
31        SystemTime::now()
32            .duration_since(UNIX_EPOCH)
33            .map_or(0, |d| d.as_secs()),
34    )
35}
36
37#[cfg(test)]
38mod tests {
39    #[test]
40    fn known_dates() {
41        assert_eq!(super::rfc3339(0), "1970-01-01T00:00:00Z");
42        assert_eq!(super::rfc3339(951_782_400), "2000-02-29T00:00:00Z");
43        assert_eq!(super::rfc3339(1_792_281_600), "2026-10-18T00:00:00Z");
44    }
45}