]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/wasi/time.rs
Auto merge of #2738 - RalfJung:rustup, r=RalfJung
[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: wasi::Clockid) -> 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 fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> {
29         self.0.checked_sub(other.0)
30     }
31
32     pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
33         Some(Instant(self.0.checked_add(*other)?))
34     }
35
36     pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
37         Some(Instant(self.0.checked_sub(*other)?))
38     }
39 }
40
41 impl SystemTime {
42     pub fn now() -> SystemTime {
43         SystemTime(current_time(wasi::CLOCKID_REALTIME))
44     }
45
46     pub fn from_wasi_timestamp(ts: wasi::Timestamp) -> SystemTime {
47         SystemTime(Duration::from_nanos(ts))
48     }
49
50     pub fn to_wasi_timestamp(&self) -> Option<wasi::Timestamp> {
51         self.0.as_nanos().try_into().ok()
52     }
53
54     pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> {
55         self.0.checked_sub(other.0).ok_or_else(|| other.0 - self.0)
56     }
57
58     pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
59         Some(SystemTime(self.0.checked_add(*other)?))
60     }
61
62     pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
63         Some(SystemTime(self.0.checked_sub(*other)?))
64     }
65 }