ntex-util 4.9.0

Utilities for ntex framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
use std::ops;

/// A span of time in milliseconds, for timeouts.
///
/// The value is a `u32`, so the longest representable span is about 49 days.
/// Arithmetic saturates instead of overflowing.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Millis(pub u32);

impl Millis {
    /// Zero milliseconds value
    pub const ZERO: Millis = Millis(0);

    /// One second value
    pub const ONE_SEC: Millis = Millis(1_000);

    #[inline]
    /// Converts seconds to milliseconds, saturating at [`u32::MAX`].
    pub const fn from_secs(secs: u32) -> Millis {
        Millis(secs.saturating_mul(1000))
    }

    #[inline]
    /// Returns `true` if the duration is zero.
    pub const fn is_zero(&self) -> bool {
        self.0 == 0
    }

    #[inline]
    /// Returns `true` if the duration is not zero.
    pub const fn non_zero(self) -> bool {
        self.0 != 0
    }

    /// Calls `f` if the duration is not zero.
    #[inline]
    pub fn map<F, R>(&self, f: F) -> Option<R>
    where
        F: FnOnce(Millis) -> R,
    {
        if self.0 == 0 { None } else { Some(f(*self)) }
    }
}

impl Default for Millis {
    #[inline]
    fn default() -> Millis {
        Millis::ZERO
    }
}

impl ops::Add<Millis> for Millis {
    type Output = Millis;

    #[inline]
    fn add(self, other: Millis) -> Millis {
        Millis(self.0.saturating_add(other.0))
    }
}

impl ops::Add<Seconds> for Millis {
    type Output = Millis;

    #[inline]
    #[allow(clippy::suspicious_arithmetic_impl)]
    fn add(self, other: Seconds) -> Millis {
        Millis(
            self.0
                .saturating_add((u32::from(other.0)).saturating_mul(1000)),
        )
    }
}

impl ops::Add<std::time::Duration> for Millis {
    type Output = Millis;

    #[inline]
    fn add(self, other: std::time::Duration) -> Millis {
        self + Millis::from(other)
    }
}

impl ops::Add<Millis> for std::time::Duration {
    type Output = std::time::Duration;

    #[inline]
    fn add(self, other: Millis) -> std::time::Duration {
        self + Self::from(other)
    }
}

impl From<u32> for Millis {
    #[inline]
    fn from(s: u32) -> Millis {
        Millis(s)
    }
}

/// Converts a non-negative integer; negative values are invalid.
///
/// A negative value logs an error and becomes zero, which disables a
/// timeout. Debug builds panic instead, so the mistake is caught early.
impl From<i32> for Millis {
    #[inline]
    fn from(i: i32) -> Millis {
        Millis(u32::try_from(i).unwrap_or_else(|_| negative("Millis", i)))
    }
}

impl From<usize> for Millis {
    #[inline]
    fn from(s: usize) -> Millis {
        Self(s.try_into().unwrap_or_else(|_| {
            log::error!("Values is too large {s:?}");
            u32::MAX
        }))
    }
}

impl From<Seconds> for Millis {
    #[inline]
    fn from(s: Seconds) -> Millis {
        Millis((u32::from(s.0)).saturating_mul(1000))
    }
}

/// Converts a duration, rounding any sub-millisecond part up.
///
/// Only `Duration::ZERO` becomes zero, so a positive duration never turns
/// into a disabled timeout and a timer never fires early. Durations that do
/// not fit saturate at [`u32::MAX`] milliseconds and log an error.
impl From<std::time::Duration> for Millis {
    #[inline]
    fn from(d: std::time::Duration) -> Millis {
        let millis = d.as_millis() + u128::from(!d.subsec_nanos().is_multiple_of(1_000_000));
        Self(millis.try_into().unwrap_or_else(|_| {
            log::error!("Duration is too large for Millis: {d:?}");
            u32::MAX
        }))
    }
}

impl From<Millis> for std::time::Duration {
    #[inline]
    fn from(d: Millis) -> std::time::Duration {
        std::time::Duration::from_millis(u64::from(d.0))
    }
}

/// A span of time in whole seconds.
///
/// The value is a `u16`, so the longest representable span is about 18 hours.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Seconds(pub u16);

impl Seconds {
    /// Zero seconds value
    pub const ZERO: Seconds = Seconds(0);

    /// One second value
    pub const ONE: Seconds = Seconds(1);

    #[inline]
    /// Creates a duration of `secs` seconds.
    pub const fn new(secs: u16) -> Seconds {
        Seconds(secs)
    }

