use crate::time::{Duration, SystemTimeError};
use std::ops::{Add, AddAssign, Sub, SubAssign};
use std::{fmt, time};
#[derive(Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct SystemTime {
pub(crate) std: time::SystemTime,
}
impl SystemTime {
#[inline]
pub fn from_std(std: time::SystemTime) -> Self {
if cfg!(emulate_second_only_system) {
match std.duration_since(time::SystemTime::UNIX_EPOCH) {
Ok(duration) => {
let secs = time::Duration::from_secs(duration.as_secs());
Self {
std: time::SystemTime::UNIX_EPOCH.checked_add(secs).unwrap(),
}
}
Err(_) => {
let duration = time::SystemTime::UNIX_EPOCH.duration_since(std).unwrap();
let secs = time::Duration::from_secs(duration.as_secs());
Self {
std: time::SystemTime::UNIX_EPOCH.checked_sub(secs).unwrap(),
}
}
}
} else {
Self { std }
}
}
#[inline]
pub const fn into_std(self) -> time::SystemTime {
self.std
}
#[inline]
pub fn duration_since(&self, earlier: Self) -> Result<Duration, SystemTimeError> {
self.std.duration_since(earlier.std)
}
#[inline]
pub fn checked_add(&self, duration: Duration) -> Option<Self> {
self.std.checked_add(duration).map(Self::from_std)
}
#[inline]
pub fn checked_sub(&self, duration: Duration) -> Option<Self> {
self.std.checked_sub(duration).map(Self::from_std)
}
}
impl Add<Duration> for SystemTime {
type Output = Self;
#[inline]
fn add(self, dur: Duration) -> Self {
self.checked_add(dur)
.expect("overflow when adding duration to instant")
}
}
impl AddAssign<Duration> for SystemTime {
#[inline]
fn add_assign(&mut self, other: Duration) {
*self = *self + other;
}
}
impl Sub<Duration> for SystemTime {
type Output = Self;
#[inline]
fn sub(self, dur: Duration) -> Self {
self.checked_sub(dur)
.expect("overflow when subtracting duration from instant")
}
}
impl SubAssign<Duration> for SystemTime {
#[inline]
fn sub_assign(&mut self, other: Duration) {
*self = *self - other;
}
}
impl fmt::Debug for SystemTime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.std.fmt(f)
}
}