use std::{
fmt,
sync::{Arc, Mutex, MutexGuard},
time::{Duration, Instant},
};
#[cfg(feature = "time")]
use time::OffsetDateTime;
pub trait Clock: Send + Sync + 'static {
fn now(&self) -> Instant;
}
pub type SharedClock = Arc<dyn Clock>;
#[cfg(feature = "time")]
#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
pub trait UtcClock: Send + Sync + 'static {
fn now_utc(&self) -> OffsetDateTime;
}
#[cfg(feature = "time")]
#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
pub type SharedUtcClock = Arc<dyn UtcClock>;
#[must_use]
pub fn system_clock() -> SharedClock {
Arc::new(SystemClock)
}
#[cfg(feature = "time")]
#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
#[must_use]
pub fn system_utc_clock() -> SharedUtcClock {
Arc::new(SystemUtcClock)
}
fn lock_clock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ClockOverflow;
impl fmt::Display for ClockOverflow {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("clock value exceeds the supported time range")
}
}
impl std::error::Error for ClockOverflow {}
#[derive(Debug, Clone, Copy, Default)]
pub struct SystemClock;
impl Clock for SystemClock {
fn now(&self) -> Instant {
Instant::now()
}
}
#[cfg(feature = "time")]
#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
#[derive(Debug, Clone, Copy, Default)]
pub struct SystemUtcClock;
#[cfg(feature = "time")]
impl UtcClock for SystemUtcClock {
fn now_utc(&self) -> OffsetDateTime {
OffsetDateTime::now_utc()
}
}
#[derive(Clone)]
pub struct ManualClock {
instant: Arc<Mutex<Instant>>,
}
impl ManualClock {
#[must_use]
pub fn new() -> Self {
Self::at(Instant::now())
}
#[must_use]
pub fn at(instant: Instant) -> Self {
Self {
instant: Arc::new(Mutex::new(instant)),
}
}
pub fn advance(&self, duration: Duration) -> Result<(), ClockOverflow> {
let mut instant = lock_clock(&self.instant);
*instant = instant.checked_add(duration).ok_or(ClockOverflow)?;
Ok(())
}
pub fn set(&self, instant: Instant) {
*lock_clock(&self.instant) = instant;
}
#[must_use]
pub fn shared(&self) -> SharedClock {
Arc::new(self.clone())
}
}
impl Default for ManualClock {
fn default() -> Self {
Self::new()
}
}
impl Clock for ManualClock {
fn now(&self) -> Instant {
*lock_clock(&self.instant)
}
}
impl fmt::Debug for ManualClock {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ManualClock")
.field("instant", &self.now())
.finish()
}
}
#[cfg(feature = "time")]
#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
#[derive(Clone)]
pub struct ManualUtcClock {
now: Arc<Mutex<OffsetDateTime>>,
}
#[cfg(feature = "time")]
impl ManualUtcClock {
#[must_use]
pub fn new() -> Self {
Self {
now: Arc::new(Mutex::new(OffsetDateTime::now_utc())),
}
}
pub fn at(now: OffsetDateTime) -> Result<Self, ClockOverflow> {
let now = now
.checked_to_offset(time::UtcOffset::UTC)
.ok_or(ClockOverflow)?;
Ok(Self {
now: Arc::new(Mutex::new(now)),
})
}
pub fn advance(&self, duration: Duration) -> Result<(), ClockOverflow> {
let duration = time::Duration::try_from(duration).map_err(|_| ClockOverflow)?;
let mut now = lock_clock(&self.now);
*now = now.checked_add(duration).ok_or(ClockOverflow)?;
Ok(())
}
pub fn set(&self, now: OffsetDateTime) -> Result<(), ClockOverflow> {
let now = now
.checked_to_offset(time::UtcOffset::UTC)
.ok_or(ClockOverflow)?;
*lock_clock(&self.now) = now;
Ok(())
}
#[must_use]
pub fn shared(&self) -> SharedUtcClock {
Arc::new(self.clone())
}
}
#[cfg(feature = "time")]
impl Default for ManualUtcClock {
fn default() -> Self {
Self::new()
}
}
#[cfg(feature = "time")]
impl UtcClock for ManualUtcClock {
fn now_utc(&self) -> OffsetDateTime {
*lock_clock(&self.now)
}
}
#[cfg(feature = "time")]
impl fmt::Debug for ManualUtcClock {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ManualUtcClock")
.field("now", &self.now_utc())
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn manual_clock_advances_monotonic_time() {
let clock = ManualClock::new();
let start = clock.now();
clock.advance(Duration::from_secs(5)).unwrap();
assert_eq!(clock.now().duration_since(start), Duration::from_secs(5));
}
#[test]
fn manual_clock_reports_overflow_without_changing_time() {
let clock = ManualClock::new();
let start = clock.now();
assert_eq!(clock.advance(Duration::MAX), Err(ClockOverflow));
assert_eq!(clock.now(), start);
}
#[test]
fn manual_clock_recovers_from_poisoned_lock() {
let clock = ManualClock::new();
let poisoned = clock.clone();
let _ = std::thread::spawn(move || {
let _guard = poisoned.instant.lock().expect("test lock should acquire");
panic!("poison manual clock lock");
})
.join();
let expected = Instant::now();
clock.set(expected);
assert_eq!(clock.now(), expected);
}
#[cfg(feature = "time")]
#[test]
fn manual_utc_clock_advances_wall_time() {
let clock = ManualUtcClock::at(OffsetDateTime::UNIX_EPOCH).unwrap();
clock.advance(Duration::from_secs(90)).unwrap();
assert_eq!(
clock.now_utc(),
OffsetDateTime::UNIX_EPOCH + time::Duration::seconds(90)
);
}
#[cfg(feature = "time")]
#[test]
fn manual_utc_clock_normalizes_offsets_without_changing_the_instant() {
use time::{Date, Month, UtcOffset};
let local = Date::from_calendar_date(2025, Month::January, 1)
.unwrap()
.with_hms(2, 30, 0)
.unwrap()
.assume_offset(UtcOffset::from_hms(8, 0, 0).unwrap());
let clock = ManualUtcClock::at(local).unwrap();
let utc = clock.now_utc();
assert_eq!(utc.offset(), UtcOffset::UTC);
assert_eq!(utc.to_calendar_date(), (2024, Month::December, 31));
assert_eq!(utc.to_hms(), (18, 30, 0));
assert_eq!(utc.unix_timestamp_nanos(), local.unix_timestamp_nanos());
let local = local
.replace_time(time::Time::from_hms(23, 45, 0).unwrap())
.replace_offset(UtcOffset::from_hms(-5, 0, 0).unwrap());
clock.set(local).unwrap();
let utc = clock.now_utc();
assert_eq!(utc.offset(), UtcOffset::UTC);
assert_eq!(utc.to_calendar_date(), (2025, Month::January, 2));
assert_eq!(utc.to_hms(), (4, 45, 0));
assert_eq!(utc.unix_timestamp_nanos(), local.unix_timestamp_nanos());
}
#[cfg(feature = "time")]
#[test]
fn manual_utc_clock_rejects_offsets_outside_the_utc_range() {
let clock = ManualUtcClock::at(OffsetDateTime::UNIX_EPOCH).unwrap();
for timestamp in [
time::Date::MIN
.midnight()
.assume_offset(time::UtcOffset::from_hms(1, 0, 0).unwrap()),
time::Date::MAX
.with_time(time::Time::MAX)
.assume_offset(time::UtcOffset::from_hms(-1, 0, 0).unwrap()),
] {
assert!(matches!(ManualUtcClock::at(timestamp), Err(ClockOverflow)));
assert_eq!(clock.set(timestamp), Err(ClockOverflow));
assert_eq!(clock.now_utc(), OffsetDateTime::UNIX_EPOCH);
assert_eq!(clock.now_utc().offset(), time::UtcOffset::UTC);
}
}
#[cfg(feature = "time")]
#[test]
fn manual_utc_clock_reports_conversion_and_timestamp_overflow() {
let clock = ManualUtcClock::at(OffsetDateTime::UNIX_EPOCH).unwrap();
assert_eq!(clock.advance(Duration::MAX), Err(ClockOverflow));
assert_eq!(clock.now_utc(), OffsetDateTime::UNIX_EPOCH);
let end = time::Date::MAX.with_time(time::Time::MAX).assume_utc();
clock.set(end).unwrap();
assert_eq!(clock.advance(Duration::from_nanos(1)), Err(ClockOverflow));
assert_eq!(clock.now_utc(), end);
}
#[cfg(feature = "time")]
#[test]
fn manual_utc_clock_recovers_from_poisoned_lock() {
let clock = ManualUtcClock::at(OffsetDateTime::UNIX_EPOCH).unwrap();
let poisoned = clock.clone();
let _ = std::thread::spawn(move || {
let _guard = poisoned.now.lock().expect("test lock should acquire");
panic!("poison manual UTC clock lock");
})
.join();
let expected = OffsetDateTime::UNIX_EPOCH + time::Duration::days(1);
clock.set(expected).unwrap();
assert_eq!(clock.now_utc(), expected);
}
}