use std::sync::Arc;
use std::time::{Instant, SystemTime, UNIX_EPOCH};
pub trait Clock: Send + Sync + std::fmt::Debug {
fn now(&self) -> Instant;
fn unix(&self) -> i64;
}
#[derive(Debug)]
pub struct SystemClock;
impl Clock for SystemClock {
fn now(&self) -> Instant {
Instant::now()
}
fn unix(&self) -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.ok()
.and_then(|d| i64::try_from(d.as_secs()).ok())
.unwrap_or_default()
}
}
pub fn system() -> Arc<dyn Clock> {
Arc::new(SystemClock)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_system_clock_reads_the_wall_and_moves_forward() {
let clock = system();
let (a, unix) = (clock.now(), clock.unix());
assert!(unix > 1_700_000_000, "{unix}");
assert!(clock.now() >= a);
}
}