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"))]
120 use crate::sync::atomic::{AtomicU64, Ordering};
122 use crate::sys_common::mul_div_u64;
123 use crate::time::Duration;
126 use super::NSEC_PER_SEC;
128 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
133 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
134 pub struct SystemTime {
138 pub const UNIX_EPOCH: SystemTime = SystemTime { t: Timespec::zero() };
141 #[derive(Copy, Clone)]
142 struct mach_timebase_info {
146 type mach_timebase_info_t = *mut mach_timebase_info;
147 type kern_return_t = libc::c_int;
150 pub fn now() -> Instant {
152 fn mach_absolute_time() -> u64;
154 Instant { t: unsafe { mach_absolute_time() } }
157 pub const fn zero() -> Instant {
161 pub fn actually_monotonic() -> bool {
165 pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> {
166 let diff = self.t.checked_sub(other.t)?;
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))
172 pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
173 Some(Instant { t: self.t.checked_add(checked_dur2intervals(other)?)? })
176 pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
177 Some(Instant { t: self.t.checked_sub(checked_dur2intervals(other)?)? })
182 pub fn now() -> SystemTime {
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);
190 pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> {
191 self.t.sub_timespec(&other.t)
194 pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
195 Some(SystemTime { t: self.t.checked_add_duration(other)? })
198 pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
199 Some(SystemTime { t: self.t.checked_sub_duration(other)? })
203 impl From<libc::timeval> for SystemTime {
204 fn from(t: libc::timeval) -> SystemTime {
205 SystemTime::from(libc::timespec {
207 tv_nsec: (t.tv_usec * 1000) as libc::c_long,
212 impl From<libc::timespec> for SystemTime {
213 fn from(t: libc::timespec) -> SystemTime {
214 SystemTime { t: Timespec { t } }
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)
227 fn checked_dur2intervals(dur: &Duration) -> Option<u64> {
229 dur.as_secs().checked_mul(NSEC_PER_SEC)?.checked_add(dur.subsec_nanos() as u64)?;
231 Some(mul_div_u64(nanos, info.denom as u64, info.numer as u64))
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
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
242 static INFO_BITS: AtomicU64 = AtomicU64::new(0);
244 // If a previous thread has initialized `INFO_BITS`, use it.
245 let info_bits = INFO_BITS.load(Ordering::Relaxed);
247 return info_from_bits(info_bits);
250 // ... otherwise learn for ourselves ...
252 fn mach_timebase_info(info: mach_timebase_info_t) -> kern_return_t;
255 let mut info = info_from_bits(0);
257 mach_timebase_info(&mut info);
259 INFO_BITS.store(info_to_bits(info), Ordering::Relaxed);
264 fn info_to_bits(info: mach_timebase_info) -> u64 {
265 ((info.denom as u64) << 32) | (info.numer as u64)
269 fn info_from_bits(bits: u64) -> mach_timebase_info {
270 mach_timebase_info { numer: bits as u32, denom: (bits >> 32) as u32 }
274 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
278 use crate::time::Duration;
282 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
287 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
288 pub struct SystemTime {
292 pub const UNIX_EPOCH: SystemTime = SystemTime { t: Timespec::zero() };
295 pub fn now() -> Instant {
296 Instant { t: now(libc::CLOCK_MONOTONIC) }
299 pub const fn zero() -> Instant {
300 Instant { t: Timespec::zero() }
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")
309 pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> {
310 self.t.sub_timespec(&other.t).ok()
313 pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
314 Some(Instant { t: self.t.checked_add_duration(other)? })
317 pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
318 Some(Instant { t: self.t.checked_sub_duration(other)? })
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)
332 pub fn now() -> SystemTime {
333 SystemTime { t: now(libc::CLOCK_REALTIME) }
336 pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> {
337 self.t.sub_timespec(&other.t)
340 pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
341 Some(SystemTime { t: self.t.checked_add_duration(other)? })
344 pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
345 Some(SystemTime { t: self.t.checked_sub_duration(other)? })
349 impl From<libc::timespec> for SystemTime {
350 fn from(t: libc::timespec) -> SystemTime {
351 SystemTime { t: Timespec { t } }
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)
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;
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();