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