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