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 {
19 t: libc::timespec { tv_sec: 0, tv_nsec: 0 },
23 fn sub_timespec(&self, other: &Timespec) -> Result<Duration, Duration> {
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)
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)
34 match other.sub_timespec(self) {
41 fn checked_add_duration(&self, other: &Duration) -> Option<Timespec> {
44 .try_into() // <- target type would be `libc::time_t`
46 .and_then(|secs| self.t.tv_sec.checked_add(secs))?;
48 // Nano calculations can't overflow because nanos are <1B which fit
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)?;
63 fn checked_sub_duration(&self, other: &Duration) -> Option<Timespec> {
66 .try_into() // <- target type would be `libc::time_t`
68 .and_then(|secs| self.t.tv_sec.checked_sub(secs))?;
70 // Similar to above, nanos can't overflow.
71 let mut nsec = self.t.tv_nsec as i32 - other.subsec_nanos() as i32;
73 nsec += NSEC_PER_SEC as i32;
74 secs = secs.checked_sub(1)?;
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
91 impl Eq for Timespec {}
93 impl PartialOrd for Timespec {
94 fn partial_cmp(&self, other: &Timespec) -> Option<Ordering> {
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);
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);
114 #[cfg(any(target_os = "macos", target_os = "ios"))]
118 use crate::sync::atomic::{AtomicUsize, Ordering::SeqCst};
120 use crate::sys_common::mul_div_u64;
121 use crate::time::Duration;
123 use super::NSEC_PER_SEC;
126 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
131 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
132 pub struct SystemTime {
136 pub const UNIX_EPOCH: SystemTime = SystemTime {
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> {
174 t: self.t.checked_add(checked_dur2intervals(other)?)?,
178 pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
180 t: self.t.checked_sub(checked_dur2intervals(other)?)?,
186 pub fn now() -> SystemTime {
189 let mut s = libc::timeval {
194 libc::gettimeofday(&mut s, ptr::null_mut())
196 return SystemTime::from(s)
199 pub fn sub_time(&self, other: &SystemTime)
200 -> Result<Duration, Duration> {
201 self.t.sub_timespec(&other.t)
204 pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
205 Some(SystemTime { t: self.t.checked_add_duration(other)? })
208 pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
209 Some(SystemTime { t: self.t.checked_sub_duration(other)? })
213 impl From<libc::timeval> for SystemTime {
214 fn from(t: libc::timeval) -> SystemTime {
215 SystemTime::from(libc::timespec {
217 tv_nsec: (t.tv_usec * 1000) as libc::c_long,
222 impl From<libc::timespec> for SystemTime {
223 fn from(t: libc::timespec) -> SystemTime {
224 SystemTime { t: Timespec { t } }
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)
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)?;
242 Some(mul_div_u64(nanos, info.denom as u64, info.numer as u64))
245 fn info() -> mach_timebase_info {
246 static mut INFO: mach_timebase_info = mach_timebase_info {
250 static STATE: AtomicUsize = AtomicUsize::new(0);
253 // If a previous thread has filled in this global state, use that.
254 if STATE.load(SeqCst) == 2 {
258 // ... otherwise learn for ourselves ...
259 let mut info = mem::zeroed();
261 fn mach_timebase_info(info: mach_timebase_info_t)
265 mach_timebase_info(&mut info);
267 // ... and attempt to be the one thread that stores it globally for
269 if STATE.compare_exchange(0, 1, SeqCst, SeqCst).is_ok() {
271 STATE.store(2, SeqCst);
278 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
282 use crate::time::Duration;
286 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
291 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
292 pub struct SystemTime {
296 pub const UNIX_EPOCH: SystemTime = SystemTime {
301 pub fn now() -> Instant {
302 Instant { t: now(libc::CLOCK_MONOTONIC) }
305 pub const fn zero() -> Instant {
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
318 pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> {
319 self.t.sub_timespec(&other.t).ok()
322 pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
323 Some(Instant { t: self.t.checked_add_duration(other)? })
326 pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
327 Some(Instant { t: self.t.checked_sub_duration(other)? })
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)
341 pub fn now() -> SystemTime {
342 SystemTime { t: now(libc::CLOCK_REALTIME) }
345 pub fn sub_time(&self, other: &SystemTime)
346 -> Result<Duration, Duration> {
347 self.t.sub_timespec(&other.t)
350 pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
351 Some(SystemTime { t: self.t.checked_add_duration(other)? })
354 pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
355 Some(SystemTime { t: self.t.checked_sub_duration(other)? })
359 impl From<libc::timespec> for SystemTime {
360 fn from(t: libc::timespec) -> SystemTime {
361 SystemTime { t: Timespec { t } }
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)
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;
379 fn now(clock: clock_t) -> Timespec {
380 let mut t = Timespec {
387 libc::clock_gettime(clock, &mut t.t)