#![no_std]
use core::marker::PhantomData;
use spin::relax::{RelaxStrategy, Spin};
pub trait Timestamp {
type Duration: PartialOrd;
type Error;
fn now() -> Self;
fn duration_since_epoch(self) -> Self::Duration;
fn duration_since(&self, other: &Self) -> Result<Self::Duration, Self::Error>;
}
pub trait ElapsedTimer {
type Timestamp: Timestamp;
fn timeout(
&self,
from: &Self::Timestamp,
to: &Self::Timestamp,
) -> Result<bool, <Self::Timestamp as Timestamp>::Error>;
}
pub struct Timer<T: Timestamp> {
duration: T::Duration,
}
impl<T: Timestamp> Timer<T> {
pub const fn new(duration: T::Duration) -> Self {
Timer { duration }
}
pub fn borrow_duration(&self) -> &T::Duration {
&self.duration
}
pub fn borrow_mut_duration(&mut self) -> &mut T::Duration {
&mut self.duration
}
}
impl<T: Timestamp> ElapsedTimer for Timer<T> {
type Timestamp = T;
fn timeout(
&self,
from: &Self::Timestamp,
to: &Self::Timestamp,
) -> Result<bool, <Self::Timestamp as Timestamp>::Error> {
Ok(to.duration_since(from)? >= self.duration)
}
}
pub struct Delay<T: Timestamp, R: RelaxStrategy = Spin> {
duration: T::Duration,
relax: PhantomData<R>,
}
impl<T: Timestamp, R: RelaxStrategy> Delay<T, R> {
pub const fn new(duration: T::Duration) -> Self {
Delay {
duration,
relax: PhantomData::<R>,
}
}
pub fn borrow_duration(&self) -> &T::Duration {
&self.duration
}
pub fn borrow_mut_duration(&mut self) -> &mut T::Duration {
&mut self.duration
}
pub fn exec(&self) -> Result<(), T::Error> {
let start = T::now();
while T::now().duration_since(&start)? < self.duration {
R::relax();
}
Ok(())
}
}