use std::collections::BTreeMap;
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::time::{Duration, Instant};
pub type Job = Box<dyn FnOnce() + Send>;
pub trait Clock: Send + Sync + std::fmt::Debug {
fn now(&self) -> Duration;
fn at(&self, at: Duration, job: Job);
}
#[derive(Default)]
struct Timers {
jobs: BTreeMap<(Duration, u64), Job>,
seq: u64,
}
impl Timers {
fn add(&mut self, at: Duration, job: Job) {
self.seq += 1;
self.jobs.insert((at, self.seq), job);
}
fn due(&mut self, now: Duration) -> Option<Job> {
let first = *self.jobs.keys().next()?;
(first.0 <= now).then(|| self.jobs.remove(&first)).flatten()
}
fn next(&self) -> Option<Duration> {
self.jobs.keys().next().map(|k| k.0)
}
}
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
m.lock().unwrap_or_else(|e| e.into_inner())
}
#[derive(Debug, Clone)]
pub struct SystemClock(Arc<SystemInner>);
struct SystemInner {
start: Instant,
timers: Mutex<(Timers, bool)>,
wake: Condvar,
}
impl std::fmt::Debug for SystemInner {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SystemClock").finish_non_exhaustive()
}
}
impl Default for SystemClock {
fn default() -> Self {
Self::new()
}
}
impl SystemClock {
pub fn new() -> Self {
Self(Arc::new(SystemInner {
start: Instant::now(),
timers: Mutex::new((Timers::default(), false)),
wake: Condvar::new(),
}))
}
}
impl Clock for SystemClock {
fn now(&self) -> Duration {
self.0.start.elapsed()
}
fn at(&self, at: Duration, job: Job) {
let mut timers = lock(&self.0.timers);
timers.0.add(at, job);
if !timers.1 {
timers.1 = true;
let inner = Arc::downgrade(&self.0);
std::thread::spawn(move || run_system(inner));
}
drop(timers);
self.0.wake.notify_all();
}
}
fn run_system(inner: std::sync::Weak<SystemInner>) {
loop {
let Some(clock) = inner.upgrade() else {
return;
};
let mut timers = lock(&clock.timers);
let now = clock.start.elapsed();
if let Some(job) = timers.0.due(now) {
drop(timers);
let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(job));
continue;
}
let wait = timers
.0
.next()
.map_or(Duration::from_millis(100), |next| next - now)
.min(Duration::from_millis(100));
let _woken = clock.wake.wait_timeout(timers, wait);
}
}
#[derive(Clone, Default)]
pub struct ManualClock(Arc<Mutex<(Duration, Timers)>>);
impl std::fmt::Debug for ManualClock {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("ManualClock").field(&self.now()).finish()
}
}
impl ManualClock {
pub fn new() -> Self {
Self::default()
}
pub fn advance(&self, by: Duration) {
let target = lock(&self.0).0 + by;
loop {
let mut state = lock(&self.0);
let Some(next) = state.1.next().filter(|next| *next <= target) else {
state.0 = state.0.max(target);
return;
};
state.0 = state.0.max(next);
let now = state.0;
let job = state.1.due(now);
drop(state);
if let Some(job) = job {
job();
}
}
}
}
impl Clock for ManualClock {
fn now(&self) -> Duration {
lock(&self.0).0
}
fn at(&self, at: Duration, job: Job) {
lock(&self.0).1.add(at, job);
}
}
#[cfg(feature = "tokio")]
#[derive(Debug, Clone)]
pub struct TokioClock(Arc<TokioInner>);
#[cfg(feature = "tokio")]
struct TokioInner {
start: tokio::time::Instant,
runtime: tokio::runtime::Handle,
timers: Mutex<Timers>,
running: Mutex<()>,
}
#[cfg(feature = "tokio")]
impl std::fmt::Debug for TokioInner {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TokioClock").finish_non_exhaustive()
}
}
#[cfg(feature = "tokio")]
impl TokioClock {
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
Self(Arc::new(TokioInner {
start: tokio::time::Instant::now(),
runtime: tokio::runtime::Handle::current(),
timers: Mutex::new(Timers::default()),
running: Mutex::new(()),
}))
}
}
#[cfg(feature = "tokio")]
impl Clock for TokioClock {
fn now(&self) -> Duration {
let _runtime = self.0.runtime.enter();
self.0.start.elapsed()
}
fn at(&self, at: Duration, job: Job) {
lock(&self.0.timers).add(at, job);
let inner = self.0.clone();
self.0.runtime.spawn(async move {
tokio::time::sleep_until(inner.start + at).await;
let _running = lock(&inner.running);
loop {
let job = lock(&inner.timers).due(inner.start.elapsed());
let Some(job) = job else { break };
job();
}
});
}
}