Skip to main content

ntex_util/time/
types.rs

1use std::ops;
2
3/// A span of time in milliseconds, for timeouts.
4///
5/// The value is a `u32`, so the longest representable span is about 49 days.
6/// Arithmetic saturates instead of overflowing.
7#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
8pub struct Millis(pub u32);
9
10impl Millis {
11    /// Zero milliseconds value
12    pub const ZERO: Millis = Millis(0);
13
14    /// One second value
15    pub const ONE_SEC: Millis = Millis(1_000);
16
17    #[inline]
18    /// Converts seconds to milliseconds, saturating at [`u32::MAX`].
19    pub const fn from_secs(secs: u32) -> Millis {
20        Millis(secs.saturating_mul(1000))
21    }
22
23    #[inline]
24    /// Returns `true` if the duration is zero.
25    pub const fn is_zero(&self) -> bool {
26        self.0 == 0
27    }
28
29    #[inline]
30    /// Returns `true` if the duration is not zero.
31    pub const fn non_zero(self) -> bool {
32        self.0 != 0
33    }
34
35    /// Calls `f` if the duration is not zero.
36    #[inline]
37    pub fn map<F, R>(&self, f: F) -> Option<R>
38    where
39        F: FnOnce(Millis) -> R,
40    {
41        if self.0 == 0 { None } else { Some(f(*self)) }
42    }
43}
44
45impl Default for Millis {
46    #[inline]
47    fn default() -> Millis {
48        Millis::ZERO
49    }
50}
51
52impl ops::Add<Millis> for Millis {
53    type Output = Millis;
54
55    #[inline]
56    fn add(self, other: Millis) -> Millis {
57        Millis(self.0.saturating_add(other.0))
58    }
59}
60
61impl ops::Add<Seconds> for Millis {
62    type Output = Millis;
63
64    #[inline]
65    #[allow(clippy::suspicious_arithmetic_impl)]
66    fn add(self, other: Seconds) -> Millis {
67        Millis(
68            self.0
69                .saturating_add((u32::from(other.0)).saturating_mul(1000)),
70        )
71    }
72}
73
74impl ops::Add<std::time::Duration> for Millis {
75    type Output = Millis;
76
77    #[inline]
78    fn add(self, other: std::time::Duration) -> Millis {
79        self + Millis::from(other)
80    }
81}
82
83impl ops::Add<Millis> for std::time::Duration {
84    type Output = std::time::Duration;
85
86    #[inline]
87    fn add(self, other: Millis) -> std::time::Duration {
88        self + Self::from(other)
89    }
90}
91
92impl From<u32> for Millis {
93    #[inline]
94    fn from(s: u32) -> Millis {
95        Millis(s)
96    }
97}
98
99/// Converts a non-negative integer; negative values are invalid.
100///
101/// A negative value logs an error and becomes zero, which disables a
102/// timeout. Debug builds panic instead, so the mistake is caught early.
103impl From<i32> for Millis {
104    #[inline]
105    fn from(i: i32) -> Millis {
106        Millis(u32::try_from(i).unwrap_or_else(|_| negative("Millis", i)))
107    }
108}
109
110impl From<usize> for Millis {
111    #[inline]
112    fn from(s: usize) -> Millis {
113        Self(s.try_into().unwrap_or_else(|_| {
114            log::error!("Values is too large {s:?}");
115            u32::MAX
116        }))
117    }
118}
119
120impl From<Seconds> for Millis {
121    #[inline]
122    fn from(s: Seconds) -> Millis {
123        Millis((u32::from(s.0)).saturating_mul(1000))
124    }
125}
126
127/// Converts a duration, rounding any sub-millisecond part up.
128///
129/// Only `Duration::ZERO` becomes zero, so a positive duration never turns
130/// into a disabled timeout and a timer never fires early. Durations that do
131/// not fit saturate at [`u32::MAX`] milliseconds and log an error.
132impl From<std::time::Duration> for Millis {
133    #[inline]
134    fn from(d: std::time::Duration) -> Millis {
135        let millis = d.as_millis() + u128::from(!d.subsec_nanos().is_multiple_of(1_000_000));
136        Self(millis.try_into().unwrap_or_else(|_| {
137            log::error!("Duration is too large for Millis: {d:?}");
138            u32::MAX
139        }))
140    }
141}
142
143impl From<Millis> for std::time::Duration {
144    #[inline]
145    fn from(d: Millis) -> std::time::Duration {
146        std::time::Duration::from_millis(u64::from(d.0))
147    }
148}
149
150/// A span of time in whole seconds.
151///
152/// The value is a `u16`, so the longest representable span is about 18 hours.
153#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
154pub struct Seconds(pub u16);
155
156impl Seconds {
157    /// Zero seconds value
158    pub const ZERO: Seconds = Seconds(0);
159
160    /// One second value
161    pub const ONE: Seconds = Seconds(1);
162
163    #[inline]
164    /// Creates a duration of `secs` seconds.
165    pub const fn new(secs: u16) -> Seconds {
166        Seconds(secs)
167    }
168
169    #[inline]
170    /// Creates a duration of `secs` seconds, saturating at [`u16::MAX`].
171    pub const fn checked_new(secs: usize) -> Seconds {
172        let secs = if (u16::MAX as usize) < secs {
173            u16::MAX
174        } else {
175            secs as u16
176        };
177        Seconds(secs)
178    }
179
180    #[inline]
181    /// Returns `true` if the duration is zero.
182    pub const fn is_zero(self) -> bool {
183        self.0 == 0
184    }
185
186    #[inline]
187    /// Returns `true` if the duration is not zero.
188    pub const fn non_zero(self) -> bool {
189        self.0 != 0
190    }
191
192    #[inline]
193    /// Returns the number of seconds.
194    pub const fn seconds(self) -> u64 {
195        self.0 as u64
196    }
197
198    /// Calls `f` with the duration in milliseconds if it is not zero.
199    #[inline]
200    pub fn map<F, R>(&self, f: F) -> Option<R>
201    where
202        F: FnOnce(Millis) -> R,
203    {
204        if self.0 == 0 {
205            None
206        } else {
207            Some(f(Millis::from(*self)))
208        }
209    }
210}
211
212impl Default for Seconds {
213    #[inline]
214    fn default() -> Seconds {
215        Seconds::ZERO
216    }
217}
218
219impl ops::Add<Seconds> for Seconds {
220    type Output = Seconds;
221
222    #[inline]
223    fn add(self, other: Seconds) -> Seconds {
224        Seconds(self.0.saturating_add(other.0))
225    }
226}
227
228impl From<Seconds> for std::time::Duration {
229    #[inline]
230    fn from(d: Seconds) -> std::time::Duration {
231        std::time::Duration::from_secs(u64::from(d.0))
232    }
233}
234
235impl From<u16> for Seconds {
236    #[inline]
237    fn from(secs: u16) -> Seconds {
238        Self(secs)
239    }
240}
241
242/// Converts a non-negative integer, saturating at [`u16::MAX`].
243///
244/// A negative value logs an error and becomes zero, which disables a
245/// timeout. Debug builds panic instead, so the mistake is caught early.
246impl From<i32> for Seconds {
247    #[inline]
248    fn from(i: i32) -> Seconds {
249        Seconds(if i < 0 {
250            negative("Seconds", i)
251        } else {
252            (i as u32).min(u32::from(u16::MAX)) as u16
253        })
254    }
255}
256
257#[cold]
258#[track_caller]
259fn negative<T: Default>(kind: &str, val: i32) -> T {
260    log::error!("Negative {kind} value {val}, using zero");
261    debug_assert!(val >= 0, "Negative {kind} value {val}");
262    T::default()
263}
264
265impl From<usize> for Seconds {
266    #[inline]
267    fn from(secs: usize) -> Seconds {
268        Self(secs.try_into().unwrap_or_else(|_| {
269            log::error!("Seconds value is too large {secs:?}");
270            u16::MAX
271        }))
272    }
273}
274
275#[cfg(test)]
276mod tests {
277    use super::*;
278    use std::time::Duration;
279
280    /// STATEMENT: Time-unit arithmetic and conversions preserve units and saturate bounded values.
281    ///
282    /// HOW:
283    /// - Check millisecond, second, and duration conversions and addition, including overflow.
284    /// - Exercise negative and oversized inputs, defaults, and zero-aware mapping helpers.
285    #[test]
286    fn time_types() {
287        let m = Millis::default();
288        assert_eq!(m.0, 0);
289
290        let m = Millis::from(10u32);
291        assert_eq!(m.0, 10);
292
293        let m = Millis::from(10usize);
294        assert_eq!(m.0, 10);
295
296        let m = Millis(10) + Millis(20);
297        assert_eq!(m.0, 30);
298
299        let m = Millis(10) + Millis(u32::MAX);
300        assert_eq!(m.0, u32::MAX);
301
302        let m = Millis(10) + Seconds(1);
303        assert_eq!(m.0, 1010);
304
305        let m = Millis(u32::MAX) + Seconds(1);
306        assert_eq!(m.0, u32::MAX);
307
308        let m = Millis(10) + Duration::from_millis(100);
309        assert_eq!(m.0, 110);
310
311        let m = Duration::from_millis(100) + Millis(10);
312        assert_eq!(m, Duration::from_millis(110));
313
314        let m = Millis::from(Seconds(1));
315        assert_eq!(m.0, 1000);
316
317        let m = Millis::from(Duration::from_secs(1));
318        assert_eq!(m.0, 1000);
319
320        let m = Millis::from(Duration::from_secs(u64::MAX));
321        assert_eq!(m.0, u32::MAX);
322
323        let m = Millis::from_secs(1);
324        assert_eq!(m.0, 1000);
325        assert_eq!(Millis::from_secs(u32::MAX).0, u32::MAX);
326
327        let m = Millis(0);
328        assert_eq!(m.map(|m| m + Millis(1)), None);
329
330        let m = Millis(1);
331        assert_eq!(m.map(|m| m + Millis(1)), Some(Millis(2)));
332
333        let s = Seconds::new(10);
334        assert_eq!(s.0, 10);
335
336        let s = Seconds::from(10u16);
337        assert_eq!(s.0, 10);
338
339        let s = Seconds::from(10usize);
340        assert_eq!(s.0, 10);
341
342        let s = Seconds::from(10i32);
343        assert_eq!(s.0, 10);
344        assert_eq!(Seconds::from(i32::MAX).0, u16::MAX);
345
346        let s = Seconds::checked_new(10);
347        assert_eq!(s.0, 10);
348
349        let s = Seconds::checked_new(u16::MAX as usize + 10);
350        assert_eq!(s.0, u16::MAX);
351
352        assert!(Seconds::ZERO.is_zero());
353        assert!(!Seconds::ZERO.non_zero());
354
355        let s = Seconds::new(10);
356        assert_eq!(s.seconds(), 10);
357
358        let s = Seconds::default();
359        assert_eq!(s.0, 0);
360
361        let s = Seconds::new(10) + Seconds::new(10);
362        assert_eq!(s.seconds(), 20);
363
364        assert_eq!(Seconds(0).map(|_| 1usize), None);
365        assert_eq!(Seconds(2).map(|_| 1usize), Some(1));
366
367        let d = Duration::from(Seconds(100));
368        assert_eq!(d.as_secs(), 100);
369    }
370
371    /// STATEMENT: Integer time conversions keep valid values and saturate oversized ones.
372    ///
373    /// HOW:
374    /// - Check zero predicates and conversions from zero, positive signed and pointer-sized integers.
375    /// - On 64-bit targets, verify maximum pointer-sized inputs saturate both time-unit types.
376    #[test]
377    fn time_types_conversions() {
378        assert!(Millis(1).non_zero());
379        assert!(!Millis::ZERO.non_zero());
380        assert_eq!(Millis::from(0i32), Millis::ZERO);
381        assert_eq!(Seconds::from(0i32), Seconds::ZERO);
382        assert_eq!(Millis::from(5i32), Millis(5));
383        assert_eq!(Millis::from(i32::MAX), Millis(i32::MAX as u32));
384        assert_eq!(Millis::from(7usize), Millis(7));
385        assert_eq!(Seconds::from(7usize), Seconds(7));
386
387        #[cfg(target_pointer_width = "64")]
388        {
389            assert_eq!(Millis::from(usize::MAX), Millis(u32::MAX));
390            assert_eq!(Seconds::from(usize::MAX), Seconds(u16::MAX));
391        }
392    }
393
394    /// STATEMENT: Negative integers are rejected in debug builds and become zero in release builds.
395    ///
396    /// HOW:
397    /// - Convert `-1` and `i32::MIN` into `Millis` and `Seconds` under `catch_unwind`.
398    /// - With debug assertions expect a panic; without them expect `ZERO`.
399    #[test]
400    fn negative_integer_conversions() {
401        fn check<T: PartialEq + std::fmt::Debug>(f: impl FnOnce() -> T, zero: &T) {
402            let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
403            if cfg!(debug_assertions) {
404                assert!(res.is_err());
405            } else {
406                assert_eq!(&res.unwrap(), zero);
407            }
408        }
409        for val in [-1, i32::MIN] {
410            check(|| Millis::from(val), &Millis::ZERO);
411            check(|| Seconds::from(val), &Seconds::ZERO);
412        }
413    }
414
415    /// STATEMENT: `Duration` conversion rounds positive sub-millisecond parts up so only zero disables a timeout.
416    ///
417    /// HOW:
418    /// - Convert zero, 1 ns, 500 us, exact 1 ms and 1 s, 1.5 ms, and 1 ms + 1 ns, and compare the milliseconds.
419    /// - Check that values at and just above `u32::MAX` milliseconds saturate.
420    #[test]
421    fn duration_conversion_rounds_up() {
422        assert_eq!(Millis::from(Duration::ZERO), Millis::ZERO);
423        assert_eq!(Millis::from(Duration::from_nanos(1)), Millis(1));
424        assert_eq!(Millis::from(Duration::from_micros(500)), Millis(1));
425        assert_eq!(Millis::from(Duration::from_millis(1)), Millis(1));
426        assert_eq!(Millis::from(Duration::from_secs(1)), Millis(1_000));
427        assert_eq!(Millis::from(Duration::from_micros(1_500)), Millis(2));
428        assert_eq!(Millis::from(Duration::from_nanos(1_000_001)), Millis(2));
429
430        let max = Duration::from_millis(u64::from(u32::MAX));
431        assert_eq!(Millis::from(max), Millis(u32::MAX));
432        assert_eq!(
433            Millis::from(max + Duration::from_nanos(1)),
434            Millis(u32::MAX)
435        );
436    }
437}