    #[inline]
    /// Creates a duration of `secs` seconds, saturating at [`u16::MAX`].
    pub const fn checked_new(secs: usize) -> Seconds {
        let secs = if (u16::MAX as usize) < secs {
            u16::MAX
        } else {
            secs as u16
        };
        Seconds(secs)
    }

    #[inline]
    /// Returns `true` if the duration is zero.
    pub const fn is_zero(self) -> bool {
        self.0 == 0
    }

    #[inline]
    /// Returns `true` if the duration is not zero.
    pub const fn non_zero(self) -> bool {
        self.0 != 0
    }

    #[inline]
    /// Returns the number of seconds.
    pub const fn seconds(self) -> u64 {
        self.0 as u64
    }

    /// Calls `f` with the duration in milliseconds if it is not zero.
    #[inline]
    pub fn map<F, R>(&self, f: F) -> Option<R>
    where
        F: FnOnce(Millis) -> R,
    {
        if self.0 == 0 {
            None
        } else {
            Some(f(Millis::from(*self)))
        }
    }
}

impl Default for Seconds {
    #[inline]
    fn default() -> Seconds {
        Seconds::ZERO
    }
}

impl ops::Add<Seconds> for Seconds {
    type Output = Seconds;

    #[inline]
    fn add(self, other: Seconds) -> Seconds {
        Seconds(self.0.saturating_add(other.0))
    }
}

impl From<Seconds> for std::time::Duration {
    #[inline]
    fn from(d: Seconds) -> std::time::Duration {
        std::time::Duration::from_secs(u64::from(d.0))
    }
}

impl From<u16> for Seconds {
    #[inline]
    fn from(secs: u16) -> Seconds {
        Self(secs)
    }
}

/// Converts a non-negative integer, saturating at [`u16::MAX`].
///
/// A negative value logs an error and becomes zero, which disables a
/// timeout. Debug builds panic instead, so the mistake is caught early.
impl From<i32> for Seconds {
    #[inline]
    fn from(i: i32) -> Seconds {
        Seconds(if i < 0 {
            negative("Seconds", i)
        } else {
            (i as u32).min(u32::from(u16::MAX)) as u16
        })
    }
}

#[cold]
#[track_caller]
fn negative<T: Default>(kind: &str, val: i32) -> T {
    log::error!("Negative {kind} value {val}, using zero");
    debug_assert!(val >= 0, "Negative {kind} value {val}");
    T::default()
}

