use std::cell::Cell;
use std::time::{Duration, Instant};
pub trait Clock {
fn now(&self) -> Instant;
}
#[derive(Debug, Clone, Copy, Default)]
pub struct SystemClock;
impl Clock for SystemClock {
fn now(&self) -> Instant {
Instant::now()
}
}
#[derive(Debug)]
pub struct MockClock {
now: Cell<Instant>,
}
impl MockClock {
pub fn new() -> Self {
Self {
now: Cell::new(Instant::now()),
}
}
pub fn advance(&self, dur: Duration) {
self.now.set(self.now.get() + dur);
}
pub fn advance_ms(&self, ms: u64) {
self.advance(Duration::from_millis(ms));
}
}
impl Default for MockClock {
fn default() -> Self {
Self::new()
}
}
impl Clock for MockClock {
fn now(&self) -> Instant {
self.now.get()
}
}
impl<C: Clock + ?Sized> Clock for &C {
fn now(&self) -> Instant {
(**self).now()
}
}