use core::ops::Sub;
use core::time::Duration;
#[cfg(all(feature = "std", not(target_arch = "wasm32")))]
pub use std::time::{Instant, SystemTime, UNIX_EPOCH};
#[cfg(target_arch = "wasm32")]
pub use instant::{Instant, SystemTime};
#[cfg(target_arch = "wasm32")]
pub const UNIX_EPOCH: SystemTime = SystemTime::UNIX_EPOCH;
use super::Timestamp;
pub trait TimeSupplier {
type Now: Clone + Sub;
type StartingPoint: Clone;
fn now(&self) -> Self::StartingPoint;
fn instant_now(&self) -> Self::Now;
fn starting_point(&self) -> Self::StartingPoint;
fn duration_since_starting_point(&self, now: Self::StartingPoint) -> Duration;
fn elapsed_instant_since(&self, now: Self::Now, since: Self::Now) -> Duration;
fn elapsed_since(&self, now: Self::StartingPoint, since: Self::StartingPoint) -> Duration;
fn to_timestamp(&self, duration: Duration) -> Timestamp {
Timestamp::from(duration.as_secs())
}
}
#[cfg(feature = "std")]
impl TimeSupplier for Instant {
type Now = Self;
type StartingPoint = SystemTime;
fn now(&self) -> Self::StartingPoint {
SystemTime::now()
}
fn instant_now(&self) -> Self::Now {
Instant::now()
}
fn starting_point(&self) -> Self::StartingPoint {
UNIX_EPOCH
}
fn duration_since_starting_point(&self, now: Self::StartingPoint) -> Duration {
now.duration_since(self.starting_point())
.unwrap_or_default()
}
fn elapsed_instant_since(&self, now: Self::Now, since: Self::Now) -> Duration {
now - since
}
fn elapsed_since(&self, now: Self::StartingPoint, since: Self::StartingPoint) -> Duration {
now.duration_since(since).unwrap_or_default()
}
}