std/sys/pal/unix/
time.rs

1use core::num::niche_types::Nanoseconds;
2
3use crate::time::Duration;
4use crate::{fmt, io};
5
6const NSEC_PER_SEC: u64 = 1_000_000_000;
7pub const UNIX_EPOCH: SystemTime = SystemTime { t: Timespec::zero() };
8#[allow(dead_code)] // Used for pthread condvar timeouts
9pub const TIMESPEC_MAX: libc::timespec =
10    libc::timespec { tv_sec: <libc::time_t>::MAX, tv_nsec: 1_000_000_000 - 1 };
11
12// This additional constant is only used when calling
13// `libc::pthread_cond_timedwait`.
14#[cfg(target_os = "nto")]
15pub(in crate::sys) const TIMESPEC_MAX_CAPPED: libc::timespec = libc::timespec {
16    tv_sec: (u64::MAX / NSEC_PER_SEC) as i64,
17    tv_nsec: (u64::MAX % NSEC_PER_SEC) as i64,
18};
19
20#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
21pub struct SystemTime {
22    pub(crate) t: Timespec,
23}
24
25#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
26pub(crate) struct Timespec {
27    tv_sec: i64,
28    tv_nsec: Nanoseconds,
29}
30
31impl SystemTime {
32    #[cfg_attr(any(target_os = "horizon", target_os = "hurd"), allow(unused))]
33    pub fn new(tv_sec: i64, tv_nsec: i64) -> Result<SystemTime, io::Error> {
34        Ok(SystemTime { t: Timespec::new(tv_sec, tv_nsec)? })
35    }
36
37    pub fn now() -> SystemTime {
38        SystemTime { t: Timespec::now(libc::CLOCK_REALTIME) }
39    }
40
41    pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> {
42        self.t.sub_timespec(&other.t)
43    }
44
45    pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
46        Some(SystemTime { t: self.t.checked_add_duration(other)? })
47    }
48
49    pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
50        Some(SystemTime { t: self.t.checked_sub_duration(other)? })
51    }
52}
53
54impl fmt::Debug for SystemTime {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        f.debug_struct("SystemTime")
57            .field("tv_sec", &self.t.tv_sec)
58            .field("tv_nsec", &self.t.tv_nsec)
59            .finish()
60    }
61}
62
63impl Timespec {
64    const unsafe fn new_unchecked(tv_sec: i64, tv_nsec: i64) -> Timespec {
65        Timespec { tv_sec, tv_nsec: unsafe { Nanoseconds::new_unchecked(tv_nsec as u32) } }
66    }
67
68    pub const fn zero() -> Timespec {
69        unsafe { Self::new_unchecked(0, 0) }
70    }
71
72    const fn new(tv_sec: i64, tv_nsec: i64) -> Result<Timespec, io::Error> {
73        // On Apple OS, dates before epoch are represented differently than on other
74        // Unix platforms: e.g. 1/10th of a second before epoch is represented as `seconds=-1`
75        // and `nanoseconds=100_000_000` on other platforms, but is `seconds=0` and
76        // `nanoseconds=-900_000_000` on Apple OS.
77        //
78        // To compensate, we first detect this special case by checking if both
79        // seconds and nanoseconds are in range, and then correct the value for seconds
80        // and nanoseconds to match the common unix representation.
81        //
82        // Please note that Apple OS nonetheless accepts the standard unix format when
83        // setting file times, which makes this compensation round-trippable and generally
84        // transparent.
85        #[cfg(target_vendor = "apple")]
86        let (tv_sec, tv_nsec) =
87            if (tv_sec <= 0 && tv_sec > i64::MIN) && (tv_nsec < 0 && tv_nsec > -1_000_000_000) {
88                (tv_sec - 1, tv_nsec + 1_000_000_000)
89            } else {
90                (tv_sec, tv_nsec)
91            };
92        if tv_nsec >= 0 && tv_nsec < NSEC_PER_SEC as i64 {
93            Ok(unsafe { Self::new_unchecked(tv_sec, tv_nsec) })
94        } else {
95            Err(io::const_error!(io::ErrorKind::InvalidData, "Invalid timestamp"))
96        }
97    }
98
99    pub fn now(clock: libc::clockid_t) -> Timespec {
100        use crate::mem::MaybeUninit;
101        use crate::sys::cvt;
102
103        // Try to use 64-bit time in preparation for Y2038.
104        #[cfg(all(
105            target_os = "linux",
106            target_env = "gnu",
107            target_pointer_width = "32",
108            not(target_arch = "riscv32")
109        ))]
110        {
111            use crate::sys::weak::weak;
112
113            // __clock_gettime64 was added to 32-bit arches in glibc 2.34,
114            // and it handles both vDSO calls and ENOSYS fallbacks itself.
115            weak!(fn __clock_gettime64(libc::clockid_t, *mut __timespec64) -> libc::c_int);
116
117            if let Some(clock_gettime64) = __clock_gettime64.get() {
118                let mut t = MaybeUninit::uninit();
119                cvt(unsafe { clock_gettime64(clock, t.as_mut_ptr()) }).unwrap();
120                let t = unsafe { t.assume_init() };
121                return Timespec::new(t.tv_sec as i64, t.tv_nsec as i64).unwrap();
122            }
123        }
124
125        let mut t = MaybeUninit::uninit();
126        cvt(unsafe { libc::clock_gettime(clock, t.as_mut_ptr()) }).unwrap();
127        let t = unsafe { t.assume_init() };
128        Timespec::new(t.tv_sec as i64, t.tv_nsec as i64).unwrap()
129    }
130
131    pub fn sub_timespec(&self, other: &Timespec) -> Result<Duration, Duration> {
132        if self >= other {
133            // NOTE(eddyb) two aspects of this `if`-`else` are required for LLVM
134            // to optimize it into a branchless form (see also #75545):
135            //
136            // 1. `self.tv_sec - other.tv_sec` shows up as a common expression
137            //    in both branches, i.e. the `else` must have its `- 1`
138            //    subtraction after the common one, not interleaved with it
139            //    (it used to be `self.tv_sec - 1 - other.tv_sec`)
140            //
141            // 2. the `Duration::new` call (or any other additional complexity)
142            //    is outside of the `if`-`else`, not duplicated in both branches
143            //
144            // Ideally this code could be rearranged such that it more
145            // directly expresses the lower-cost behavior we want from it.
146            let (secs, nsec) = if self.tv_nsec.as_inner() >= other.tv_nsec.as_inner() {
147                (
148                    (self.tv_sec - other.tv_sec) as u64,
149                    self.tv_nsec.as_inner() - other.tv_nsec.as_inner(),
150                )
151            } else {
152                (
153                    (self.tv_sec - other.tv_sec - 1) as u64,
154                    self.tv_nsec.as_inner() + (NSEC_PER_SEC as u32) - other.tv_nsec.as_inner(),
155                )
156            };
157
158            Ok(Duration::new(secs, nsec))
159        } else {
160            match other.sub_timespec(self) {
161                Ok(d) => Err(d),
162                Err(d) => Ok(d),
163            }
164        }
165    }
166
167    pub fn checked_add_duration(&self, other: &Duration) -> Option<Timespec> {
168        let mut secs = self.tv_sec.checked_add_unsigned(other.as_secs())?;
169
170        // Nano calculations can't overflow because nanos are <1B which fit
171        // in a u32.
172        let mut nsec = other.subsec_nanos() + self.tv_nsec.as_inner();
173        if nsec >= NSEC_PER_SEC as u32 {
174            nsec -= NSEC_PER_SEC as u32;
175            secs = secs.checked_add(1)?;
176        }
177        Some(unsafe { Timespec::new_unchecked(secs, nsec.into()) })
178    }
179
180    pub fn checked_sub_duration(&self, other: &Duration) -> Option<Timespec> {
181        let mut secs = self.tv_sec.checked_sub_unsigned(other.as_secs())?;
182
183        // Similar to above, nanos can't overflow.
184        let mut nsec = self.tv_nsec.as_inner() as i32 - other.subsec_nanos() as i32;
185        if nsec < 0 {
186            nsec += NSEC_PER_SEC as i32;
187            secs = secs.checked_sub(1)?;
188        }
189        Some(unsafe { Timespec::new_unchecked(secs, nsec.into()) })
190    }
191
192    #[allow(dead_code)]
193    pub fn to_timespec(&self) -> Option<libc::timespec> {
194        Some(libc::timespec {
195            tv_sec: self.tv_sec.try_into().ok()?,
196            tv_nsec: self.tv_nsec.as_inner().try_into().ok()?,
197        })
198    }
199
200    // On QNX Neutrino, the maximum timespec for e.g. pthread_cond_timedwait
201    // is 2^64 nanoseconds
202    #[cfg(target_os = "nto")]
203    pub(in crate::sys) fn to_timespec_capped(&self) -> Option<libc::timespec> {
204        // Check if timeout in nanoseconds would fit into an u64
205        if (self.tv_nsec.as_inner() as u64)
206            .checked_add((self.tv_sec as u64).checked_mul(NSEC_PER_SEC)?)
207            .is_none()
208        {
209            return None;
210        }
211        self.to_timespec()
212    }
213
214    #[cfg(all(
215        target_os = "linux",
216        target_env = "gnu",
217        target_pointer_width = "32",
218        not(target_arch = "riscv32")
219    ))]
220    pub fn to_timespec64(&self) -> __timespec64 {
221        __timespec64::new(self.tv_sec, self.tv_nsec.as_inner() as _)
222    }
223}
224
225#[cfg(all(
226    target_os = "linux",
227    target_env = "gnu",
228    target_pointer_width = "32",
229    not(target_arch = "riscv32")
230))]
231#[repr(C)]
232pub(crate) struct __timespec64 {
233    pub(crate) tv_sec: i64,
234    #[cfg(target_endian = "big")]
235    _padding: i32,
236    pub(crate) tv_nsec: i32,
237    #[cfg(target_endian = "little")]
238    _padding: i32,
239}
240
241#[cfg(all(
242    target_os = "linux",
243    target_env = "gnu",
244    target_pointer_width = "32",
245    not(target_arch = "riscv32")
246))]
247impl __timespec64 {
248    pub(crate) fn new(tv_sec: i64, tv_nsec: i32) -> Self {
249        Self { tv_sec, tv_nsec, _padding: 0 }
250    }
251}
252
253#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
254pub struct Instant {
255    t: Timespec,
256}
257
258impl Instant {
259    pub fn now() -> Instant {
260        // https://www.manpagez.com/man/3/clock_gettime/
261        //
262        // CLOCK_UPTIME_RAW   clock that increments monotonically, in the same man-
263        //                    ner as CLOCK_MONOTONIC_RAW, but that does not incre-
264        //                    ment while the system is asleep.  The returned value
265        //                    is identical to the result of mach_absolute_time()
266        //                    after the appropriate mach_timebase conversion is
267        //                    applied.
268        //
269        // Instant on macos was historically implemented using mach_absolute_time;
270        // we preserve this value domain out of an abundance of caution.
271        #[cfg(target_vendor = "apple")]
272        const clock_id: libc::clockid_t = libc::CLOCK_UPTIME_RAW;
273        #[cfg(not(target_vendor = "apple"))]
274        const clock_id: libc::clockid_t = libc::CLOCK_MONOTONIC;
275        Instant { t: Timespec::now(clock_id) }
276    }
277
278    pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> {
279        self.t.sub_timespec(&other.t).ok()
280    }
281
282    pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
283        Some(Instant { t: self.t.checked_add_duration(other)? })
284    }
285
286    pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
287        Some(Instant { t: self.t.checked_sub_duration(other)? })
288    }
289}
290
291impl fmt::Debug for Instant {
292    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293        f.debug_struct("Instant")
294            .field("tv_sec", &self.t.tv_sec)
295            .field("tv_nsec", &self.t.tv_nsec)
296            .finish()
297    }
298}