use std::{
ops::{Add, AddAssign, Sub, SubAssign},
time::Duration,
};
type StdInstant = std::time::Instant;
#[ctor::ctor]
static START_INSTANT: StdInstant = StdInstant::now();
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Instant(Duration);
impl Instant {
#[must_use]
pub fn now() -> Self {
Self(super::uptime())
}
#[must_use]
pub fn duration_since(&self, earlier: Self) -> Duration {
self.checked_duration_since(earlier).unwrap_or_default()
}
#[must_use]
pub fn elapsed(&self) -> Duration {
Self::now().duration_since(*self)
}
pub fn checked_add(&self, duration: Duration) -> Option<Self> {
self.0.checked_add(duration).map(Instant)
}
pub fn checked_sub(&self, duration: Duration) -> Option<Self> {
self.0.checked_sub(duration).map(Instant)
}
#[must_use]
pub fn checked_duration_since(&self, earlier: Self) -> Option<Duration> {
if earlier.0 > self.0 {
None
} else {
Some(self.0 - earlier.0)
}
}
#[must_use]
pub fn saturating_duration_since(&self, earlier: Self) -> Duration {
self.checked_duration_since(earlier).unwrap_or_default()
}
}
impl Add<Duration> for Instant {
type Output = Self;
fn add(self, rhs: Duration) -> Self {
Self(self.0 + rhs)
}
}
impl AddAssign<Duration> for Instant {
fn add_assign(&mut self, rhs: Duration) {
self.0 += rhs;
}
}
impl Sub<Duration> for Instant {
type Output = Self;
fn sub(self, rhs: Duration) -> Self {
Self(self.0 - rhs)
}
}
impl Sub<Self> for Instant {
type Output = Duration;
fn sub(self, rhs: Self) -> Duration {
self.duration_since(rhs)
}
}
impl SubAssign<Duration> for Instant {
fn sub_assign(&mut self, rhs: Duration) {
self.0 -= rhs;
}
}
impl From<StdInstant> for Instant {
fn from(instant: StdInstant) -> Self {
Self(instant.duration_since(*START_INSTANT))
}
}
impl From<Instant> for StdInstant {
fn from(instant: Instant) -> Self {
*START_INSTANT + instant.0
}
}