]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/time.rs
Rollup merge of #59432 - phansch:compiletest_docs, r=alexcrichton
[rust.git] / src / libstd / sys / unix / time.rs
1 use crate::cmp::Ordering;
2 use crate::time::Duration;
3
4 use core::hash::{Hash, Hasher};
5
6 pub use self::inner::{Instant, SystemTime, UNIX_EPOCH};
7 use crate::convert::TryInto;
8
9 const NSEC_PER_SEC: u64 = 1_000_000_000;
10
11 #[derive(Copy, Clone)]
12 struct Timespec {
13     t: libc::timespec,
14 }
15
16 impl Timespec {
17     const fn zero() -> Timespec {
18         Timespec {
19             t: libc::timespec { tv_sec: 0, tv_nsec: 0 },
20         }
21     }
22
23     fn sub_timespec(&self, other: &Timespec) -> Result<Duration, Duration> {
24         if self >= other {
25             Ok(if self.t.tv_nsec >= other.t.tv_nsec {
26                 Duration::new((self.t.tv_sec - other.t.tv_sec) as u64,
27                               (self.t.tv_nsec - other.t.tv_nsec) as u32)
28             } else {
29                 Duration::new((self.t.tv_sec - 1 - other.t.tv_sec) as u64,
30                               self.t.tv_nsec as u32 + (NSEC_PER_SEC as u32) -
31                               other.t.tv_nsec as u32)
32             })
33         } else {
34             match other.sub_timespec(self) {
35                 Ok(d) => Err(d),
36                 Err(d) => Ok(d),
37             }
38         }
39     }
40
41     fn checked_add_duration(&self, other: &Duration) -> Option<Timespec> {
42         let mut secs = other
43             .as_secs()
44             .try_into() // <- target type would be `libc::time_t`
45             .ok()
46             .and_then(|secs| self.t.tv_sec.checked_add(secs))?;
47
48         // Nano calculations can't overflow because nanos are <1B which fit
49         // in a u32.
50         let mut nsec = other.subsec_nanos() + self.t.tv_nsec as u32;
51         if nsec >= NSEC_PER_SEC as u32 {
52             nsec -= NSEC_PER_SEC as u32;
53             secs = secs.checked_add(1)?;
54         }
55         Some(Timespec {
56             t: libc::timespec {
57                 tv_sec: secs,
58                 tv_nsec: nsec as _,
59             },
60         })
61     }
62
63     fn checked_sub_duration(&self, other: &Duration) -> Option<Timespec> {
64         let mut secs = other
65             .as_secs()
66             .try_into() // <- target type would be `libc::time_t`
67             .ok()
68             .and_then(|secs| self.t.tv_sec.checked_sub(secs))?;
69
70         // Similar to above, nanos can't overflow.
71         let mut nsec = self.t.tv_nsec as i32 - other.subsec_nanos() as i32;
72         if nsec < 0 {
73             nsec += NSEC_PER_SEC as i32;
74             secs = secs.checked_sub(1)?;
75         }
76         Some(Timespec {
77             t: libc::timespec {
78                 tv_sec: secs,
79                 tv_nsec: nsec as _,
80             },
81         })
82     }
83 }
84
85 impl PartialEq for Timespec {
86     fn eq(&self, other: &Timespec) -> bool {
87         self.t.tv_sec == other.t.tv_sec && self.t.tv_nsec == other.t.tv_nsec
88     }
89 }
90
91 impl Eq for Timespec {}
92
93 impl PartialOrd for Timespec {
94     fn partial_cmp(&self, other: &Timespec) -> Option<Ordering> {
95         Some(self.cmp(other))
96     }
97 }
98
99 impl Ord for Timespec {
100     fn cmp(&self, other: &Timespec) -> Ordering {
101         let me = (self.t.tv_sec, self.t.tv_nsec);
102         let other = (other.t.tv_sec, other.t.tv_nsec);
103         me.cmp(&other)
104     }
105 }
106
107 impl Hash for Timespec {
108     fn hash<H : Hasher>(&self, state: &mut H) {
109         self.t.tv_sec.hash(state);
110         self.t.tv_nsec.hash(state);
111     }
112 }
113
114 #[cfg(any(target_os = "macos", target_os = "ios"))]
115 mod inner {
116     use crate::fmt;
117     use crate::sync::Once;
118     use crate::sys::cvt;
119     use crate::sys_common::mul_div_u64;
120     use crate::time::Duration;
121
122     use super::NSEC_PER_SEC;
123     use super::Timespec;
124
125     #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
126     pub struct Instant {
127         t: u64
128     }
129
130     #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
131     pub struct SystemTime {
132         t: Timespec,
133     }
134
135     pub const UNIX_EPOCH: SystemTime = SystemTime {
136         t: Timespec::zero(),
137     };
138
139     impl Instant {
140         pub fn now() -> Instant {
141             Instant { t: unsafe { libc::mach_absolute_time() } }
142         }
143
144         pub const fn zero() -> Instant {
145             Instant { t: 0 }
146         }
147
148         pub fn actually_monotonic() -> bool {
149             true
150         }
151
152         pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> {
153             let diff = self.t.checked_sub(other.t)?;
154             let info = info();
155             let nanos = mul_div_u64(diff, info.numer as u64, info.denom as u64);
156             Some(Duration::new(nanos / NSEC_PER_SEC, (nanos % NSEC_PER_SEC) as u32))
157         }
158
159         pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
160             Some(Instant {
161                 t: self.t.checked_add(checked_dur2intervals(other)?)?,
162             })
163         }
164
165         pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
166             Some(Instant {
167                 t: self.t.checked_sub(checked_dur2intervals(other)?)?,
168             })
169         }
170     }
171
172     impl SystemTime {
173         pub fn now() -> SystemTime {
174             use crate::ptr;
175
176             let mut s = libc::timeval {
177                 tv_sec: 0,
178                 tv_usec: 0,
179             };
180             cvt(unsafe {
181                 libc::gettimeofday(&mut s, ptr::null_mut())
182             }).unwrap();
183             return SystemTime::from(s)
184         }
185
186         pub fn sub_time(&self, other: &SystemTime)
187                         -> Result<Duration, Duration> {
188             self.t.sub_timespec(&other.t)
189         }
190
191         pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
192             Some(SystemTime { t: self.t.checked_add_duration(other)? })
193         }
194
195         pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
196             Some(SystemTime { t: self.t.checked_sub_duration(other)? })
197         }
198     }
199
200     impl From<libc::timeval> for SystemTime {
201         fn from(t: libc::timeval) -> SystemTime {
202             SystemTime::from(libc::timespec {
203                 tv_sec: t.tv_sec,
204                 tv_nsec: (t.tv_usec * 1000) as libc::c_long,
205             })
206         }
207     }
208
209     impl From<libc::timespec> for SystemTime {
210         fn from(t: libc::timespec) -> SystemTime {
211             SystemTime { t: Timespec { t } }
212         }
213     }
214
215     impl fmt::Debug for SystemTime {
216         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
217             f.debug_struct("SystemTime")
218              .field("tv_sec", &self.t.t.tv_sec)
219              .field("tv_nsec", &self.t.t.tv_nsec)
220              .finish()
221         }
222     }
223
224     fn checked_dur2intervals(dur: &Duration) -> Option<u64> {
225         let nanos = dur.as_secs()
226             .checked_mul(NSEC_PER_SEC)?
227             .checked_add(dur.subsec_nanos() as u64)?;
228         let info = info();
229         Some(mul_div_u64(nanos, info.denom as u64, info.numer as u64))
230     }
231
232     fn info() -> &'static libc::mach_timebase_info {
233         static mut INFO: libc::mach_timebase_info = libc::mach_timebase_info {
234             numer: 0,
235             denom: 0,
236         };
237         static ONCE: Once = Once::new();
238
239         unsafe {
240             ONCE.call_once(|| {
241                 libc::mach_timebase_info(&mut INFO);
242             });
243             &INFO
244         }
245     }
246 }
247
248 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
249 mod inner {
250     use crate::fmt;
251     use crate::sys::cvt;
252     use crate::time::Duration;
253
254     use super::Timespec;
255
256     #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
257     pub struct Instant {
258         t: Timespec,
259     }
260
261     #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
262     pub struct SystemTime {
263         t: Timespec,
264     }
265
266     pub const UNIX_EPOCH: SystemTime = SystemTime {
267         t: Timespec::zero(),
268     };
269
270     impl Instant {
271         pub fn now() -> Instant {
272             Instant { t: now(libc::CLOCK_MONOTONIC) }
273         }
274
275         pub const fn zero() -> Instant {
276             Instant {
277                 t: Timespec::zero(),
278             }
279         }
280
281         pub fn actually_monotonic() -> bool {
282             (cfg!(target_os = "linux") && cfg!(target_arch = "x86_64")) ||
283             (cfg!(target_os = "linux") && cfg!(target_arch = "x86")) ||
284             false // last clause, used so `||` is always trailing above
285         }
286
287         pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> {
288             self.t.sub_timespec(&other.t).ok()
289         }
290
291         pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
292             Some(Instant { t: self.t.checked_add_duration(other)? })
293         }
294
295         pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
296             Some(Instant { t: self.t.checked_sub_duration(other)? })
297         }
298     }
299
300     impl fmt::Debug for Instant {
301         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
302             f.debug_struct("Instant")
303              .field("tv_sec", &self.t.t.tv_sec)
304              .field("tv_nsec", &self.t.t.tv_nsec)
305              .finish()
306         }
307     }
308
309     impl SystemTime {
310         pub fn now() -> SystemTime {
311             SystemTime { t: now(libc::CLOCK_REALTIME) }
312         }
313
314         pub fn sub_time(&self, other: &SystemTime)
315                         -> Result<Duration, Duration> {
316             self.t.sub_timespec(&other.t)
317         }
318
319         pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
320             Some(SystemTime { t: self.t.checked_add_duration(other)? })
321         }
322
323         pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
324             Some(SystemTime { t: self.t.checked_sub_duration(other)? })
325         }
326     }
327
328     impl From<libc::timespec> for SystemTime {
329         fn from(t: libc::timespec) -> SystemTime {
330             SystemTime { t: Timespec { t } }
331         }
332     }
333
334     impl fmt::Debug for SystemTime {
335         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
336             f.debug_struct("SystemTime")
337              .field("tv_sec", &self.t.t.tv_sec)
338              .field("tv_nsec", &self.t.t.tv_nsec)
339              .finish()
340         }
341     }
342
343     #[cfg(not(any(target_os = "dragonfly", target_os = "hermit")))]
344     pub type clock_t = libc::c_int;
345     #[cfg(any(target_os = "dragonfly", target_os = "hermit"))]
346     pub type clock_t = libc::c_ulong;
347
348     fn now(clock: clock_t) -> Timespec {
349         let mut t = Timespec {
350             t: libc::timespec {
351                 tv_sec: 0,
352                 tv_nsec: 0,
353             }
354         };
355         cvt(unsafe {
356             libc::clock_gettime(clock, &mut t.t)
357         }).unwrap();
358         t
359     }
360 }