Skip to main content

ic_time/
lib.rs

1#![allow(dead_code, unused_imports)]
2
3use std::convert::TryInto;
4use std::ops::{Add, AddAssign, Sub, SubAssign};
5
6pub use std::time::*;
7
8#[cfg(not(target_arch = "wasm32"))]
9#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
10pub struct Instant(std::time::Instant);
11#[cfg(not(target_arch = "wasm32"))]
12impl Instant {
13    pub fn now() -> Self {
14        Self(std::time::Instant::now())
15    }
16    pub fn duration_since(&self, earlier: Instant) -> Duration {
17        self.0.duration_since(earlier.0)
18    }
19    pub fn elapsed(&self) -> Duration {
20        self.0.elapsed()
21    }
22    pub fn checked_add(&self, duration: Duration) -> Option<Self> {
23        self.0.checked_add(duration).map(|i| Self(i))
24    }
25    pub fn checked_sub(&self, duration: Duration) -> Option<Self> {
26        self.0.checked_sub(duration).map(|i| Self(i))
27    }
28}
29
30#[cfg(target_arch = "wasm32")]
31use ic_cdk::api::time as date_now;
32
33#[cfg(target_arch = "wasm32")]
34#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
35pub struct Instant(u64);
36#[cfg(target_arch = "wasm32")]
37impl Instant {
38    pub fn now() -> Self {
39        Self(date_now() as u64)
40    }
41    pub fn duration_since(&self, earlier: Instant) -> Duration {
42        Duration::from_millis(self.0 - earlier.0)
43    }
44    pub fn elapsed(&self) -> Duration {
45        Self::now().duration_since(*self)
46    }
47    pub fn checked_add(&self, duration: Duration) -> Option<Self> {
48        match duration.as_millis().try_into() {
49            Ok(duration) => self.0.checked_add(duration).map(|i| Self(i)),
50            Err(_) => None,
51        }
52    }
53    pub fn checked_sub(&self, duration: Duration) -> Option<Self> {
54        match duration.as_millis().try_into() {
55            Ok(duration) => self.0.checked_sub(duration).map(|i| Self(i)),
56            Err(_) => None,
57        }
58    }
59}
60
61impl Add<Duration> for Instant {
62    type Output = Instant;
63    fn add(self, other: Duration) -> Instant {
64        self.checked_add(other).unwrap()
65    }
66}
67impl Sub<Duration> for Instant {
68    type Output = Instant;
69    fn sub(self, other: Duration) -> Instant {
70        self.checked_sub(other).unwrap()
71    }
72}
73impl Sub<Instant> for Instant {
74    type Output = Duration;
75    fn sub(self, other: Instant) -> Duration {
76        self.duration_since(other)
77    }
78}
79impl AddAssign<Duration> for Instant {
80    fn add_assign(&mut self, other: Duration) {
81        *self = *self + other;
82    }
83}
84impl SubAssign<Duration> for Instant {
85    fn sub_assign(&mut self, other: Duration) {
86        *self = *self - other;
87    }
88}