1use core::num::niche_types::Nanoseconds;
2
3use crate::io;
4use crate::time::Duration;
5
6const NSEC_PER_SEC: u64 = 1_000_000_000;
7
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(crate) struct Timespec {
22 pub tv_sec: i64,
23 pub tv_nsec: Nanoseconds,
24}
25
26impl Timespec {
27 pub const MAX: Timespec = unsafe { Self::new_unchecked(i64::MAX, 1_000_000_000 - 1) };
28
29 pub const MIN: Timespec = unsafe { Self::new_unchecked(i64::MIN, 0) };
33
34 const unsafe fn new_unchecked(tv_sec: i64, tv_nsec: i64) -> Timespec {
35 Timespec { tv_sec, tv_nsec: unsafe { Nanoseconds::new_unchecked(tv_nsec as u32) } }
36 }
37
38 pub const fn zero() -> Timespec {
39 unsafe { Self::new_unchecked(0, 0) }
40 }
41
42 pub const fn new(tv_sec: i64, tv_nsec: i64) -> Result<Timespec, io::Error> {
43 #[cfg(target_vendor = "apple")]
56 let (tv_sec, tv_nsec) =
57 if (tv_sec <= 0 && tv_sec > i64::MIN) && (tv_nsec < 0 && tv_nsec > -1_000_000_000) {
58 (tv_sec - 1, tv_nsec + 1_000_000_000)
59 } else {
60 (tv_sec, tv_nsec)
61 };
62 if tv_nsec >= 0 && tv_nsec < NSEC_PER_SEC as i64 {
63 Ok(unsafe { Self::new_unchecked(tv_sec, tv_nsec) })
64 } else {
65 Err(io::const_error!(io::ErrorKind::InvalidData, "invalid timestamp"))
66 }
67 }
68
69 pub fn now(clock: libc::clockid_t) -> Timespec {
70 use crate::mem::MaybeUninit;
71 use crate::sys::cvt;
72
73 #[cfg(all(
75 target_os = "linux",
76 target_env = "gnu",
77 target_pointer_width = "32",
78 not(target_arch = "riscv32")
79 ))]
80 {
81 use crate::sys::weak::weak;
82
83 weak!(
86 fn __clock_gettime64(
87 clockid: libc::clockid_t,
88 tp: *mut __timespec64,
89 ) -> libc::c_int;
90 );
91
92 if let Some(clock_gettime64) = __clock_gettime64.get() {
93 let mut t = MaybeUninit::uninit();
94 cvt(unsafe { clock_gettime64(clock, t.as_mut_ptr()) }).unwrap();
95 let t = unsafe { t.assume_init() };
96 return Timespec::new(t.tv_sec as i64, t.tv_nsec as i64).unwrap();
97 }
98 }
99
100 let mut t = MaybeUninit::uninit();
101 cvt(unsafe { libc::clock_gettime(clock, t.as_mut_ptr()) }).unwrap();
102 let t = unsafe { t.assume_init() };
103 Timespec::new(t.tv_sec as i64, t.tv_nsec as i64).unwrap()
104 }
105
106 pub fn sub_timespec(&self, other: &Timespec) -> Result<Duration, Duration> {
107 fn sub_ge_to_unsigned(a: i64, b: i64) -> u64 {
109 debug_assert!(a >= b);
110 a.wrapping_sub(b).cast_unsigned()
111 }
112
113 if self >= other {
114 let (secs, nsec) = if self.tv_nsec.as_inner() >= other.tv_nsec.as_inner() {
115 (
116 sub_ge_to_unsigned(self.tv_sec, other.tv_sec),
117 self.tv_nsec.as_inner() - other.tv_nsec.as_inner(),
118 )
119 } else {
120 debug_assert!(self.tv_nsec < other.tv_nsec);
122 debug_assert!(self.tv_sec > other.tv_sec);
123 debug_assert!(self.tv_sec > i64::MIN);
124 (
125 sub_ge_to_unsigned(self.tv_sec - 1, other.tv_sec),
126 self.tv_nsec.as_inner() + (NSEC_PER_SEC as u32) - other.tv_nsec.as_inner(),
127 )
128 };
129
130 Ok(Duration::new(secs, nsec))
131 } else {
132 match other.sub_timespec(self) {
133 Ok(d) => Err(d),
134 Err(d) => Ok(d),
135 }
136 }
137 }
138
139 pub fn checked_add_duration(&self, other: &Duration) -> Option<Timespec> {
140 let mut secs = self.tv_sec.checked_add_unsigned(other.as_secs())?;
141
142 let mut nsec = other.subsec_nanos() + self.tv_nsec.as_inner();
145 if nsec >= NSEC_PER_SEC as u32 {
146 nsec -= NSEC_PER_SEC as u32;
147 secs = secs.checked_add(1)?;
148 }
149 Some(unsafe { Timespec::new_unchecked(secs, nsec.into()) })
150 }
151
152 pub fn checked_sub_duration(&self, other: &Duration) -> Option<Timespec> {
153 let mut secs = self.tv_sec.checked_sub_unsigned(other.as_secs())?;
154
155 let mut nsec = self.tv_nsec.as_inner() as i32 - other.subsec_nanos() as i32;
157 if nsec < 0 {
158 nsec += NSEC_PER_SEC as i32;
159 secs = secs.checked_sub(1)?;
160 }
161 Some(unsafe { Timespec::new_unchecked(secs, nsec.into()) })
162 }
163
164 #[allow(dead_code)]
165 pub fn to_timespec(&self) -> Option<libc::timespec> {
166 Some(libc::timespec {
167 tv_sec: self.tv_sec.try_into().ok()?,
168 tv_nsec: self.tv_nsec.as_inner().try_into().ok()?,
169 })
170 }
171
172 #[cfg(target_os = "nto")]
175 pub(in crate::sys) fn to_timespec_capped(&self) -> Option<libc::timespec> {
176 if (self.tv_nsec.as_inner() as u64)
178 .checked_add((self.tv_sec as u64).checked_mul(NSEC_PER_SEC)?)
179 .is_none()
180 {
181 return None;
182 }
183 self.to_timespec()
184 }
185
186 #[cfg(all(
187 target_os = "linux",
188 target_env = "gnu",
189 target_pointer_width = "32",
190 not(target_arch = "riscv32")
191 ))]
192 pub fn to_timespec64(&self) -> __timespec64 {
193 __timespec64::new(self.tv_sec, self.tv_nsec.as_inner() as _)
194 }
195}
196
197#[cfg(all(
198 target_os = "linux",
199 target_env = "gnu",
200 target_pointer_width = "32",
201 not(target_arch = "riscv32")
202))]
203#[repr(C)]
204pub(crate) struct __timespec64 {
205 pub(crate) tv_sec: i64,
206 #[cfg(target_endian = "big")]
207 _padding: i32,
208 pub(crate) tv_nsec: i32,
209 #[cfg(target_endian = "little")]
210 _padding: i32,
211}
212
213#[cfg(all(
214 target_os = "linux",
215 target_env = "gnu",
216 target_pointer_width = "32",
217 not(target_arch = "riscv32")
218))]
219impl __timespec64 {
220 pub(crate) fn new(tv_sec: i64, tv_nsec: i32) -> Self {
221 Self { tv_sec, tv_nsec, _padding: 0 }
222 }
223}