Skip to main content

saturating_time/
internal.rs

1//! Internal parts used for sealing.
2//!
3//! This module primarily consists of the internal [`SaturatingTime`] trait, an
4//! unstable abstraction used internally to implement the main logic behind
5//! this.
6//!
7//! Normal users should not be using this.
8
9use std::{
10    cmp,
11    sync::LazyLock,
12    time::{Duration, Instant, SystemTime},
13};
14
15/// The maximum value of [`SystemTime`] for this platform.
16static MAX_SYSTEM_TIME: LazyLock<SystemTime> = LazyLock::new(find_max);
17
18/// The minimum value of [`SystemTime`] for this platform.
19static MIN_SYSTEM_TIME: LazyLock<SystemTime> = LazyLock::new(find_min);
20
21/// The maximum value of [`Instant`] for this platform.
22static MAX_INSTANT: LazyLock<Instant> = LazyLock::new(find_max);
23
24/// The minimum value of [`Instant`] for this platform.
25static MIN_INSTANT: LazyLock<Instant> = LazyLock::new(find_min);
26
27/// An internal trait implementing the actual magic behind this.
28pub trait SaturatingTime: Sized + Copy + PartialEq {
29    /// Anchor method to obtain an instance of this type.
30    fn anchor() -> Self;
31
32    /// Returns the maximum value of this type.
33    fn max_value() -> Self;
34
35    /// Returns the minimum value of this type.
36    fn min_value() -> Self;
37
38    /// Performs a checked addition on this type.
39    fn checked_add(&self, duration: Duration) -> Option<Self>;
40
41    /// Performs a checked subtraction on this type.
42    fn checked_sub(&self, duration: Duration) -> Option<Self>;
43
44    /// Performs a checked time delta on this type.
45    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    /// DO NOT USE!
97    ///
98    /// Instead, override the top-level provided implementation with the already
99    /// existing [`Instant::saturating_duration_since()`].
100    fn checked_duration_since(&self, _earlier: Self) -> Option<Duration> {
101        unreachable!()
102    }
103}
104
105/// Finds the value for [`SaturatingTime::max_value()`].
106fn find_max<T: SaturatingTime>() -> T {
107    find_limit(T::checked_add)
108}
109
110/// Finds the value for [`SaturatingTime::min_value()`].
111fn find_min<T: SaturatingTime>() -> T {
112    find_limit(T::checked_sub)
113}
114
115/// Internal algorithm of [`find_max()`] and [`find_min()`].
116///
117/// It works by performing `f` with a very large [`Duration`] onto
118/// [`SaturatingTime::anchor()`] until this call returns [`None`], in which case
119/// this [`Duration`] gets halved.  This process is repeated until `f` returns
120/// [`None`] and the [`Duration`] has reached 1ns.
121///
122/// # Algorithm
123///
124/// 1. Set `step` to `INITIAL_STEP` and `res` to [`SaturatingTime::anchor()`].
125/// 2. Call `f(&res, step)`.
126///     1. If [`Some`], set `res` to the returned value and continue.
127///         * A [`Some`] that is equal to the previous value is considered as a
128///           [`None`] due to a long lived bug in the Rust standard library.
129///         * See Also: <https://github.com/rust-lang/rust/issues/149995>
130///     2. If [`None`] and `step == 1ns`, return `res`.
131///     3. Else, set `step` to `MAX{1ns, step / 2}` and continue.
132fn 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    // (1) Set step to INITIAL_STEP and res to T::anchor().
141    let mut step = INITIAL_STEP;
142    let mut res = T::anchor();
143
144    loop {
145        // (2) Call f().
146        let next = f(&res, step);
147        match next {
148            // We only consider a Some as a Some if the value actually changed.
149            Some(st) if st != res => {
150                // (2.1) If Some, set res to the returned value and continue.
151                res = st;
152            }
153            None | Some(_) => {
154                if step == ONE_NS {
155                    // (2.2) If None and step == 1ns, return res.
156                    return res;
157                } else {
158                    // (2.3) Else, set step to MAX{1ns, step / 2}.
159                    step = cmp::max(ONE_NS, step / 2);
160                }
161            }
162        }
163    }
164}
165
166#[cfg(test)]
167mod tests {
168    // @@ begin test lint list maintained by maint/add_warning @@
169    #![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)] // See arti#2571
181    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
182
183    use std::{
184        fmt::Debug,
185        ops::{Add, Sub},
186    };
187
188    use super::*;
189
190    /// Checks whether the minimum and maximum values are correct.
191    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    /// Verifies [`SystemTime::min_value()`] and [`SystemTime::max_value()`] are
229    /// correct.
230    #[test]
231    fn system_time_min_max() {
232        min_max::<SystemTime>();
233    }
234
235    /// Verifies [`Instant::min_value()`] and [`Instant::max_value()`] are
236    /// correct.
237    #[test]
238    fn instant_min_max() {
239        min_max::<Instant>();
240    }
241
242    /// Verifies [`SystemTime::min_value()`] and [`SystemTime::max_value()`] are
243    /// correct on Unix systems.
244    #[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    /// Verifies that [`Instant::min_value()`] and [`Instant::max_value()`] are
258    /// correct on Unix systems.
259    #[test]
260    #[cfg(target_family = "unix")]
261    fn instant_min_max_unix() {
262        // Using format is not nice but I cannot see a better way for now.
263        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}