2 use crate::time::Duration;
4 pub use self::inner::Instant;
6 const NSEC_PER_SEC: u64 = 1_000_000_000;
7 pub const UNIX_EPOCH: SystemTime = SystemTime { t: Timespec::zero() };
9 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
11 #[rustc_layout_scalar_valid_range_start(0)]
12 #[rustc_layout_scalar_valid_range_end(999_999_999)]
13 struct Nanoseconds(u32);
15 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
16 pub struct SystemTime {
17 pub(in crate::sys::unix) t: Timespec,
20 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
21 pub(in crate::sys::unix) struct Timespec {
27 #[cfg_attr(target_os = "horizon", allow(unused))]
28 pub fn new(tv_sec: i64, tv_nsec: i64) -> SystemTime {
29 SystemTime { t: Timespec::new(tv_sec, tv_nsec) }
32 pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> {
33 self.t.sub_timespec(&other.t)
36 pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
37 Some(SystemTime { t: self.t.checked_add_duration(other)? })
40 pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
41 Some(SystemTime { t: self.t.checked_sub_duration(other)? })
45 impl From<libc::timespec> for SystemTime {
46 fn from(t: libc::timespec) -> SystemTime {
47 SystemTime { t: Timespec::from(t) }
51 impl fmt::Debug for SystemTime {
52 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53 f.debug_struct("SystemTime")
54 .field("tv_sec", &self.t.tv_sec)
55 .field("tv_nsec", &self.t.tv_nsec.0)
61 pub const fn zero() -> Timespec {
65 const fn new(tv_sec: i64, tv_nsec: i64) -> Timespec {
66 assert!(tv_nsec >= 0 && tv_nsec < NSEC_PER_SEC as i64);
67 // SAFETY: The assert above checks tv_nsec is within the valid range
68 Timespec { tv_sec, tv_nsec: unsafe { Nanoseconds(tv_nsec as u32) } }
71 pub fn sub_timespec(&self, other: &Timespec) -> Result<Duration, Duration> {
73 // NOTE(eddyb) two aspects of this `if`-`else` are required for LLVM
74 // to optimize it into a branchless form (see also #75545):
76 // 1. `self.tv_sec - other.tv_sec` shows up as a common expression
77 // in both branches, i.e. the `else` must have its `- 1`
78 // subtraction after the common one, not interleaved with it
79 // (it used to be `self.tv_sec - 1 - other.tv_sec`)
81 // 2. the `Duration::new` call (or any other additional complexity)
82 // is outside of the `if`-`else`, not duplicated in both branches
84 // Ideally this code could be rearranged such that it more
85 // directly expresses the lower-cost behavior we want from it.
86 let (secs, nsec) = if self.tv_nsec.0 >= other.tv_nsec.0 {
87 ((self.tv_sec - other.tv_sec) as u64, self.tv_nsec.0 - other.tv_nsec.0)
90 (self.tv_sec - other.tv_sec - 1) as u64,
91 self.tv_nsec.0 + (NSEC_PER_SEC as u32) - other.tv_nsec.0,
95 Ok(Duration::new(secs, nsec))
97 match other.sub_timespec(self) {
104 pub fn checked_add_duration(&self, other: &Duration) -> Option<Timespec> {
107 .try_into() // <- target type would be `i64`
109 .and_then(|secs| self.tv_sec.checked_add(secs))?;
111 // Nano calculations can't overflow because nanos are <1B which fit
113 let mut nsec = other.subsec_nanos() + self.tv_nsec.0;
114 if nsec >= NSEC_PER_SEC as u32 {
115 nsec -= NSEC_PER_SEC as u32;
116 secs = secs.checked_add(1)?;
118 Some(Timespec::new(secs, nsec as i64))
121 pub fn checked_sub_duration(&self, other: &Duration) -> Option<Timespec> {
124 .try_into() // <- target type would be `i64`
126 .and_then(|secs| self.tv_sec.checked_sub(secs))?;
128 // Similar to above, nanos can't overflow.
129 let mut nsec = self.tv_nsec.0 as i32 - other.subsec_nanos() as i32;
131 nsec += NSEC_PER_SEC as i32;
132 secs = secs.checked_sub(1)?;
134 Some(Timespec::new(secs, nsec as i64))
138 pub fn to_timespec(&self) -> Option<libc::timespec> {
139 Some(libc::timespec {
140 tv_sec: self.tv_sec.try_into().ok()?,
141 tv_nsec: self.tv_nsec.0.try_into().ok()?,
146 impl From<libc::timespec> for Timespec {
147 fn from(t: libc::timespec) -> Timespec {
148 Timespec::new(t.tv_sec as i64, t.tv_nsec as i64)
152 #[cfg(any(target_os = "macos", target_os = "ios", target_os = "watchos"))]
154 use crate::sync::atomic::{AtomicU64, Ordering};
156 use crate::sys_common::mul_div_u64;
157 use crate::time::Duration;
159 use super::{SystemTime, Timespec, NSEC_PER_SEC};
161 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
167 #[derive(Copy, Clone)]
168 struct mach_timebase_info {
172 type mach_timebase_info_t = *mut mach_timebase_info;
173 type kern_return_t = libc::c_int;
176 pub fn now() -> Instant {
178 fn mach_absolute_time() -> u64;
180 Instant { t: unsafe { mach_absolute_time() } }
183 pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> {
184 let diff = self.t.checked_sub(other.t)?;
186 let nanos = mul_div_u64(diff, info.numer as u64, info.denom as u64);
187 Some(Duration::new(nanos / NSEC_PER_SEC, (nanos % NSEC_PER_SEC) as u32))
190 pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
191 Some(Instant { t: self.t.checked_add(checked_dur2intervals(other)?)? })
194 pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
195 Some(Instant { t: self.t.checked_sub(checked_dur2intervals(other)?)? })
200 pub fn now() -> SystemTime {
203 let mut s = libc::timeval { tv_sec: 0, tv_usec: 0 };
204 cvt(unsafe { libc::gettimeofday(&mut s, ptr::null_mut()) }).unwrap();
205 return SystemTime::from(s);
209 impl From<libc::timeval> for Timespec {
210 fn from(t: libc::timeval) -> Timespec {
211 Timespec::new(t.tv_sec as i64, 1000 * t.tv_usec as i64)
215 impl From<libc::timeval> for SystemTime {
216 fn from(t: libc::timeval) -> SystemTime {
217 SystemTime { t: Timespec::from(t) }
221 fn checked_dur2intervals(dur: &Duration) -> Option<u64> {
223 dur.as_secs().checked_mul(NSEC_PER_SEC)?.checked_add(dur.subsec_nanos() as u64)?;
225 Some(mul_div_u64(nanos, info.denom as u64, info.numer as u64))
228 fn info() -> mach_timebase_info {
229 // INFO_BITS conceptually is an `Option<mach_timebase_info>`. We can do
230 // this in 64 bits because we know 0 is never a valid value for the
233 // Encoding this as a single `AtomicU64` allows us to use `Relaxed`
234 // operations, as we are only interested in the effects on a single
236 static INFO_BITS: AtomicU64 = AtomicU64::new(0);
238 // If a previous thread has initialized `INFO_BITS`, use it.
239 let info_bits = INFO_BITS.load(Ordering::Relaxed);
241 return info_from_bits(info_bits);
244 // ... otherwise learn for ourselves ...
246 fn mach_timebase_info(info: mach_timebase_info_t) -> kern_return_t;
249 let mut info = info_from_bits(0);
251 mach_timebase_info(&mut info);
253 INFO_BITS.store(info_to_bits(info), Ordering::Relaxed);
258 fn info_to_bits(info: mach_timebase_info) -> u64 {
259 ((info.denom as u64) << 32) | (info.numer as u64)
263 fn info_from_bits(bits: u64) -> mach_timebase_info {
264 mach_timebase_info { numer: bits as u32, denom: (bits >> 32) as u32 }
268 #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "watchos")))]
271 use crate::mem::MaybeUninit;
273 use crate::time::Duration;
275 use super::{SystemTime, Timespec};
277 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
283 pub fn now() -> Instant {
284 Instant { t: Timespec::now(libc::CLOCK_MONOTONIC) }
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.tv_sec)
304 .field("tv_nsec", &self.t.tv_nsec.0)
310 pub fn now() -> SystemTime {
311 SystemTime { t: Timespec::now(libc::CLOCK_REALTIME) }
315 #[cfg(not(any(target_os = "dragonfly", target_os = "espidf", target_os = "horizon")))]
316 pub type clock_t = libc::c_int;
317 #[cfg(any(target_os = "dragonfly", target_os = "espidf", target_os = "horizon"))]
318 pub type clock_t = libc::c_ulong;
321 pub fn now(clock: clock_t) -> Timespec {
322 // Try to use 64-bit time in preparation for Y2038.
323 #[cfg(all(target_os = "linux", target_env = "gnu", target_pointer_width = "32"))]
325 use crate::sys::weak::weak;
327 // __clock_gettime64 was added to 32-bit arches in glibc 2.34,
328 // and it handles both vDSO calls and ENOSYS fallbacks itself.
329 weak!(fn __clock_gettime64(libc::clockid_t, *mut __timespec64) -> libc::c_int);
332 struct __timespec64 {
334 #[cfg(target_endian = "big")]
337 #[cfg(target_endian = "little")]
341 if let Some(clock_gettime64) = __clock_gettime64.get() {
342 let mut t = MaybeUninit::uninit();
343 cvt(unsafe { clock_gettime64(clock, t.as_mut_ptr()) }).unwrap();
344 let t = unsafe { t.assume_init() };
345 return Timespec::new(t.tv_sec, t.tv_nsec as i64);
349 let mut t = MaybeUninit::uninit();
350 cvt(unsafe { libc::clock_gettime(clock, t.as_mut_ptr()) }).unwrap();
351 Timespec::from(unsafe { t.assume_init() })