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