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 Ok(if self.t.tv_nsec >= other.t.tv_nsec {
25 (self.t.tv_sec - other.t.tv_sec) as u64,
26 (self.t.tv_nsec - other.t.tv_nsec) as u32,
30 (self.t.tv_sec - 1 - other.t.tv_sec) as u64,
31 self.t.tv_nsec as u32 + (NSEC_PER_SEC as u32) - other.t.tv_nsec as u32,
35 match other.sub_timespec(self) {
42 fn checked_add_duration(&self, other: &Duration) -> Option<Timespec> {
45 .try_into() // <- target type would be `libc::time_t`
47 .and_then(|secs| self.t.tv_sec.checked_add(secs))?;
49 // Nano calculations can't overflow because nanos are <1B which fit
51 let mut nsec = other.subsec_nanos() + self.t.tv_nsec as u32;
52 if nsec >= NSEC_PER_SEC as u32 {
53 nsec -= NSEC_PER_SEC as u32;
54 secs = secs.checked_add(1)?;
56 Some(Timespec { t: libc::timespec { tv_sec: secs, tv_nsec: nsec as _ } })
59 fn checked_sub_duration(&self, other: &Duration) -> Option<Timespec> {
62 .try_into() // <- target type would be `libc::time_t`
64 .and_then(|secs| self.t.tv_sec.checked_sub(secs))?;
66 // Similar to above, nanos can't overflow.
67 let mut nsec = self.t.tv_nsec as i32 - other.subsec_nanos() as i32;
69 nsec += NSEC_PER_SEC as i32;
70 secs = secs.checked_sub(1)?;
72 Some(Timespec { t: libc::timespec { tv_sec: secs, tv_nsec: nsec as _ } })
76 impl PartialEq for Timespec {
77 fn eq(&self, other: &Timespec) -> bool {
78 self.t.tv_sec == other.t.tv_sec && self.t.tv_nsec == other.t.tv_nsec
82 impl Eq for Timespec {}
84 impl PartialOrd for Timespec {
85 fn partial_cmp(&self, other: &Timespec) -> Option<Ordering> {
90 impl Ord for Timespec {
91 fn cmp(&self, other: &Timespec) -> Ordering {
92 let me = (self.t.tv_sec, self.t.tv_nsec);
93 let other = (other.t.tv_sec, other.t.tv_nsec);
98 impl Hash for Timespec {
99 fn hash<H: Hasher>(&self, state: &mut H) {
100 self.t.tv_sec.hash(state);
101 self.t.tv_nsec.hash(state);
105 #[cfg(any(target_os = "macos", target_os = "ios"))]
109 use crate::sync::atomic::{AtomicUsize, Ordering::SeqCst};
111 use crate::sys_common::mul_div_u64;
112 use crate::time::Duration;
115 use super::NSEC_PER_SEC;
117 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
122 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
123 pub struct SystemTime {
127 pub const UNIX_EPOCH: SystemTime = SystemTime { t: Timespec::zero() };
130 #[derive(Copy, Clone)]
131 struct mach_timebase_info {
135 type mach_timebase_info_t = *mut mach_timebase_info;
136 type kern_return_t = libc::c_int;
139 pub fn now() -> Instant {
141 fn mach_absolute_time() -> u64;
143 Instant { t: unsafe { mach_absolute_time() } }
146 pub const fn zero() -> Instant {
150 pub fn actually_monotonic() -> bool {
154 pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> {
155 let diff = self.t.checked_sub(other.t)?;
157 let nanos = mul_div_u64(diff, info.numer as u64, info.denom as u64);
158 Some(Duration::new(nanos / NSEC_PER_SEC, (nanos % NSEC_PER_SEC) as u32))
161 pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
162 Some(Instant { t: self.t.checked_add(checked_dur2intervals(other)?)? })
165 pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
166 Some(Instant { t: self.t.checked_sub(checked_dur2intervals(other)?)? })
171 pub fn now() -> SystemTime {
174 let mut s = libc::timeval { tv_sec: 0, tv_usec: 0 };
175 cvt(unsafe { libc::gettimeofday(&mut s, ptr::null_mut()) }).unwrap();
176 return SystemTime::from(s);
179 pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> {
180 self.t.sub_timespec(&other.t)
183 pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
184 Some(SystemTime { t: self.t.checked_add_duration(other)? })
187 pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
188 Some(SystemTime { t: self.t.checked_sub_duration(other)? })
192 impl From<libc::timeval> for SystemTime {
193 fn from(t: libc::timeval) -> SystemTime {
194 SystemTime::from(libc::timespec {
196 tv_nsec: (t.tv_usec * 1000) as libc::c_long,
201 impl From<libc::timespec> for SystemTime {
202 fn from(t: libc::timespec) -> SystemTime {
203 SystemTime { t: Timespec { t } }
207 impl fmt::Debug for SystemTime {
208 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209 f.debug_struct("SystemTime")
210 .field("tv_sec", &self.t.t.tv_sec)
211 .field("tv_nsec", &self.t.t.tv_nsec)
216 fn checked_dur2intervals(dur: &Duration) -> Option<u64> {
218 dur.as_secs().checked_mul(NSEC_PER_SEC)?.checked_add(dur.subsec_nanos() as u64)?;
220 Some(mul_div_u64(nanos, info.denom as u64, info.numer as u64))
223 fn info() -> mach_timebase_info {
224 static mut INFO: mach_timebase_info = mach_timebase_info { numer: 0, denom: 0 };
225 static STATE: AtomicUsize = AtomicUsize::new(0);
228 // If a previous thread has filled in this global state, use that.
229 if STATE.load(SeqCst) == 2 {
233 // ... otherwise learn for ourselves ...
234 let mut info = mem::zeroed();
236 fn mach_timebase_info(info: mach_timebase_info_t) -> kern_return_t;
239 mach_timebase_info(&mut info);
241 // ... and attempt to be the one thread that stores it globally for
243 if STATE.compare_exchange(0, 1, SeqCst, SeqCst).is_ok() {
245 STATE.store(2, SeqCst);
252 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
256 use crate::time::Duration;
260 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
265 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
266 pub struct SystemTime {
270 pub const UNIX_EPOCH: SystemTime = SystemTime { t: Timespec::zero() };
273 pub fn now() -> Instant {
274 Instant { t: now(libc::CLOCK_MONOTONIC) }
277 pub const fn zero() -> Instant {
278 Instant { t: Timespec::zero() }
281 pub fn actually_monotonic() -> bool {
282 (cfg!(target_os = "linux") && cfg!(target_arch = "x86_64"))
283 || (cfg!(target_os = "linux") && cfg!(target_arch = "x86"))
284 || cfg!(target_os = "fuchsia")
287 pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> {
288 self.t.sub_timespec(&other.t).ok()
291 pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
292 Some(Instant { t: self.t.checked_add_duration(other)? })
295 pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
296 Some(Instant { t: self.t.checked_sub_duration(other)? })
300 impl fmt::Debug for Instant {
301 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
302 f.debug_struct("Instant")
303 .field("tv_sec", &self.t.t.tv_sec)
304 .field("tv_nsec", &self.t.t.tv_nsec)
310 pub fn now() -> SystemTime {
311 SystemTime { t: now(libc::CLOCK_REALTIME) }
314 pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> {
315 self.t.sub_timespec(&other.t)
318 pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
319 Some(SystemTime { t: self.t.checked_add_duration(other)? })
322 pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
323 Some(SystemTime { t: self.t.checked_sub_duration(other)? })
327 impl From<libc::timespec> for SystemTime {
328 fn from(t: libc::timespec) -> SystemTime {
329 SystemTime { t: Timespec { t } }
333 impl fmt::Debug for SystemTime {
334 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335 f.debug_struct("SystemTime")
336 .field("tv_sec", &self.t.t.tv_sec)
337 .field("tv_nsec", &self.t.t.tv_nsec)
342 #[cfg(not(target_os = "dragonfly"))]
343 pub type clock_t = libc::c_int;
344 #[cfg(target_os = "dragonfly")]
345 pub type clock_t = libc::c_ulong;
347 fn now(clock: clock_t) -> Timespec {
348 let mut t = Timespec { t: libc::timespec { tv_sec: 0, tv_nsec: 0 } };
349 cvt(unsafe { libc::clock_gettime(clock, &mut t.t) }).unwrap();