use super::{Clock, Reference};
use crate::lib::*;
use parking_lot::Mutex;
use std::time::SystemTime;
pub type DefaultClock = MonotonicClock;
#[derive(Debug, Clone)]
pub struct FakeAbsoluteClock {
now: Arc<Mutex<Instant>>,
}
impl Default for FakeAbsoluteClock {
fn default() -> Self {
FakeAbsoluteClock {
now: Arc::new(Mutex::new(Instant::now())),
}
}
}
impl FakeAbsoluteClock {
pub fn advance(&mut self, by: Duration) {
*(self.now.lock()) += by
}
}
impl Clock for FakeAbsoluteClock {
type Instant = Instant;
fn now(&self) -> Self::Instant {
*self.now.lock()
}
}
#[derive(Clone, Debug, Default)]
pub struct MonotonicClock();
impl Reference for Instant {
fn duration_since(&self, earlier: Self) -> Duration {
if earlier < *self {
*self - earlier
} else {
Duration::new(0, 0)
}
}
fn saturating_sub(&self, duration: Duration) -> Self {
self.checked_sub(duration).unwrap_or(*self)
}
}
impl Clock for MonotonicClock {
type Instant = Instant;
fn now(&self) -> Self::Instant {
Instant::now()
}
}
#[derive(Clone, Debug, Default)]
pub struct SystemClock();
impl Reference for SystemTime {
fn duration_since(&self, earlier: Self) -> Duration {
self.duration_since(earlier)
.unwrap_or_else(|_| Duration::new(0, 0))
}
fn saturating_sub(&self, duration: Duration) -> Self {
self.checked_sub(duration).unwrap_or(*self)
}
}
impl Clock for SystemClock {
type Instant = SystemTime;
fn now(&self) -> Self::Instant {
SystemTime::now()
}
}