use std::fmt;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
pub trait Clock: Send + Sync + 'static {
fn now(&self) -> Instant;
}
#[derive(Debug, Clone, Copy, Default)]
pub struct SystemClock;
impl Clock for SystemClock {
fn now(&self) -> Instant {
Instant::now()
}
}
#[derive(Debug, Clone)]
pub struct ManualClock {
inner: Arc<ManualInner>,
}
#[derive(Debug)]
struct ManualInner {
base: Instant,
advanced_nanos: AtomicU64,
}
impl ManualClock {
#[must_use]
pub fn new() -> Self {
Self {
inner: Arc::new(ManualInner {
base: Instant::now(),
advanced_nanos: AtomicU64::new(0),
}),
}
}
pub fn advance(&self, by: Duration) {
let nanos = u64::try_from(by.as_nanos()).expect("advance fits in u64 nanoseconds");
self.inner
.advanced_nanos
.fetch_add(nanos, Ordering::Relaxed);
}
}
impl Default for ManualClock {
fn default() -> Self {
Self::new()
}
}
impl Clock for ManualClock {
fn now(&self) -> Instant {
self.inner.base + Duration::from_nanos(self.inner.advanced_nanos.load(Ordering::Relaxed))
}
}
#[derive(Clone)]
pub struct AnyClock(Arc<dyn Clock>);
impl AnyClock {
#[must_use]
pub fn new(clock: impl Clock) -> Self {
Self(Arc::new(clock))
}
#[must_use]
pub fn now(&self) -> Instant {
self.0.now()
}
#[must_use]
pub fn since(&self, earlier: Instant) -> Duration {
self.now().saturating_duration_since(earlier)
}
}
impl Default for AnyClock {
fn default() -> Self {
Self::new(SystemClock)
}
}
impl fmt::Debug for AnyClock {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("AnyClock")
}
}