]> git.proxmox.com Git - rustc.git/blame - src/libstd/sys/cloudabi/time.rs
New upstream version 1.37.0+dfsg1
[rustc.git] / src / libstd / sys / cloudabi / time.rs
CommitLineData
532ac7d7
XL
1use crate::mem;
2use crate::sys::cloudabi::abi;
3use crate::time::Duration;
2c00a5a8
XL
4
5const NSEC_PER_SEC: abi::timestamp = 1_000_000_000;
6
7#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
8pub struct Instant {
9 t: abi::timestamp,
10}
11
0731742a 12pub fn checked_dur2intervals(dur: &Duration) -> Option<abi::timestamp> {
2c00a5a8 13 dur.as_secs()
0731742a
XL
14 .checked_mul(NSEC_PER_SEC)?
15 .checked_add(dur.subsec_nanos() as abi::timestamp)
2c00a5a8
XL
16}
17
18impl Instant {
19 pub fn now() -> Instant {
20 unsafe {
21 let mut t = mem::uninitialized();
22 let ret = abi::clock_time_get(abi::clockid::MONOTONIC, 0, &mut t);
23 assert_eq!(ret, abi::errno::SUCCESS);
a1dfa0c6 24 Instant { t }
2c00a5a8
XL
25 }
26 }
27
0731742a
XL
28 pub fn actually_monotonic() -> bool {
29 true
30 }
31
32 pub const fn zero() -> Instant {
33 Instant { t: 0 }
34 }
35
532ac7d7
XL
36 pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> {
37 let diff = self.t.checked_sub(other.t)?;
38 Some(Duration::new(diff / NSEC_PER_SEC, (diff % NSEC_PER_SEC) as u32))
2c00a5a8
XL
39 }
40
0731742a
XL
41 pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
42 Some(Instant {
43 t: self.t.checked_add(checked_dur2intervals(other)?)?,
44 })
2c00a5a8
XL
45 }
46
0731742a
XL
47 pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
48 Some(Instant {
49 t: self.t.checked_sub(checked_dur2intervals(other)?)?,
50 })
2c00a5a8
XL
51 }
52}
53
54#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
55pub struct SystemTime {
56 t: abi::timestamp,
57}
58
59impl SystemTime {
60 pub fn now() -> SystemTime {
61 unsafe {
62 let mut t = mem::uninitialized();
63 let ret = abi::clock_time_get(abi::clockid::REALTIME, 0, &mut t);
64 assert_eq!(ret, abi::errno::SUCCESS);
a1dfa0c6 65 SystemTime { t }
2c00a5a8
XL
66 }
67 }
68
69 pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> {
70 if self.t >= other.t {
71 let diff = self.t - other.t;
72 Ok(Duration::new(
73 diff / NSEC_PER_SEC,
74 (diff % NSEC_PER_SEC) as u32,
75 ))
76 } else {
77 let diff = other.t - self.t;
78 Err(Duration::new(
79 diff / NSEC_PER_SEC,
80 (diff % NSEC_PER_SEC) as u32,
81 ))
82 }
83 }
84
a1dfa0c6 85 pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
0731742a
XL
86 Some(SystemTime {
87 t: self.t.checked_add(checked_dur2intervals(other)?)?,
88 })
2c00a5a8
XL
89 }
90
0731742a
XL
91 pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
92 Some(SystemTime {
93 t: self.t.checked_sub(checked_dur2intervals(other)?)?,
94 })
2c00a5a8
XL
95 }
96}
97
98pub const UNIX_EPOCH: SystemTime = SystemTime { t: 0 };