use prometeu_hal::WallClock; use std::time::{SystemTime, UNIX_EPOCH}; /// Desktop civil time. Synchronization and clock adjustments belong to the OS. #[derive(Debug, Default)] pub struct SystemWallClock; impl WallClock for SystemWallClock { fn utc_unix_seconds(&self) -> u64 { seconds_from_system_time(SystemTime::now()) } } fn seconds_from_system_time(time: SystemTime) -> u64 { match time.duration_since(UNIX_EPOCH) { Ok(duration) => seconds_from_unix_nanos(duration.as_nanos()), Err(_) => 0, } } fn seconds_from_unix_nanos(nanos: u128) -> u64 { u64::try_from(nanos / 1_000_000_000).unwrap_or(u64::MAX) } #[cfg(test)] mod tests { use super::*; use std::time::Duration; #[test] fn conversion_truncates_fractions_and_saturates_at_both_limits() { assert_eq!(seconds_from_system_time(UNIX_EPOCH), 0); assert_eq!(seconds_from_system_time(UNIX_EPOCH - Duration::from_nanos(1)), 0); assert_eq!(seconds_from_system_time(UNIX_EPOCH - Duration::from_secs(1)), 0); assert_eq!(seconds_from_system_time(UNIX_EPOCH + Duration::from_millis(999)), 0); assert_eq!(seconds_from_system_time(UNIX_EPOCH + Duration::from_millis(1_900)), 1); let limit = u128::from(u64::MAX) * 1_000_000_000; assert_eq!(seconds_from_unix_nanos(limit - 1), u64::MAX - 1); assert_eq!(seconds_from_unix_nanos(limit), u64::MAX); assert_eq!(seconds_from_unix_nanos(limit + 1_000_000_000), u64::MAX); assert_eq!(seconds_from_unix_nanos(u128::MAX), u64::MAX); } #[test] fn system_provider_reads_current_local_time() { let before = seconds_from_system_time(SystemTime::now()); let actual = SystemWallClock.utc_unix_seconds(); let after = seconds_from_system_time(SystemTime::now()); // A wall-clock adjustment may reverse the bounding samples. assert!((before.min(after)..=before.max(after)).contains(&actual)); } }