]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/time.rs
Auto merge of #79253 - rcvalle:fix-rustc-sysroot-cas, r=nagisa
[rust.git] / library / std / src / 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 { t: libc::timespec { tv_sec: 0, tv_nsec: 0 } }
19     }
20
21     fn sub_timespec(&self, other: &Timespec) -> Result<Duration, Duration> {
22         if self >= other {
23             // NOTE(eddyb) two aspects of this `if`-`else` are required for LLVM
24             // to optimize it into a branchless form (see also #75545):
25             //
26             // 1. `self.t.tv_sec - other.t.tv_sec` shows up as a common expression
27             //    in both branches, i.e. the `else` must have its `- 1`
28             //    subtraction after the common one, not interleaved with it
29             //    (it used to be `self.t.tv_sec - 1 - other.t.tv_sec`)
30             //
31             // 2. the `Duration::new` call (or any other additional complexity)
32             //    is outside of the `if`-`else`, not duplicated in both branches
33             //
34             // Ideally this code could be rearranged such that it more
35             // directly expresses the lower-cost behavior we want from it.
36             let (secs, nsec) = if self.t.tv_nsec >= other.t.tv_nsec {
37                 ((self.t.tv_sec - other.t.tv_sec) as u64, (self.t.tv_nsec - other.t.tv_nsec) as u32)
38             } else {
39                 (
40                     (self.t.tv_sec - other.t.tv_sec - 1) as u64,
41                     self.t.tv_nsec as u32 + (NSEC_PER_SEC as u32) - other.t.tv_nsec as u32,
42                 )
43             };
44
45             Ok(Duration::new(secs, nsec))
46         } else {
47             match other.sub_timespec(self) {
48                 Ok(d) => Err(d),
49                 Err(d) => Ok(d),
50             }
51         }
52     }
53
54     fn checked_add_duration(&self, other: &Duration) -> Option<Timespec> {
55         let mut secs = other
56             .as_secs()
57             .try_into() // <- target type would be `libc::time_t`
58             .ok()
59             .and_then(|secs| self.t.tv_sec.checked_add(secs))?;
60
61         // Nano calculations can't overflow because nanos are <1B which fit
62         // in a u32.
63         let mut nsec = other.subsec_nanos() + self.t.tv_nsec as u32;
64         if nsec >= NSEC_PER_SEC as u32 {
65             nsec -= NSEC_PER_SEC as u32;
66             secs = secs.checked_add(1)?;
67         }
68         Some(Timespec { t: libc::timespec { tv_sec: secs, tv_nsec: nsec as _ } })
69     }
70
71     fn checked_sub_duration(&self, other: &Duration) -> Option<Timespec> {
72         let mut secs = other
73             .as_secs()
74             .try_into() // <- target type would be `libc::time_t`
75             .ok()
76             .and_then(|secs| self.t.tv_sec.checked_sub(secs))?;
77
78         // Similar to above, nanos can't overflow.
79         let mut nsec = self.t.tv_nsec as i32 - other.subsec_nanos() as i32;
80         if nsec < 0 {
81             nsec += NSEC_PER_SEC as i32;
82             secs = secs.checked_sub(1)?;
83         }
84         Some(Timespec { t: libc::timespec { tv_sec: secs, tv_nsec: nsec as _ } })
85     }
86 }
87
88 impl PartialEq for Timespec {
89     fn eq(&self, other: &Timespec) -> bool {
90         self.t.tv_sec == other.t.tv_sec && self.t.tv_nsec == other.t.tv_nsec
91     }
92 }
93
94 impl Eq for Timespec {}
95
96 impl PartialOrd for Timespec {
97     fn partial_cmp(&self, other: &Timespec) -> Option<Ordering> {
98         Some(self.cmp(other))
99     }
100 }
101
102 impl Ord for Timespec {
103     fn cmp(&self, other: &Timespec) -> Ordering {
104         let me = (self.t.tv_sec, self.t.tv_nsec);
105         let other = (other.t.tv_sec, other.t.tv_nsec);
106         me.cmp(&other)
107     }
108 }
109
110 impl Hash for Timespec {
111     fn hash<H: Hasher>(&self, state: &mut H) {
112         self.t.tv_sec.hash(state);
113         self.t.tv_nsec.hash(state);
114     }
115 }
116
117 #[cfg(any(target_os = "macos", target_os = "ios"))]
118 mod inner {
119     use crate::fmt;
120     use crate::sync::atomic::{AtomicU64, Ordering};
121     use crate::sys::cvt;
122     use crate::sys_common::mul_div_u64;
123     use crate::time::Duration;
124
125     use super::Timespec;
126     use super::NSEC_PER_SEC;
127
128     #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
129     pub struct Instant {
130         t: u64,
131     }
132
133     #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
134     pub struct SystemTime {
135         t: Timespec,
136     }
137
138     pub const UNIX_EPOCH: SystemTime = SystemTime { t: Timespec::zero() };
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 { t: self.t.checked_add(checked_dur2intervals(other)?)? })
174         }
175
176         pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
177             Some(Instant { t: self.t.checked_sub(checked_dur2intervals(other)?)? })
178         }
179     }
180
181     impl SystemTime {
182         pub fn now() -> SystemTime {
183             use crate::ptr;
184
185             let mut s = libc::timeval { tv_sec: 0, tv_usec: 0 };
186             cvt(unsafe { libc::gettimeofday(&mut s, ptr::null_mut()) }).unwrap();
187             return SystemTime::from(s);
188         }
189
190         pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> {
191             self.t.sub_timespec(&other.t)
192         }
193
194         pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
195             Some(SystemTime { t: self.t.checked_add_duration(other)? })
196         }
197
198         pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
199             Some(SystemTime { t: self.t.checked_sub_duration(other)? })
200         }
201     }
202
203     impl From<libc::timeval> for SystemTime {
204         fn from(t: libc::timeval) -> SystemTime {
205             SystemTime::from(libc::timespec {
206                 tv_sec: t.tv_sec,
207                 tv_nsec: (t.tv_usec * 1000) as libc::c_long,
208             })
209         }
210     }
211
212     impl From<libc::timespec> for SystemTime {
213         fn from(t: libc::timespec) -> SystemTime {
214             SystemTime { t: Timespec { t } }
215         }
216     }
217
218     impl fmt::Debug for SystemTime {
219         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220             f.debug_struct("SystemTime")
221                 .field("tv_sec", &self.t.t.tv_sec)
222                 .field("tv_nsec", &self.t.t.tv_nsec)
223                 .finish()
224         }
225     }
226
227     fn checked_dur2intervals(dur: &Duration) -> Option<u64> {
228         let nanos =
229             dur.as_secs().checked_mul(NSEC_PER_SEC)?.checked_add(dur.subsec_nanos() as u64)?;
230         let info = info();
231         Some(mul_div_u64(nanos, info.denom as u64, info.numer as u64))
232     }
233
234     fn info() -> mach_timebase_info {
235         // INFO_BITS conceptually is an `Option<mach_timebase_info>`. We can do
236         // this in 64 bits because we know 0 is never a valid value for the
237         // `denom` field.
238         //
239         // Encoding this as a single `AtomicU64` allows us to use `Relaxed`
240         // operations, as we are only interested in the effects on a single
241         // memory location.
242         static INFO_BITS: AtomicU64 = AtomicU64::new(0);
243
244         // If a previous thread has initialized `INFO_BITS`, use it.
245         let info_bits = INFO_BITS.load(Ordering::Relaxed);
246         if info_bits != 0 {
247             return info_from_bits(info_bits);
248         }
249
250         // ... otherwise learn for ourselves ...
251         extern "C" {
252             fn mach_timebase_info(info: mach_timebase_info_t) -> kern_return_t;
253         }
254
255         let mut info = info_from_bits(0);
256         unsafe {
257             mach_timebase_info(&mut info);
258         }
259         INFO_BITS.store(info_to_bits(info), Ordering::Relaxed);
260         info
261     }
262
263     #[inline]
264     fn info_to_bits(info: mach_timebase_info) -> u64 {
265         ((info.denom as u64) << 32) | (info.numer as u64)
266     }
267
268     #[inline]
269     fn info_from_bits(bits: u64) -> mach_timebase_info {
270         mach_timebase_info { numer: bits as u32, denom: (bits >> 32) as u32 }
271     }
272 }
273
274 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
275 mod inner {
276     use crate::fmt;
277     use crate::sys::cvt;
278     use crate::time::Duration;
279
280     use super::Timespec;
281
282     #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
283     pub struct Instant {
284         t: Timespec,
285     }
286
287     #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
288     pub struct SystemTime {
289         t: Timespec,
290     }
291
292     pub const UNIX_EPOCH: SystemTime = SystemTime { t: Timespec::zero() };
293
294     impl Instant {
295         pub fn now() -> Instant {
296             Instant { t: now(libc::CLOCK_MONOTONIC) }
297         }
298
299         pub const fn zero() -> Instant {
300             Instant { t: Timespec::zero() }
301         }
302
303         pub fn actually_monotonic() -> bool {
304             (cfg!(target_os = "linux") && cfg!(target_arch = "x86_64"))
305                 || (cfg!(target_os = "linux") && cfg!(target_arch = "x86"))
306                 || cfg!(target_os = "fuchsia")
307         }
308
309         pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> {
310             self.t.sub_timespec(&other.t).ok()
311         }
312
313         pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
314             Some(Instant { t: self.t.checked_add_duration(other)? })
315         }
316
317         pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
318             Some(Instant { t: self.t.checked_sub_duration(other)? })
319         }
320     }
321
322     impl fmt::Debug for Instant {
323         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
324             f.debug_struct("Instant")
325                 .field("tv_sec", &self.t.t.tv_sec)
326                 .field("tv_nsec", &self.t.t.tv_nsec)
327                 .finish()
328         }
329     }
330
331     impl SystemTime {
332         pub fn now() -> SystemTime {
333             SystemTime { t: now(libc::CLOCK_REALTIME) }
334         }
335
336         pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> {
337             self.t.sub_timespec(&other.t)
338         }
339
340         pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
341             Some(SystemTime { t: self.t.checked_add_duration(other)? })
342         }
343
344         pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
345             Some(SystemTime { t: self.t.checked_sub_duration(other)? })
346         }
347     }
348
349     impl From<libc::timespec> for SystemTime {
350         fn from(t: libc::timespec) -> SystemTime {
351             SystemTime { t: Timespec { t } }
352         }
353     }
354
355     impl fmt::Debug for SystemTime {
356         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
357             f.debug_struct("SystemTime")
358                 .field("tv_sec", &self.t.t.tv_sec)
359                 .field("tv_nsec", &self.t.t.tv_nsec)
360                 .finish()
361         }
362     }
363
364     #[cfg(not(target_os = "dragonfly"))]
365     pub type clock_t = libc::c_int;
366     #[cfg(target_os = "dragonfly")]
367     pub type clock_t = libc::c_ulong;
368
369     fn now(clock: clock_t) -> Timespec {
370         let mut t = Timespec { t: libc::timespec { tv_sec: 0, tv_nsec: 0 } };
371         cvt(unsafe { libc::clock_gettime(clock, &mut t.t) }).unwrap();
372         t
373     }
374 }