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