//! Defines an injectable clock, for testing time-sensitive code. use std::time::SystemTime; #[cfg(test)] mod simulated { use std::sync::Arc; use std::time::SystemTime; use parking_lot::Mutex; #[derive(Debug)] pub struct Clock { now: Arc>, } impl Clock { pub fn new(now: SystemTime) -> Self { Self { now: Arc::new(Mutex::new(now)), } } pub fn now(&self) -> SystemTime { *self.now.lock() } } } #[cfg(test)] pub use simulated::Clock as SimulatedSystemClock; #[derive(Debug, Default)] pub struct SystemClock { #[cfg(test)] simulated_clock: Option, } impl SystemClock { #[cfg(test)] pub fn set_simulated_clock(&mut self, clock: Option) { self.simulated_clock = clock } pub fn now(&self) -> SystemTime { #[cfg(test)] if let Some(ref clock) = self.simulated_clock { return clock.now(); } SystemTime::now() } }