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)] pub const TIMESPEC_MAX: libc::timespec =
10 libc::timespec { tv_sec: <libc::time_t>::MAX, tv_nsec: 1_000_000_000 - 1 };
11
12#[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 #[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 #[cfg_attr(
102 all(
103 target_os = "linux",
104 target_env = "gnu",
105 target_pointer_width = "32",
106 not(target_arch = "riscv32")
107 ),
108 no_sanitize(cfi)
109 )]
110 pub fn now(clock: libc::clockid_t) -> Timespec {
111 use crate::mem::MaybeUninit;
112 use crate::sys::cvt;
113
114 #[cfg(all(
116 target_os = "linux",
117 target_env = "gnu",
118 target_pointer_width = "32",
119 not(target_arch = "riscv32")
120 ))]
121 {
122 use crate::sys::weak::weak;
123
124 weak!(
127 fn __clock_gettime64(
128 clockid: libc::clockid_t,
129 tp: *mut __timespec64,
130 ) -> libc::c_int;
131 );
132
133 if let Some(clock_gettime64) = __clock_gettime64.get() {
134 let mut t = MaybeUninit::uninit();
135 cvt(unsafe { clock_gettime64(clock, t.as_mut_ptr()) }).unwrap();
136 let t = unsafe { t.assume_init() };
137 return Timespec::new(t.tv_sec as i64, t.tv_nsec as i64).unwrap();
138 }
139 }
140
141 let mut t = MaybeUninit::uninit();
142 cvt(unsafe { libc::clock_gettime(clock, t.as_mut_ptr()) }).unwrap();
143 let t = unsafe { t.assume_init() };
144 Timespec::new(t.tv_sec as i64, t.tv_nsec as i64).unwrap()
145 }
146
147 pub fn sub_timespec(&self, other: &Timespec) -> Result<Duration, Duration> {
148 if self >= other {
149 let (secs, nsec) = if self.tv_nsec.as_inner() >= other.tv_nsec.as_inner() {
163 (
164 (self.tv_sec - other.tv_sec) as u64,
165 self.tv_nsec.as_inner() - other.tv_nsec.as_inner(),
166 )
167 } else {
168 (
169 (self.tv_sec - other.tv_sec - 1) as u64,
170 self.tv_nsec.as_inner() + (NSEC_PER_SEC as u32) - other.tv_nsec.as_inner(),
171 )
172 };
173
174 Ok(Duration::new(secs, nsec))
175 } else {
176 match other.sub_timespec(self) {
177 Ok(d) => Err(d),
178 Err(d) => Ok(d),
179 }
180 }
181 }
182
183 pub fn checked_add_duration(&self, other: &Duration) -> Option<Timespec> {
184 let mut secs = self.tv_sec.checked_add_unsigned(other.as_secs())?;
185
186 let mut nsec = other.subsec_nanos() + self.tv_nsec.as_inner();
189 if nsec >= NSEC_PER_SEC as u32 {
190 nsec -= NSEC_PER_SEC as u32;
191 secs = secs.checked_add(1)?;
192 }
193 Some(unsafe { Timespec::new_unchecked(secs, nsec.into()) })
194 }
195
196 pub fn checked_sub_duration(&self, other: &Duration) -> Option<Timespec> {
197 let mut secs = self.tv_sec.checked_sub_unsigned(other.as_secs())?;
198
199 let mut nsec = self.tv_nsec.as_inner() as i32 - other.subsec_nanos() as i32;
201 if nsec < 0 {
202 nsec += NSEC_PER_SEC as i32;
203 secs = secs.checked_sub(1)?;
204 }
205 Some(unsafe { Timespec::new_unchecked(secs, nsec.into()) })
206 }
207
208 #[allow(dead_code)]
209 pub fn to_timespec(&self) -> Option<libc::timespec> {
210 Some(libc::timespec {
211 tv_sec: self.tv_sec.try_into().ok()?,
212 tv_nsec: self.tv_nsec.as_inner().try_into().ok()?,
213 })
214 }
215
216 #[cfg(target_os = "nto")]
219 pub(in crate::sys) fn to_timespec_capped(&self) -> Option<libc::timespec> {
220 if (self.tv_nsec.as_inner() as u64)
222 .checked_add((self.tv_sec as u64).checked_mul(NSEC_PER_SEC)?)
223 .is_none()
224 {
225 return None;
226 }
227 self.to_timespec()
228 }
229
230 #[cfg(all(
231 target_os = "linux",
232 target_env = "gnu",
233 target_pointer_width = "32",
234 not(target_arch = "riscv32")
235 ))]
236 pub fn to_timespec64(&self) -> __timespec64 {
237 __timespec64::new(self.tv_sec, self.tv_nsec.as_inner() as _)
238 }
239}
240
241#[cfg(all(
242 target_os = "linux",
243 target_env = "gnu",
244 target_pointer_width = "32",
245 not(target_arch = "riscv32")
246))]
247#[repr(C)]
248pub(crate) struct __timespec64 {
249 pub(crate) tv_sec: i64,
250 #[cfg(target_endian = "big")]
251 _padding: i32,
252 pub(crate) tv_nsec: i32,
253 #[cfg(target_endian = "little")]
254 _padding: i32,
255}
256
257#[cfg(all(
258 target_os = "linux",
259 target_env = "gnu",
260 target_pointer_width = "32",
261 not(target_arch = "riscv32")
262))]
263impl __timespec64 {
264 pub(crate) fn new(tv_sec: i64, tv_nsec: i32) -> Self {
265 Self { tv_sec, tv_nsec, _padding: 0 }
266 }
267}
268
269#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
270pub struct Instant {
271 t: Timespec,
272}
273
274impl Instant {
275 pub fn now() -> Instant {
276 #[cfg(target_vendor = "apple")]
288 const clock_id: libc::clockid_t = libc::CLOCK_UPTIME_RAW;
289 #[cfg(not(target_vendor = "apple"))]
290 const clock_id: libc::clockid_t = libc::CLOCK_MONOTONIC;
291 Instant { t: Timespec::now(clock_id) }
292 }
293
294 pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> {
295 self.t.sub_timespec(&other.t).ok()
296 }
297
298 pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
299 Some(Instant { t: self.t.checked_add_duration(other)? })
300 }
301
302 pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
303 Some(Instant { t: self.t.checked_sub_duration(other)? })
304 }
305}
306
307impl fmt::Debug for Instant {
308 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
309 f.debug_struct("Instant")
310 .field("tv_sec", &self.t.tv_sec)
311 .field("tv_nsec", &self.t.tv_nsec)
312 .finish()
313 }
314}