use std::fmt::{Debug, Formatter};
use std::ops::{Add, AddAssign, Sub};
use std::time::Duration;
#[cfg(feature = "tokio")]
type Inner = tokio::time::Instant;
#[cfg(all(not(feature = "tokio"), not(target_arch = "wasm32")))]
type Inner = std::time::Instant;
#[cfg(all(not(feature = "tokio"), target_arch = "wasm32"))]
type Inner = web_time::Instant;
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Instant(Inner);
impl Debug for Instant {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
#[cfg(not(target_arch = "wasm32"))]
impl From<std::time::Instant> for Instant {
fn from(value: std::time::Instant) -> Self {
#[cfg(feature = "tokio")]
{
Instant(value.into())
}
#[cfg(not(feature = "tokio"))]
{
Instant(value)
}
}
}
impl Instant {
pub fn now() -> Self {
Self(Inner::now())
}
pub fn saturating_duration_since(&self, other: Instant) -> Duration {
self.0.saturating_duration_since(other.0)
}
pub fn elapsed(&self) -> Duration {
self.0.elapsed()
}
#[cfg(feature = "tokio")]
pub fn tokio_instant(&self) -> Inner {
self.0
}
}
impl AddAssign<Duration> for Instant {
fn add_assign(&mut self, rhs: Duration) {
self.0 += rhs;
}
}
impl Add<Duration> for Instant {
type Output = Instant;
fn add(self, rhs: Duration) -> Self::Output {
Self(self.0 + rhs)
}
}
impl Sub<Instant> for Instant {
type Output = Duration;
fn sub(self, rhs: Instant) -> Self::Output {
self.0 - rhs.0
}
}