use std::ops::{Add, Sub};
use std::time::Duration;
unsafe extern "Rust" {
safe fn __bashkit_host_now_micros() -> u64;
}
fn now_duration() -> Duration {
Duration::from_micros(__bashkit_host_now_micros())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct SystemTime(Duration);
pub const UNIX_EPOCH: SystemTime = SystemTime(Duration::ZERO);
#[derive(Debug, Clone)]
pub struct SystemTimeError(Duration);
impl SystemTimeError {
pub fn duration(&self) -> Duration {
self.0
}
}
impl SystemTime {
pub fn now() -> Self {
Self(now_duration())
}
pub fn duration_since(&self, earlier: SystemTime) -> Result<Duration, SystemTimeError> {
self.0
.checked_sub(earlier.0)
.ok_or_else(|| SystemTimeError(earlier.0 - self.0))
}
}
impl Add<Duration> for SystemTime {
type Output = SystemTime;
fn add(self, rhs: Duration) -> SystemTime {
SystemTime(self.0 + rhs)
}
}
impl Sub<Duration> for SystemTime {
type Output = SystemTime;
fn sub(self, rhs: Duration) -> SystemTime {
SystemTime(self.0.saturating_sub(rhs))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Instant(Duration);
impl Instant {
pub fn now() -> Self {
Self(now_duration())
}
pub fn elapsed(&self) -> Duration {
now_duration().saturating_sub(self.0)
}
#[allow(dead_code)]
pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> {
self.0.checked_sub(earlier.0)
}
pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
self.0.checked_add(duration).map(Instant)
}
}
impl Add<Duration> for Instant {
type Output = Instant;
fn add(self, rhs: Duration) -> Instant {
Instant(self.0 + rhs)
}
}
impl Sub<Instant> for Instant {
type Output = Duration;
fn sub(self, rhs: Instant) -> Duration {
self.0.saturating_sub(rhs.0)
}
}