1 //! Time.2 //!3 //! Two small encodings that the event object needs and that the tree cannot4 //! take from a dependency: an RFC 3339 timestamp and standard base64. Both are5 //! pure functions with published vectors, so both are pinned by tests.6 7 // --- clock ----------------------------------------------------------------8 9 /// The current time as RFC 3339 with milliseconds, always in UTC.10 ///11 /// `2026-01-01T00:00:00.100Z`. A fixed width is what makes two logs sortable as12 /// text and a golden stable.13 pub fn now_unix_seconds() -> u64 {14 std::time::SystemTime::now()15 .duration_since(std::time::UNIX_EPOCH)16 .map(|since| since.as_secs())17 .unwrap_or(0)18 }19 20 pub fn now_rfc3339() -> String {21 let since = std::time::SystemTime::now()22 .duration_since(std::time::UNIX_EPOCH)23 .unwrap_or_default();24 rfc3339(since.as_secs(), since.subsec_millis())25 }26 27 /// Formats seconds since the Unix epoch and milliseconds as RFC 3339.28 pub fn rfc3339(seconds: u64, millis: u32) -> String {29 let (year, month, day) = civil_from_days((seconds / 86_400) as i64);30 let rest = seconds % 86_400;31 let hour = rest / 3_600;32 let minute = (rest % 3_600) / 60;33 let second = rest % 60;34 format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{millis:03}Z")35 }36 37 /// Days since 1970-01-01 to a date in the proleptic Gregorian calendar.38 ///39 /// Howard Hinnant's `civil_from_days`, which is exact for every day that an40 /// `i64` can hold and needs no table.41 fn civil_from_days(days: i64) -> (i64, u32, u32) {42 let z = days + 719_468;43 let era = if z >= 0 { z } else { z - 146_096 } / 146_097;44 let doe = z - era * 146_097;45 let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;46 let y = yoe + era * 400;47 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);48 let mp = (5 * doy + 2) / 153;49 let d = (doy - (153 * mp + 2) / 5 + 1) as u32;50 let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;51 let y = if m <= 2 { y + 1 } else { y };52 (y, m, d)53 }