use std::fmt;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Instant {
nanos: u64,
}
impl Instant {
pub(crate) const fn from_nanos(nanos: u64) -> Self {
Self { nanos }
}
pub(crate) const fn as_nanos(self) -> u64 {
self.nanos
}
#[must_use]
pub const fn checked_duration_since(self, earlier: Self) -> Option<Duration> {
match self.nanos.checked_sub(earlier.nanos) {
Some(nanos) => Some(Duration::from_nanos(nanos)),
None => None,
}
}
#[must_use]
pub const fn duration_since(self, earlier: Self) -> Duration {
Duration::from_nanos(self.nanos.saturating_sub(earlier.nanos))
}
#[must_use]
pub fn checked_add(self, by: Duration) -> Option<Self> {
let nanos = u64::try_from(by.as_nanos()).ok()?;
self.nanos.checked_add(nanos).map(Self::from_nanos)
}
#[must_use]
pub fn checked_sub(self, by: Duration) -> Option<Self> {
let nanos = u64::try_from(by.as_nanos()).ok()?;
self.nanos.checked_sub(nanos).map(Self::from_nanos)
}
}
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::from_nanos(system_nanos())
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
const SYSTEM_CLOCK: rustix::time::ClockId = rustix::time::ClockId::Boottime;
#[cfg(all(unix, not(any(target_os = "linux", target_os = "android"))))]
const SYSTEM_CLOCK: rustix::time::ClockId = rustix::time::ClockId::Monotonic;
#[cfg(unix)]
fn system_nanos() -> u64 {
let now = rustix::time::clock_gettime(SYSTEM_CLOCK);
let secs = u64::try_from(now.tv_sec).expect("the system clock is not negative");
let subsec = u64::try_from(now.tv_nsec).expect("tv_nsec is not negative");
secs.checked_mul(1_000_000_000)
.and_then(|nanos| nanos.checked_add(subsec))
.expect("the system clock fits in u64 nanoseconds")
}
#[cfg(windows)]
fn system_nanos() -> u64 {
let mut ticks = 0_u64;
unsafe { windows_sys::Win32::System::WindowsProgramming::QueryInterruptTime(&raw mut ticks) };
ticks
.checked_mul(100)
.expect("the interrupt time fits in u64 nanoseconds")
}
#[derive(Debug, Clone)]
pub struct ManualClock {
advanced_nanos: Arc<AtomicU64>,
}
impl ManualClock {
#[must_use]
pub fn new() -> Self {
Self {
advanced_nanos: Arc::new(AtomicU64::new(0)),
}
}
pub fn advance(&self, by: Duration) {
let nanos = u64::try_from(by.as_nanos()).expect("advance fits in u64 nanoseconds");
self.advanced_nanos.fetch_add(nanos, Ordering::Relaxed);
}
}
impl Default for ManualClock {
fn default() -> Self {
Self::new()
}
}
impl Clock for ManualClock {
fn now(&self) -> Instant {
Instant::from_nanos(self.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().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")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_system_clock_advances() {
let clock = SystemClock;
let first = clock.now();
std::thread::sleep(Duration::from_millis(20));
assert!(clock.now().duration_since(first) >= Duration::from_millis(20));
}
#[test]
fn instants_do_arithmetic() {
let at = Instant::from_nanos(10_000);
let later = at.checked_add(Duration::from_micros(5)).unwrap();
assert_eq!(later.duration_since(at), Duration::from_micros(5));
assert_eq!(at.duration_since(later), Duration::ZERO);
assert_eq!(at.checked_duration_since(later), None);
assert_eq!(later.checked_sub(Duration::from_micros(5)), Some(at));
assert_eq!(at.checked_sub(Duration::from_secs(1)), None);
}
}