]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/wasi/time.rs
Merge commit '3d0b0e66afdfaa519d8855b338b35b4605775945' into clippyup
[rust.git] / library / std / src / sys / wasi / time.rs
1 use crate::time::Duration;
2
3 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
4 pub struct Instant(Duration);
5
6 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
7 pub struct SystemTime(Duration);
8
9 pub const UNIX_EPOCH: SystemTime = SystemTime(Duration::from_secs(0));
10
11 fn current_time(clock: u32) -> Duration {
12     let ts = unsafe {
13         wasi::clock_time_get(
14             clock, 1, // precision... seems ignored though?
15         )
16         .unwrap()
17     };
18     Duration::new((ts / 1_000_000_000) as u64, (ts % 1_000_000_000) as u32)
19 }
20
21 impl Instant {
22     pub fn now() -> Instant {
23         Instant(current_time(wasi::CLOCKID_MONOTONIC))
24     }
25
26     pub const fn zero() -> Instant {
27         Instant(Duration::from_secs(0))
28     }
29
30     pub fn actually_monotonic() -> bool {
31         true
32     }
33
34     pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> {
35         self.0.checked_sub(other.0)
36     }
37
38     pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
39         Some(Instant(self.0.checked_add(*other)?))
40     }
41
42     pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
43         Some(Instant(self.0.checked_sub(*other)?))
44     }
45 }
46
47 impl SystemTime {
48     pub fn now() -> SystemTime {
49         SystemTime(current_time(wasi::CLOCKID_REALTIME))
50     }
51
52     pub fn from_wasi_timestamp(ts: wasi::Timestamp) -> SystemTime {
53         SystemTime(Duration::from_nanos(ts))
54     }
55
56     pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> {
57         self.0.checked_sub(other.0).ok_or_else(|| other.0 - self.0)
58     }
59
60     pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
61         Some(SystemTime(self.0.checked_add(*other)?))
62     }
63
64     pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
65         Some(SystemTime(self.0.checked_sub(*other)?))
66     }
67 }