//! 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<Mutex<SystemTime>>,
|
|
}
|
|
|
|
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<SimulatedSystemClock>,
|
|
}
|
|
|
|
impl SystemClock {
|
|
#[cfg(test)]
|
|
pub fn set_simulated_clock(&mut self, clock: Option<SimulatedSystemClock>) {
|
|
self.simulated_clock = clock
|
|
}
|
|
|
|
pub fn now(&self) -> SystemTime {
|
|
#[cfg(test)]
|
|
if let Some(ref clock) = self.simulated_clock {
|
|
return clock.now();
|
|
}
|
|
|
|
SystemTime::now()
|
|
}
|
|
}
|