]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/time.rs
Auto merge of #64546 - weiznich:bugfix/rfc-2451-rerebalance-tests, r=nikomatsakis
[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::mem;
118     use crate::sync::atomic::{AtomicUsize, Ordering::SeqCst};
119     use crate::sys::cvt;
120     use crate::sys_common::mul_div_u64;
121     use crate::time::Duration;
122
123     use super::NSEC_PER_SEC;
124     use super::Timespec;
125
126     #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
127     pub struct Instant {
128         t: u64
129     }
130
131     #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
132     pub struct SystemTime {
133         t: Timespec,
134     }
135
136     pub const UNIX_EPOCH: SystemTime = SystemTime {
137         t: Timespec::zero(),
138     };
139
140     #[repr(C)]
141     #[derive(Copy, Clone)]
142     struct mach_timebase_info {
143         numer: u32,
144         denom: u32,
145     }
146     type mach_timebase_info_t = *mut mach_timebase_info;
147     type kern_return_t = libc::c_int;
148
149     impl Instant {
150         pub fn now() -> Instant {
151             extern "C" {
152                 fn mach_absolute_time() -> u64;
153             }
154             Instant { t: unsafe { mach_absolute_time() } }
155         }
156
157         pub const fn zero() -> Instant {
158             Instant { t: 0 }
159         }
160
161         pub fn actually_monotonic() -> bool {
162             true
163         }
164
165         pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> {
166             let diff = self.t.checked_sub(other.t)?;
167             let info = info();
168             let nanos = mul_div_u64(diff, info.numer as u64, info.denom as u64);
169             Some(Duration::new(nanos / NSEC_PER_SEC, (nanos % NSEC_PER_SEC) as u32))
170         }
171
172         pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
173             Some(Instant {
174                 t: self.t.checked_add(checked_dur2intervals(other)?)?,
175             })
176         }
177
178         pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
179             Some(Instant {
180                 t: self.t.checked_sub(checked_dur2intervals(other)?)?,
181             })
182         }
183     }
184
185     impl SystemTime {
186         pub fn now() -> SystemTime {
187             use crate::ptr;
188
189             let mut s = libc::timeval {
190                 tv_sec: 0,
191                 tv_usec: 0,
192             };
193             cvt(unsafe {
194                 libc::gettimeofday(&mut s, ptr::null_mut())
195             }).unwrap();
196             return SystemTime::from(s)
197         }
198
199         pub fn sub_time(&self, other: &SystemTime)
200                         -> Result<Duration, Duration> {
201             self.t.sub_timespec(&other.t)
202         }
203
204         pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
205             Some(SystemTime { t: self.t.checked_add_duration(other)? })
206         }
207
208         pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
209             Some(SystemTime { t: self.t.checked_sub_duration(other)? })
210         }
211     }
212
213     impl From<libc::timeval> for SystemTime {
214         fn from(t: libc::timeval) -> SystemTime {
215             SystemTime::from(libc::timespec {
216                 tv_sec: t.tv_sec,
217                 tv_nsec: (t.tv_usec * 1000) as libc::c_long,
218             })
219         }
220     }
221
222     impl From<libc::timespec> for SystemTime {
223         fn from(t: libc::timespec) -> SystemTime {
224             SystemTime { t: Timespec { t } }
225         }
226     }
227
228     impl fmt::Debug for SystemTime {
229         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
230             f.debug_struct("SystemTime")
231              .field("tv_sec", &self.t.t.tv_sec)
232              .field("tv_nsec", &self.t.t.tv_nsec)
233              .finish()
234         }
235     }
236
237     fn checked_dur2intervals(dur: &Duration) -> Option<u64> {
238         let nanos = dur.as_secs()
239             .checked_mul(NSEC_PER_SEC)?
240             .checked_add(dur.subsec_nanos() as u64)?;
241         let info = info();
242         Some(mul_div_u64(nanos, info.denom as u64, info.numer as u64))
243     }
244
245     fn info() -> mach_timebase_info {
246         static mut INFO: mach_timebase_info = mach_timebase_info {
247             numer: 0,
248             denom: 0,
249         };
250         static STATE: AtomicUsize = AtomicUsize::new(0);
251
252         unsafe {
253             // If a previous thread has filled in this global state, use that.
254             if STATE.load(SeqCst) == 2 {
255                 return INFO;
256             }
257
258             // ... otherwise learn for ourselves ...
259             let mut info = mem::zeroed();
260             extern "C" {
261                 fn mach_timebase_info(info: mach_timebase_info_t)
262                                       -> kern_return_t;
263             }
264
265             mach_timebase_info(&mut info);
266
267             // ... and attempt to be the one thread that stores it globally for
268             // all other threads
269             if STATE.compare_exchange(0, 1, SeqCst, SeqCst).is_ok() {
270                 INFO = info;
271                 STATE.store(2, SeqCst);
272             }
273             return info;
274         }
275     }
276 }
277
278 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
279 mod inner {
280     use crate::fmt;
281     use crate::sys::cvt;
282     use crate::time::Duration;
283
284     use super::Timespec;
285
286     #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
287     pub struct Instant {
288         t: Timespec,
289     }
290
291     #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
292     pub struct SystemTime {
293         t: Timespec,
294     }
295
296     pub const UNIX_EPOCH: SystemTime = SystemTime {
297         t: Timespec::zero(),
298     };
299
300     impl Instant {
301         pub fn now() -> Instant {
302             Instant { t: now(libc::CLOCK_MONOTONIC) }
303         }
304
305         pub const fn zero() -> Instant {
306             Instant {
307                 t: Timespec::zero(),
308             }
309         }
310
311         pub fn actually_monotonic() -> bool {
312             (cfg!(target_os = "linux") && cfg!(target_arch = "x86_64")) ||
313             (cfg!(target_os = "linux") && cfg!(target_arch = "x86")) ||
314             cfg!(target_os = "fuchsia") ||
315             false // last clause, used so `||` is always trailing above
316         }
317
318         pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> {
319             self.t.sub_timespec(&other.t).ok()
320         }
321
322         pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
323             Some(Instant { t: self.t.checked_add_duration(other)? })
324         }
325
326         pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
327             Some(Instant { t: self.t.checked_sub_duration(other)? })
328         }
329     }
330
331     impl fmt::Debug for Instant {
332         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
333             f.debug_struct("Instant")
334              .field("tv_sec", &self.t.t.tv_sec)
335              .field("tv_nsec", &self.t.t.tv_nsec)
336              .finish()
337         }
338     }
339
340     impl SystemTime {
341         pub fn now() -> SystemTime {
342             SystemTime { t: now(libc::CLOCK_REALTIME) }
343         }
344
345         pub fn sub_time(&self, other: &SystemTime)
346                         -> Result<Duration, Duration> {
347             self.t.sub_timespec(&other.t)
348         }
349
350         pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
351             Some(SystemTime { t: self.t.checked_add_duration(other)? })
352         }
353
354         pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
355             Some(SystemTime { t: self.t.checked_sub_duration(other)? })
356         }
357     }
358
359     impl From<libc::timespec> for SystemTime {
360         fn from(t: libc::timespec) -> SystemTime {
361             SystemTime { t: Timespec { t } }
362         }
363     }
364
365     impl fmt::Debug for SystemTime {
366         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
367             f.debug_struct("SystemTime")
368              .field("tv_sec", &self.t.t.tv_sec)
369              .field("tv_nsec", &self.t.t.tv_nsec)
370              .finish()
371         }
372     }
373
374     #[cfg(not(any(target_os = "dragonfly", target_os = "hermit")))]
375     pub type clock_t = libc::c_int;
376     #[cfg(any(target_os = "dragonfly", target_os = "hermit"))]
377     pub type clock_t = libc::c_ulong;
378
379     fn now(clock: clock_t) -> Timespec {
380         let mut t = Timespec {
381             t: libc::timespec {
382                 tv_sec: 0,
383                 tv_nsec: 0,
384             }
385         };
386         cvt(unsafe {
387             libc::clock_gettime(clock, &mut t.t)
388         }).unwrap();
389         t
390     }
391 }