saturating_time/
internal.rs1use std::{
10 cmp,
11 sync::LazyLock,
12 time::{Duration, Instant, SystemTime},
13};
14
15static MAX_SYSTEM_TIME: LazyLock<SystemTime> = LazyLock::new(find_max);
17
18static MIN_SYSTEM_TIME: LazyLock<SystemTime> = LazyLock::new(find_min);
20
21static MAX_INSTANT: LazyLock<Instant> = LazyLock::new(find_max);
23
24static MIN_INSTANT: LazyLock<Instant> = LazyLock::new(find_min);
26
27pub trait SaturatingTime: Sized + Copy + PartialEq {
29 fn anchor() -> Self;
31
32 fn max_value() -> Self;
34
35 fn min_value() -> Self;
37
38 fn checked_add(&self, duration: Duration) -> Option<Self>;
40
41 fn checked_sub(&self, duration: Duration) -> Option<Self>;
43
44 fn checked_duration_since(&self, earlier: Self) -> Option<Duration>;
46}
47
48impl SaturatingTime for SystemTime {
49 fn anchor() -> Self {
50 Self::UNIX_EPOCH
51 }
52
53 fn max_value() -> Self {
54 *MAX_SYSTEM_TIME
55 }
56
57 fn min_value() -> Self {
58 *MIN_SYSTEM_TIME
59 }
60
61 fn checked_add(&self, duration: Duration) -> Option<Self> {
62 Self::checked_add(self, duration)
63 }
64
65 fn checked_sub(&self, duration: Duration) -> Option<Self> {
66 Self::checked_sub(self, duration)
67 }
68
69 fn checked_duration_since(&self, earlier: Self) -> Option<Duration> {
70 Self::duration_since(self, earlier).ok()
71 }
72}
73
74impl SaturatingTime for Instant {
75 fn anchor() -> Self {
76 use web_time_compat::InstantExt;
77 Self::get()
78 }
79
80 fn max_value() -> Self {
81 *MAX_INSTANT
82 }
83
84 fn min_value() -> Self {
85 *MIN_INSTANT
86 }
87
88 fn checked_add(&self, duration: Duration) -> Option<Self> {
89 Self::checked_add(self, duration)
90 }
91
92 fn checked_sub(&self, duration: Duration) -> Option<Self> {
93 Self::checked_sub(self, duration)
94 }
95
96 fn checked_duration_since(&self, _earlier: Self) -> Option<Duration> {
101 unreachable!()
102 }
103}
104
105fn find_max<T: SaturatingTime>() -> T {
107 find_limit(T::checked_add)
108}
109
110fn find_min<T: SaturatingTime>() -> T {
112 find_limit(T::checked_sub)
113}
114
115fn find_limit<T, F>(f: F) -> T
133where
134 T: SaturatingTime,
135 F: Fn(&T, Duration) -> Option<T>,
136{
137 const INITIAL_STEP: Duration = Duration::new(1_000_000_000_000_000_000, 0);
138 const ONE_NS: Duration = Duration::new(0, 1);
139
140 let mut step = INITIAL_STEP;
142 let mut res = T::anchor();
143
144 loop {
145 let next = f(&res, step);
147 match next {
148 Some(st) if st != res => {
150 res = st;
152 }
153 None | Some(_) => {
154 if step == ONE_NS {
155 return res;
157 } else {
158 step = cmp::max(ONE_NS, step / 2);
160 }
161 }
162 }
163 }
164}
165
166#[cfg(test)]
167mod tests {
168 #![allow(clippy::bool_assert_comparison)]
170 #![allow(clippy::clone_on_copy)]
171 #![allow(clippy::dbg_macro)]
172 #![allow(clippy::mixed_attributes_style)]
173 #![allow(clippy::print_stderr)]
174 #![allow(clippy::print_stdout)]
175 #![allow(clippy::single_char_pattern)]
176 #![allow(clippy::unwrap_used)]
177 #![allow(clippy::unchecked_time_subtraction)]
178 #![allow(clippy::useless_vec)]
179 #![allow(clippy::needless_pass_by_value)]
180 #![allow(clippy::string_slice)] use std::{
184 fmt::Debug,
185 ops::{Add, Sub},
186 };
187
188 use super::*;
189
190 fn min_max<T>()
192 where
193 T: SaturatingTime
194 + PartialEq
195 + Debug
196 + Add<Duration, Output = T>
197 + Sub<Duration, Output = T>,
198 {
199 assert_eq!(
200 T::max_value().checked_add(Duration::ZERO),
201 Some(T::max_value())
202 );
203 assert_eq!(T::max_value().checked_add(Duration::new(0, 1)), None);
204 assert_eq!(
205 T::max_value().checked_sub(Duration::ZERO),
206 Some(T::max_value())
207 );
208 assert_eq!(
209 T::max_value().checked_sub(Duration::new(0, 1)),
210 Some(T::max_value() - Duration::new(0, 1))
211 );
212
213 assert_eq!(
214 T::min_value().checked_sub(Duration::ZERO),
215 Some(T::min_value())
216 );
217 assert_eq!(T::min_value().checked_sub(Duration::new(0, 1)), None);
218 assert_eq!(
219 T::min_value().checked_add(Duration::ZERO),
220 Some(T::min_value())
221 );
222 assert_eq!(
223 T::min_value().checked_add(Duration::new(0, 1)),
224 Some(T::min_value() + Duration::new(0, 1))
225 );
226 }
227
228 #[test]
231 fn system_time_min_max() {
232 min_max::<SystemTime>();
233 }
234
235 #[test]
238 fn instant_min_max() {
239 min_max::<Instant>();
240 }
241
242 #[cfg(target_family = "unix")]
245 #[test]
246 fn system_time_min_max_unix() {
247 assert_eq!(
248 SystemTime::max_value(),
249 SystemTime::UNIX_EPOCH + Duration::new(i64::MAX as u64, 999_999_999)
250 );
251 assert_eq!(
252 SystemTime::min_value(),
253 SystemTime::UNIX_EPOCH - Duration::new(i64::MAX as u64 + 1, 0)
254 );
255 }
256
257 #[test]
260 #[cfg(target_family = "unix")]
261 fn instant_min_max_unix() {
262 assert_eq!(
264 format!("{:?}", Instant::max_value()),
265 format!(
266 "Instant {{ tv_sec: {}, tv_nsec: {} }}",
267 i64::MAX,
268 999_999_999
269 )
270 );
271
272 assert_eq!(
273 format!("{:?}", Instant::min_value()),
274 format!("Instant {{ tv_sec: {}, tv_nsec: {} }}", i64::MIN, 0)
275 );
276 }
277}