1 use crate::cmp::Ordering;
2 use crate::time::Duration;
4 use core::hash::{Hash, Hasher};
6 pub use self::inner::{Instant, SystemTime, UNIX_EPOCH};
7 use crate::convert::TryInto;
9 const NSEC_PER_SEC: u64 = 1_000_000_000;
11 #[derive(Copy, Clone)]
17 const fn zero() -> Timespec {
18 Timespec { t: libc::timespec { tv_sec: 0, tv_nsec: 0 } }
21 fn sub_timespec(&self, other: &Timespec) -> Result<Duration, Duration> {
23 // NOTE(eddyb) two aspects of this `if`-`else` are required for LLVM
24 // to optimize it into a branchless form (see also #75545):
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`)
31 // 2. the `Duration::new` call (or any other additional complexity)
32 // is outside of the `if`-`else`, not duplicated in both branches
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)
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,
45 Ok(Duration::new(secs, nsec))
47 match other.sub_timespec(self) {
54 fn checked_add_duration(&self, other: &Duration) -> Option<Timespec> {
57 .try_into() // <- target type would be `libc::time_t`
59 .and_then(|secs| self.t.tv_sec.checked_add(secs))?;
61 // Nano calculations can't overflow because nanos are <1B which fit
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)?;
68 Some(Timespec { t: libc::timespec { tv_sec: secs, tv_nsec: nsec as _ } })
71 fn checked_sub_duration(&self, other: &Duration) -> Option<Timespec> {
74 .try_into() // <- target type would be `libc::time_t`
76 .and_then(|secs| self.t.tv_sec.checked_sub(secs))?;
78 // Similar to above, nanos can't overflow.
79 let mut nsec = self.t.tv_nsec as i32 - other.subsec_nanos() as i32;
81 nsec += NSEC_PER_SEC as i32;
82 secs = secs.checked_sub(1)?;
84 Some(Timespec { t: libc::timespec { tv_sec: secs, tv_nsec: nsec as _ } })
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
94 impl Eq for Timespec {}
96 impl PartialOrd for Timespec {
97 fn partial_cmp(&self, other: &Timespec) -> Option<Ordering> {
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);
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);
117 #[cfg(any(target_os = "macos", target_os = "ios"))]
121 use crate::sync::atomic::{AtomicUsize, Ordering::SeqCst};
123 use crate::sys_common::mul_div_u64;
124 use crate::time::Duration;
127 use super::NSEC_PER_SEC;
129 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
134 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
135 pub struct SystemTime {
139 pub const UNIX_EPOCH: SystemTime = SystemTime { t: Timespec::zero() };
142 #[derive(Copy, Clone)]
143 struct mach_timebase_info {
147 type mach_timebase_info_t = *mut mach_timebase_info;
148 type kern_return_t = libc::c_int;
151 pub fn now() -> Instant {
153 fn mach_absolute_time() -> u64;
155 Instant { t: unsafe { mach_absolute_time() } }
158 pub const fn zero() -> Instant {
162 pub fn actually_monotonic() -> bool {
166 pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> {
167 let diff = self.t.checked_sub(other.t)?;
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))
173 pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
174 Some(Instant { t: self.t.checked_add(checked_dur2intervals(other)?)? })
177 pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
178 Some(Instant { t: self.t.checked_sub(checked_dur2intervals(other)?)? })
183 pub fn now() -> SystemTime {
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);
191 pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> {
192 self.t.sub_timespec(&other.t)
195 pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
196 Some(SystemTime { t: self.t.checked_add_duration(other)? })
199 pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
200 Some(SystemTime { t: self.t.checked_sub_duration(other)? })
204 impl From<libc::timeval> for SystemTime {
205 fn from(t: libc::timeval) -> SystemTime {
206 SystemTime::from(libc::timespec {
208 tv_nsec: (t.tv_usec * 1000) as libc::c_long,
213 impl From<libc::timespec> for SystemTime {
214 fn from(t: libc::timespec) -> SystemTime {
215 SystemTime { t: Timespec { t } }
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)
228 fn checked_dur2intervals(dur: &Duration) -> Option<u64> {
230 dur.as_secs().checked_mul(NSEC_PER_SEC)?.checked_add(dur.subsec_nanos() as u64)?;
232 Some(mul_div_u64(nanos, info.denom as u64, info.numer as u64))
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);
240 // If a previous thread has filled in this global state, use that.
241 if STATE.load(SeqCst) == 2 {
245 // ... otherwise learn for ourselves ...
246 let mut info = mem::zeroed();
248 fn mach_timebase_info(info: mach_timebase_info_t) -> kern_return_t;
251 mach_timebase_info(&mut info);
253 // ... and attempt to be the one thread that stores it globally for
255 if STATE.compare_exchange(0, 1, SeqCst, SeqCst).is_ok() {
257 STATE.store(2, SeqCst);
264 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
268 use crate::time::Duration;
272 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
277 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
278 pub struct SystemTime {
282 pub const UNIX_EPOCH: SystemTime = SystemTime { t: Timespec::zero() };
285 pub fn now() -> Instant {
286 Instant { t: now(libc::CLOCK_MONOTONIC) }
289 pub const fn zero() -> Instant {
290 Instant { t: Timespec::zero() }
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")
299 pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> {
300 self.t.sub_timespec(&other.t).ok()
303 pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
304 Some(Instant { t: self.t.checked_add_duration(other)? })
307 pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
308 Some(Instant { t: self.t.checked_sub_duration(other)? })
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)
322 pub fn now() -> SystemTime {
323 SystemTime { t: now(libc::CLOCK_REALTIME) }
326 pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> {
327 self.t.sub_timespec(&other.t)
330 pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
331 Some(SystemTime { t: self.t.checked_add_duration(other)? })
334 pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
335 Some(SystemTime { t: self.t.checked_sub_duration(other)? })
339 impl From<libc::timespec> for SystemTime {
340 fn from(t: libc::timespec) -> SystemTime {
341 SystemTime { t: Timespec { t } }
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)
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;
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();