use crate::{
MonotonicClock,
MonotonicInstant,
TimeError,
TimerFuture,
};
use std::time::Duration;
pub trait Timer: Send + Sync {
#[must_use = "the Timer clock should be used to sample or validate deadlines"]
fn clock(&self) -> &dyn MonotonicClock;
#[must_use = "the current timer instant should be used to measure or validate deadlines"]
#[inline(always)]
fn now(&self) -> MonotonicInstant {
self.clock().now()
}
fn at(&self, deadline: MonotonicInstant) -> Result<TimerFuture, TimeError>;
#[inline]
fn after(&self, duration: Duration) -> Result<TimerFuture, TimeError> {
let deadline = self.now().checked_add(duration)?;
self.at(deadline)
}
}
impl<T> Timer for std::sync::Arc<T>
where
T: Timer + ?Sized,
{
#[inline(always)]
fn clock(&self) -> &dyn MonotonicClock {
self.as_ref().clock()
}
#[inline(always)]
fn at(&self, deadline: MonotonicInstant) -> Result<TimerFuture, TimeError> {
self.as_ref().at(deadline)
}
#[inline(always)]
fn after(&self, duration: Duration) -> Result<TimerFuture, TimeError> {
self.as_ref().after(duration)
}
}
impl<T> Timer for Box<T>
where
T: Timer + ?Sized,
{
#[inline(always)]
fn clock(&self) -> &dyn MonotonicClock {
self.as_ref().clock()
}
#[inline(always)]
fn at(&self, deadline: MonotonicInstant) -> Result<TimerFuture, TimeError> {
self.as_ref().at(deadline)
}
#[inline(always)]
fn after(&self, duration: Duration) -> Result<TimerFuture, TimeError> {
self.as_ref().after(duration)
}
}