use crate::Moment;
pub trait Clock {
type Error;
fn now(&mut self) -> Result<Moment, Self::Error>;
}
impl<C> Clock for &mut C
where
C: Clock + ?Sized,
{
type Error = C::Error;
fn now(&mut self) -> Result<Moment, Self::Error> {
(**self).now()
}
}
#[cfg(feature = "std")]
use std::{sync::Arc, time::Instant};
#[cfg(feature = "std")]
use crate::{DurationOverflow, Span};
#[cfg(feature = "std")]
#[derive(Clone, Debug)]
pub struct MonotonicClock {
origin: Arc<Instant>,
}
#[cfg(feature = "std")]
impl MonotonicClock {
pub fn new() -> Self {
Self {
origin: Arc::new(Instant::now()),
}
}
pub fn shares_origin(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.origin, &other.origin)
}
}
#[cfg(feature = "std")]
impl Default for MonotonicClock {
fn default() -> Self {
Self::new()
}
}
#[cfg(feature = "std")]
impl Clock for MonotonicClock {
type Error = DurationOverflow;
fn now(&mut self) -> Result<Moment, Self::Error> {
let elapsed = Span::try_from(self.origin.elapsed())?;
Ok(Moment::from_nanos(elapsed.as_nanos()))
}
}