use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
pub use super::timestamp::Timestamp;
pub trait Clock: Send + Sync {
fn now(&self) -> Timestamp;
fn advance_by(&self, _duration: Duration) {}
fn set(&self, _timestamp: Timestamp) {}
}
#[derive(Debug)]
pub struct VirtualClock {
current: AtomicU64,
}
impl VirtualClock {
pub const fn new() -> Self {
Self {
current: AtomicU64::new(0),
}
}
}
impl Default for VirtualClock {
fn default() -> Self {
Self::new()
}
}
impl Clock for VirtualClock {
fn now(&self) -> Timestamp {
Timestamp::from_nanos(self.current.load(Ordering::Relaxed))
}
fn advance_by(&self, duration: Duration) {
let nanos = u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX);
let _ = self
.current
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
Some(current.saturating_add(nanos))
});
}
fn set(&self, timestamp: Timestamp) {
let nanos = timestamp.as_nanos();
let _ = self
.current
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
debug_assert!(nanos >= current, "virtual time must never move backwards");
Some(nanos)
});
}
}
#[derive(Clone, Copy, Debug)]
pub struct HostClock;
impl HostClock {
pub const fn new() -> Self {
Self
}
}
impl Default for HostClock {
fn default() -> Self {
Self::new()
}
}
impl Clock for HostClock {
fn now(&self) -> Timestamp {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
Timestamp::from_nanos(u64::try_from(nanos).unwrap_or(u64::MAX))
}
}