use core::ops::{Add, AddAssign, Sub, SubAssign};
use super::Duration;
#[repr(transparent)]
#[derive(Copy, Clone, Default, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Instant {
pub(crate) ns: u64,
}
impl Instant {
pub fn now() -> Self {
let mut ts = libc::timespec {
tv_sec: 0,
tv_nsec: 0,
};
unsafe {
libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts);
}
let now = (ts.tv_sec as u64)
.wrapping_mul(1_000_000_000)
.wrapping_add(ts.tv_nsec as u64);
Self { ns: now }
}
pub fn elapsed(&self) -> Duration {
Self::now() - *self
}
pub fn duration_since(&self, earlier: Self) -> Duration {
*self - earlier
}
pub fn checked_duration_since(&self, earlier: Self) -> Option<Duration> {
self.ns.checked_sub(earlier.ns).map(|ns| Duration { ns })
}
pub fn checked_sub(&self, duration: Duration) -> Option<Self> {
self.ns.checked_sub(duration.ns).map(|ns| Self { ns })
}
}
impl Add<Duration> for Instant {
type Output = Instant;
fn add(self, rhs: Duration) -> Self::Output {
Instant {
ns: self.ns + rhs.ns,
}
}
}
impl Add<core::time::Duration> for Instant {
type Output = Instant;
fn add(self, rhs: core::time::Duration) -> Self::Output {
Instant {
ns: self.ns + rhs.as_nanos() as u64,
}
}
}
impl Sub<Instant> for Instant {
type Output = Duration;
fn sub(self, rhs: Instant) -> Self::Output {
Duration {
ns: self.ns - rhs.ns,
}
}
}
impl AddAssign<Duration> for Instant {
fn add_assign(&mut self, rhs: Duration) {
self.ns += rhs.ns;
}
}
impl Sub<Duration> for Instant {
type Output = Instant;
fn sub(self, rhs: Duration) -> Self::Output {
Instant {
ns: self.ns - rhs.ns,
}
}
}
impl SubAssign<Duration> for Instant {
fn sub_assign(&mut self, rhs: Duration) {
self.ns -= rhs.ns;
}
}
impl AddAssign<core::time::Duration> for Instant {
fn add_assign(&mut self, rhs: core::time::Duration) {
self.ns += rhs.as_nanos() as u64;
}
}
impl Sub<core::time::Duration> for Instant {
type Output = Instant;
fn sub(self, rhs: core::time::Duration) -> Self::Output {
Instant {
ns: self.ns - rhs.as_nanos() as u64,
}
}
}
impl SubAssign<core::time::Duration> for Instant {
fn sub_assign(&mut self, rhs: core::time::Duration) {
self.ns -= rhs.as_nanos() as u64;
}
}
impl From<crate::coarse::Instant> for Instant {
fn from(other: crate::coarse::Instant) -> Self {
Self {
ns: other.secs as u64 * super::Duration::NANOSECOND.as_nanos(),
}
}
}