impl From<usize> for Seconds {
    #[inline]
    fn from(secs: usize) -> Seconds {
        Self(secs.try_into().unwrap_or_else(|_| {
            log::error!("Seconds value is too large {secs:?}");
            u16::MAX
        }))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    /// STATEMENT: Time-unit arithmetic and conversions preserve units and saturate bounded values.
    ///
    /// HOW:
    /// - Check millisecond, second, and duration conversions and addition, including overflow.
    /// - Exercise negative and oversized inputs, defaults, and zero-aware mapping helpers.
    #[test]
    fn time_types() {
        let m = Millis::default();
        assert_eq!(m.0, 0);

        let m = Millis::from(10u32);
        assert_eq!(m.0, 10);

        let m = Millis::from(10usize);
        assert_eq!(m.0, 10);

        let m = Millis(10) + Millis(20);
        assert_eq!(m.0, 30);

        let m = Millis(10) + Millis(u32::MAX);
        assert_eq!(m.0, u32::MAX);

        let m = Millis(10) + Seconds(1);
        assert_eq!(m.0, 1010);

        let m = Millis(u32::MAX) + Seconds(1);
        assert_eq!(m.0, u32::MAX);

        let m = Millis(10) + Duration::from_millis(100);
        assert_eq!(m.0, 110);

        let m = Duration::from_millis(100) + Millis(10);
        assert_eq!(m, Duration::from_millis(110));

        let m = Millis::from(Seconds(1));
        assert_eq!(m.0, 1000);

        let m = Millis::from(Duration::from_secs(1));
        assert_eq!(m.0, 1000);

        let m = Millis::from(Duration::from_secs(u64::MAX));
        assert_eq!(m.0, u32::MAX);

        let m = Millis::from_secs(1);
        assert_eq!(m.0, 1000);
        assert_eq!(Millis::from_secs(u32::MAX).0, u32::MAX);

        let m = Millis(0);
        assert_eq!(m.map(|m| m + Millis(1)), None);

        let m = Millis(1);
        assert_eq!(m.map(|m| m + Millis(1)), Some(Millis(2)));

        let s = Seconds::new(10);
        assert_eq!(s.0, 10);

        let s = Seconds::from(10u16);
        assert_eq!(s.0, 10);

        let s = Seconds::from(10usize);
        assert_eq!(s.0, 10);

        let s = Seconds::from(10i32);
        assert_eq!(s.0, 10);
        assert_eq!(Seconds::from(i32::MAX).0, u16::MAX);

        let s = Seconds::checked_new(10);
        assert_eq!(s.0, 10);

        let s = Seconds::checked_new(u16::MAX as usize + 10);
        assert_eq!(s.0, u16::MAX);

        assert!(Seconds::ZERO.is_zero());
        assert!(!Seconds::ZERO.non_zero());

        let s = Seconds::new(10);
        assert_eq!(s.seconds(), 10);

        let s = Seconds::default();
        assert_eq!(s.0, 0);

        let s = Seconds::new(10) + Seconds::new(10);
        assert_eq!(s.seconds(), 20);

        assert_eq!(Seconds(0).map(|_| 1usize), None);
        assert_eq!(Seconds(2).map(|_| 1usize), Some(1));

        let d = Duration::from(Seconds(100));
        assert_eq!(d.as_secs(), 100);
    }

    /// STATEMENT: Integer time conversions keep valid values and saturate oversized ones.
    ///
    /// HOW:
    /// - Check zero predicates and conversions from zero, positive signed and pointer-sized integers.
    /// - On 64-bit targets, verify maximum pointer-sized inputs saturate both time-unit types.
    #[test]
    fn time_types_conversions() {
        assert!(Millis(1).non_zero());
        assert!(!Millis::ZERO.non_zero());
        assert_eq!(Millis::from(0i32), Millis::ZERO);
        assert_eq!(Seconds::from(0i32), Seconds::ZERO);
        assert_eq!(Millis::from(5i32), Millis(5));
        assert_eq!(Millis::from(i32::MAX), Millis(i32::MAX as u32));
        assert_eq!(Millis::from(7usize), Millis(7));
        assert_eq!(Seconds::from(7usize), Seconds(7));

        #[cfg(target_pointer_width = "64")]
        {
            assert_eq!(Millis::from(usize::MAX), Millis(u32::MAX));
            assert_eq!(Seconds::from(usize::MAX), Seconds(u16::MAX));
        }
    }

    /// STATEMENT: Negative integers are rejected in debug builds and become zero in release builds.
    ///
    /// HOW:
    /// - Convert `-1` and `i32::MIN` into `Millis` and `Seconds` under `catch_unwind`.
    /// - With debug assertions expect a panic; without them expect `ZERO`.
    #[test]
    fn negative_integer_conversions() {
        fn check<T: PartialEq + std::fmt::Debug>(f: impl FnOnce() -> T, zero: &T) {
            let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
            if cfg!(debug_assertions) {
                assert!(res.is_err());
            } else {
                assert_eq!(&res.unwrap(), zero);
            }
        }
        for val in [-1, i32::MIN] {
            check(|| Millis::from(val), &Millis::ZERO);
            check(|| Seconds::from(val), &Seconds::ZERO);
        }
    }

    /// STATEMENT: `Duration` conversion rounds positive sub-millisecond parts up so only zero disables a timeout.
    ///
    /// HOW:
    /// - Convert zero, 1 ns, 500 us, exact 1 ms and 1 s, 1.5 ms, and 1 ms + 1 ns, and compare the milliseconds.
    /// - Check that values at and just above `u32::MAX` milliseconds saturate.
    #[test]
    fn duration_conversion_rounds_up() {
        assert_eq!(Millis::from(Duration::ZERO), Millis::ZERO);
        assert_eq!(Millis::from(Duration::from_nanos(1)), Millis(1));
        assert_eq!(Millis::from(Duration::from_micros(500)), Millis(1));
        assert_eq!(Millis::from(Duration::from_millis(1)), Millis(1));
        assert_eq!(Millis::from(Duration::from_secs(1)), Millis(1_000));
        assert_eq!(Millis::from(Duration::from_micros(1_500)), Millis(2));
        assert_eq!(Millis::from(Duration::from_nanos(1_000_001)), Millis(2));

        let max = Duration::from_millis(u64::from(u32::MAX));
        assert_eq!(Millis::from(max), Millis(u32::MAX));
        assert_eq!(
            Millis::from(max + Duration::from_nanos(1)),
            Millis(u32::MAX)
        );
    }
}