use std::time::SystemTime;
pub trait Clock {
fn now(&self) -> SystemTime;
}
#[derive(Clone, Copy)]
pub struct SystemClock;
impl Clock for SystemClock {
fn now(&self) -> SystemTime {
SystemTime::now()
}
}
impl<C: Clock> Clock for &C {
fn now(&self) -> SystemTime {
(*self).now()
}
}
#[cfg(any(test, feature = "test-dependencies"))]
pub mod testing {
use std::sync::{Arc, RwLock};
use std::time::SystemTime;
use std::time::Duration;
use super::Clock;
#[derive(Clone)]
pub struct FixedClock {
now: Arc<RwLock<SystemTime>>,
}
impl FixedClock {
pub fn new(now: SystemTime) -> Self {
Self {
now: Arc::new(RwLock::new(now)),
}
}
pub fn tick(&self, delta: Duration) {
let mut w = self.now.write().unwrap();
*w += delta;
}
}
impl Clock for FixedClock {
fn now(&self) -> SystemTime {
*self.now.read().unwrap()
}
}
}