2 use crate::sys::cloudabi::abi;
3 use crate::time::Duration;
5 const NSEC_PER_SEC: abi::timestamp = 1_000_000_000;
7 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
12 pub fn checked_dur2intervals(dur: &Duration) -> Option<abi::timestamp> {
13 dur.as_secs().checked_mul(NSEC_PER_SEC)?.checked_add(dur.subsec_nanos() as abi::timestamp)
17 pub fn now() -> Instant {
19 let mut t: mem::MaybeUninit<abi::timestamp> = mem::MaybeUninit::uninit();
20 let ret = abi::clock_time_get(abi::clockid::MONOTONIC, 0, t.as_mut_ptr());
21 assert_eq!(ret, abi::errno::SUCCESS);
22 Instant { t: t.assume_init() }
26 pub fn actually_monotonic() -> bool {
30 pub const fn zero() -> Instant {
34 pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> {
35 let diff = self.t.checked_sub(other.t)?;
36 Some(Duration::new(diff / NSEC_PER_SEC, (diff % NSEC_PER_SEC) as u32))
39 pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
40 Some(Instant { t: self.t.checked_add(checked_dur2intervals(other)?)? })
43 pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
44 Some(Instant { t: self.t.checked_sub(checked_dur2intervals(other)?)? })
48 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
49 pub struct SystemTime {
54 pub fn now() -> SystemTime {
56 let mut t: mem::MaybeUninit<abi::timestamp> = mem::MaybeUninit::uninit();
57 let ret = abi::clock_time_get(abi::clockid::REALTIME, 0, t.as_mut_ptr());
58 assert_eq!(ret, abi::errno::SUCCESS);
59 SystemTime { t: t.assume_init() }
63 pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> {
64 if self.t >= other.t {
65 let diff = self.t - other.t;
66 Ok(Duration::new(diff / NSEC_PER_SEC, (diff % NSEC_PER_SEC) as u32))
68 let diff = other.t - self.t;
69 Err(Duration::new(diff / NSEC_PER_SEC, (diff % NSEC_PER_SEC) as u32))
73 pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
74 Some(SystemTime { t: self.t.checked_add(checked_dur2intervals(other)?)? })
77 pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
78 Some(SystemTime { t: self.t.checked_sub(checked_dur2intervals(other)?)? })
82 pub const UNIX_EPOCH: SystemTime = SystemTime { t: 0 };