Coverage Report

Created: 2024-05-20 06:38

/rust/registry/src/index.crates.io-6f17d22bba15001f/time-0.3.14/src/duration.rs
Line
Count
Source (jump to first uncovered line)
1
//! The [`Duration`] struct and its associated `impl`s.
2
3
use core::cmp::Ordering;
4
use core::fmt;
5
use core::iter::Sum;
6
use core::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign};
7
use core::time::Duration as StdDuration;
8
9
use crate::error;
10
#[cfg(feature = "std")]
11
use crate::Instant;
12
13
/// By explicitly inserting this enum where padding is expected, the compiler is able to better
14
/// perform niche value optimization.
15
#[repr(u32)]
16
0
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
17
pub(crate) enum Padding {
18
    #[allow(clippy::missing_docs_in_private_items)]
19
    Optimize,
20
}
21
22
impl Default for Padding {
23
0
    fn default() -> Self {
24
0
        Self::Optimize
25
0
    }
26
}
27
28
/// A span of time with nanosecond precision.
29
///
30
/// Each `Duration` is composed of a whole number of seconds and a fractional part represented in
31
/// nanoseconds.
32
///
33
/// This implementation allows for negative durations, unlike [`core::time::Duration`].
34
0
#[derive(Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
35
pub struct Duration {
36
    /// Number of whole seconds.
37
    seconds: i64,
38
    /// Number of nanoseconds within the second. The sign always matches the `seconds` field.
39
    nanoseconds: i32, // always -10^9 < nanoseconds < 10^9
40
    #[allow(clippy::missing_docs_in_private_items)]
41
    padding: Padding,
42
}
43
44
impl fmt::Debug for Duration {
45
0
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46
0
        f.debug_struct("Duration")
47
0
            .field("seconds", &self.seconds)
48
0
            .field("nanoseconds", &self.nanoseconds)
49
0
            .finish()
50
0
    }
51
}
52
53
impl Duration {
54
    // region: constants
55
    /// Equivalent to `0.seconds()`.
56
    ///
57
    /// ```rust
58
    /// # use time::{Duration, ext::NumericalDuration};
59
    /// assert_eq!(Duration::ZERO, 0.seconds());
60
    /// ```
61
    pub const ZERO: Self = Self::seconds(0);
62
63
    /// Equivalent to `1.nanoseconds()`.
64
    ///
65
    /// ```rust
66
    /// # use time::{Duration, ext::NumericalDuration};
67
    /// assert_eq!(Duration::NANOSECOND, 1.nanoseconds());
68
    /// ```
69
    pub const NANOSECOND: Self = Self::nanoseconds(1);
70
71
    /// Equivalent to `1.microseconds()`.
72
    ///
73
    /// ```rust
74
    /// # use time::{Duration, ext::NumericalDuration};
75
    /// assert_eq!(Duration::MICROSECOND, 1.microseconds());
76
    /// ```
77
    pub const MICROSECOND: Self = Self::microseconds(1);
78
79
    /// Equivalent to `1.milliseconds()`.
80
    ///
81
    /// ```rust
82
    /// # use time::{Duration, ext::NumericalDuration};
83
    /// assert_eq!(Duration::MILLISECOND, 1.milliseconds());
84
    /// ```
85
    pub const MILLISECOND: Self = Self::milliseconds(1);
86
87
    /// Equivalent to `1.seconds()`.
88
    ///
89
    /// ```rust
90
    /// # use time::{Duration, ext::NumericalDuration};
91
    /// assert_eq!(Duration::SECOND, 1.seconds());
92
    /// ```
93
    pub const SECOND: Self = Self::seconds(1);
94
95
    /// Equivalent to `1.minutes()`.
96
    ///
97
    /// ```rust
98
    /// # use time::{Duration, ext::NumericalDuration};
99
    /// assert_eq!(Duration::MINUTE, 1.minutes());
100
    /// ```
101
    pub const MINUTE: Self = Self::minutes(1);
102
103
    /// Equivalent to `1.hours()`.
104
    ///
105
    /// ```rust
106
    /// # use time::{Duration, ext::NumericalDuration};
107
    /// assert_eq!(Duration::HOUR, 1.hours());
108
    /// ```
109
    pub const HOUR: Self = Self::hours(1);
110
111
    /// Equivalent to `1.days()`.
112
    ///
113
    /// ```rust
114
    /// # use time::{Duration, ext::NumericalDuration};
115
    /// assert_eq!(Duration::DAY, 1.days());
116
    /// ```
117
    pub const DAY: Self = Self::days(1);
118
119
    /// Equivalent to `1.weeks()`.
120
    ///
121
    /// ```rust
122
    /// # use time::{Duration, ext::NumericalDuration};
123
    /// assert_eq!(Duration::WEEK, 1.weeks());
124
    /// ```
125
    pub const WEEK: Self = Self::weeks(1);
126
127
    /// The minimum possible duration. Adding any negative duration to this will cause an overflow.
128
    pub const MIN: Self = Self::new_unchecked(i64::MIN, -999_999_999);
129
130
    /// The maximum possible duration. Adding any positive duration to this will cause an overflow.
131
    pub const MAX: Self = Self::new_unchecked(i64::MAX, 999_999_999);
132
    // endregion constants
133
134
    // region: is_{sign}
135
    /// Check if a duration is exactly zero.
136
    ///
137
    /// ```rust
138
    /// # use time::ext::NumericalDuration;
139
    /// assert!(0.seconds().is_zero());
140
    /// assert!(!1.nanoseconds().is_zero());
141
    /// ```
142
0
    pub const fn is_zero(self) -> bool {
143
0
        self.seconds == 0 && self.nanoseconds == 0
144
0
    }
145
146
    /// Check if a duration is negative.
147
    ///
148
    /// ```rust
149
    /// # use time::ext::NumericalDuration;
150
    /// assert!((-1).seconds().is_negative());
151
    /// assert!(!0.seconds().is_negative());
152
    /// assert!(!1.seconds().is_negative());
153
    /// ```
154
0
    pub const fn is_negative(self) -> bool {
155
0
        self.seconds < 0 || self.nanoseconds < 0
156
0
    }
157
158
    /// Check if a duration is positive.
159
    ///
160
    /// ```rust
161
    /// # use time::ext::NumericalDuration;
162
    /// assert!(1.seconds().is_positive());
163
    /// assert!(!0.seconds().is_positive());
164
    /// assert!(!(-1).seconds().is_positive());
165
    /// ```
166
0
    pub const fn is_positive(self) -> bool {
167
0
        self.seconds > 0 || self.nanoseconds > 0
168
0
    }
169
    // endregion is_{sign}
170
171
    // region: abs
172
    /// Get the absolute value of the duration.
173
    ///
174
    /// This method saturates the returned value if it would otherwise overflow.
175
    ///
176
    /// ```rust
177
    /// # use time::ext::NumericalDuration;
178
    /// assert_eq!(1.seconds().abs(), 1.seconds());
179
    /// assert_eq!(0.seconds().abs(), 0.seconds());
180
    /// assert_eq!((-1).seconds().abs(), 1.seconds());
181
    /// ```
182
0
    pub const fn abs(self) -> Self {
183
0
        Self::new_unchecked(self.seconds.saturating_abs(), self.nanoseconds.abs())
184
0
    }
185
186
    /// Convert the existing `Duration` to a `std::time::Duration` and its sign. This returns a
187
    /// [`std::time::Duration`] and does not saturate the returned value (unlike [`Duration::abs`]).
188
    ///
189
    /// ```rust
190
    /// # use time::ext::{NumericalDuration, NumericalStdDuration};
191
    /// assert_eq!(1.seconds().unsigned_abs(), 1.std_seconds());
192
    /// assert_eq!(0.seconds().unsigned_abs(), 0.std_seconds());
193
    /// assert_eq!((-1).seconds().unsigned_abs(), 1.std_seconds());
194
    /// ```
195
0
    pub const fn unsigned_abs(self) -> StdDuration {
196
0
        StdDuration::new(self.seconds.unsigned_abs(), self.nanoseconds.unsigned_abs())
197
0
    }
198
    // endregion abs
199
200
    // region: constructors
201
    /// Create a new `Duration` without checking the validity of the components.
202
0
    pub(crate) const fn new_unchecked(seconds: i64, nanoseconds: i32) -> Self {
203
0
        if seconds < 0 {
204
0
            debug_assert!(nanoseconds <= 0);
205
0
            debug_assert!(nanoseconds > -1_000_000_000);
206
0
        } else if seconds > 0 {
207
0
            debug_assert!(nanoseconds >= 0);
208
0
            debug_assert!(nanoseconds < 1_000_000_000);
209
        } else {
210
0
            debug_assert!(nanoseconds.unsigned_abs() < 1_000_000_000);
211
        }
212
213
0
        Self {
214
0
            seconds,
215
0
            nanoseconds,
216
0
            padding: Padding::Optimize,
217
0
        }
218
0
    }
219
220
    /// Create a new `Duration` with the provided seconds and nanoseconds. If nanoseconds is at
221
    /// least ±10<sup>9</sup>, it will wrap to the number of seconds.
222
    ///
223
    /// ```rust
224
    /// # use time::{Duration, ext::NumericalDuration};
225
    /// assert_eq!(Duration::new(1, 0), 1.seconds());
226
    /// assert_eq!(Duration::new(-1, 0), (-1).seconds());
227
    /// assert_eq!(Duration::new(1, 2_000_000_000), 3.seconds());
228
    /// ```
229
0
    pub const fn new(mut seconds: i64, mut nanoseconds: i32) -> Self {
230
0
        seconds += nanoseconds as i64 / 1_000_000_000;
231
0
        nanoseconds %= 1_000_000_000;
232
0
233
0
        if seconds > 0 && nanoseconds < 0 {
234
0
            seconds -= 1;
235
0
            nanoseconds += 1_000_000_000;
236
0
        } else if seconds < 0 && nanoseconds > 0 {
237
0
            seconds += 1;
238
0
            nanoseconds -= 1_000_000_000;
239
0
        }
240
241
0
        Self::new_unchecked(seconds, nanoseconds)
242
0
    }
243
244
    /// Create a new `Duration` with the given number of weeks. Equivalent to
245
    /// `Duration::seconds(weeks * 604_800)`.
246
    ///
247
    /// ```rust
248
    /// # use time::{Duration, ext::NumericalDuration};
249
    /// assert_eq!(Duration::weeks(1), 604_800.seconds());
250
    /// ```
251
0
    pub const fn weeks(weeks: i64) -> Self {
252
0
        Self::seconds(weeks * 604_800)
253
0
    }
254
255
    /// Create a new `Duration` with the given number of days. Equivalent to
256
    /// `Duration::seconds(days * 86_400)`.
257
    ///
258
    /// ```rust
259
    /// # use time::{Duration, ext::NumericalDuration};
260
    /// assert_eq!(Duration::days(1), 86_400.seconds());
261
    /// ```
262
0
    pub const fn days(days: i64) -> Self {
263
0
        Self::seconds(days * 86_400)
264
0
    }
265
266
    /// Create a new `Duration` with the given number of hours. Equivalent to
267
    /// `Duration::seconds(hours * 3_600)`.
268
    ///
269
    /// ```rust
270
    /// # use time::{Duration, ext::NumericalDuration};
271
    /// assert_eq!(Duration::hours(1), 3_600.seconds());
272
    /// ```
273
0
    pub const fn hours(hours: i64) -> Self {
274
0
        Self::seconds(hours * 3_600)
275
0
    }
276
277
    /// Create a new `Duration` with the given number of minutes. Equivalent to
278
    /// `Duration::seconds(minutes * 60)`.
279
    ///
280
    /// ```rust
281
    /// # use time::{Duration, ext::NumericalDuration};
282
    /// assert_eq!(Duration::minutes(1), 60.seconds());
283
    /// ```
284
0
    pub const fn minutes(minutes: i64) -> Self {
285
0
        Self::seconds(minutes * 60)
286
0
    }
287
288
    /// Create a new `Duration` with the given number of seconds.
289
    ///
290
    /// ```rust
291
    /// # use time::{Duration, ext::NumericalDuration};
292
    /// assert_eq!(Duration::seconds(1), 1_000.milliseconds());
293
    /// ```
294
0
    pub const fn seconds(seconds: i64) -> Self {
295
0
        Self::new_unchecked(seconds, 0)
296
0
    }
297
298
    /// Creates a new `Duration` from the specified number of seconds represented as `f64`.
299
    ///
300
    /// ```rust
301
    /// # use time::{Duration, ext::NumericalDuration};
302
    /// assert_eq!(Duration::seconds_f64(0.5), 0.5.seconds());
303
    /// assert_eq!(Duration::seconds_f64(-0.5), -0.5.seconds());
304
    /// ```
305
0
    pub fn seconds_f64(seconds: f64) -> Self {
306
0
        Self::new_unchecked(seconds as _, ((seconds % 1.) * 1_000_000_000.) as _)
307
0
    }
308
309
    /// Creates a new `Duration` from the specified number of seconds represented as `f32`.
310
    ///
311
    /// ```rust
312
    /// # use time::{Duration, ext::NumericalDuration};
313
    /// assert_eq!(Duration::seconds_f32(0.5), 0.5.seconds());
314
    /// assert_eq!(Duration::seconds_f32(-0.5), (-0.5).seconds());
315
    /// ```
316
0
    pub fn seconds_f32(seconds: f32) -> Self {
317
0
        Self::new_unchecked(seconds as _, ((seconds % 1.) * 1_000_000_000.) as _)
318
0
    }
319
320
    /// Create a new `Duration` with the given number of milliseconds.
321
    ///
322
    /// ```rust
323
    /// # use time::{Duration, ext::NumericalDuration};
324
    /// assert_eq!(Duration::milliseconds(1), 1_000.microseconds());
325
    /// assert_eq!(Duration::milliseconds(-1), (-1_000).microseconds());
326
    /// ```
327
0
    pub const fn milliseconds(milliseconds: i64) -> Self {
328
0
        Self::new_unchecked(
329
0
            milliseconds / 1_000,
330
0
            ((milliseconds % 1_000) * 1_000_000) as _,
331
0
        )
332
0
    }
333
334
    /// Create a new `Duration` with the given number of microseconds.
335
    ///
336
    /// ```rust
337
    /// # use time::{Duration, ext::NumericalDuration};
338
    /// assert_eq!(Duration::microseconds(1), 1_000.nanoseconds());
339
    /// assert_eq!(Duration::microseconds(-1), (-1_000).nanoseconds());
340
    /// ```
341
0
    pub const fn microseconds(microseconds: i64) -> Self {
342
0
        Self::new_unchecked(
343
0
            microseconds / 1_000_000,
344
0
            ((microseconds % 1_000_000) * 1_000) as _,
345
0
        )
346
0
    }
347
348
    /// Create a new `Duration` with the given number of nanoseconds.
349
    ///
350
    /// ```rust
351
    /// # use time::{Duration, ext::NumericalDuration};
352
    /// assert_eq!(Duration::nanoseconds(1), 1.microseconds() / 1_000);
353
    /// assert_eq!(Duration::nanoseconds(-1), (-1).microseconds() / 1_000);
354
    /// ```
355
0
    pub const fn nanoseconds(nanoseconds: i64) -> Self {
356
0
        Self::new_unchecked(
357
0
            nanoseconds / 1_000_000_000,
358
0
            (nanoseconds % 1_000_000_000) as _,
359
0
        )
360
0
    }
361
362
    /// Create a new `Duration` with the given number of nanoseconds.
363
    ///
364
    /// As the input range cannot be fully mapped to the output, this should only be used where it's
365
    /// known to result in a valid value.
366
0
    pub(crate) const fn nanoseconds_i128(nanoseconds: i128) -> Self {
367
0
        Self::new_unchecked(
368
0
            (nanoseconds / 1_000_000_000) as _,
369
0
            (nanoseconds % 1_000_000_000) as _,
370
0
        )
371
0
    }
372
    // endregion constructors
373
374
    // region: getters
375
    /// Get the number of whole weeks in the duration.
376
    ///
377
    /// ```rust
378
    /// # use time::ext::NumericalDuration;
379
    /// assert_eq!(1.weeks().whole_weeks(), 1);
380
    /// assert_eq!((-1).weeks().whole_weeks(), -1);
381
    /// assert_eq!(6.days().whole_weeks(), 0);
382
    /// assert_eq!((-6).days().whole_weeks(), 0);
383
    /// ```
384
0
    pub const fn whole_weeks(self) -> i64 {
385
0
        self.whole_seconds() / 604_800
386
0
    }
387
388
    /// Get the number of whole days in the duration.
389
    ///
390
    /// ```rust
391
    /// # use time::ext::NumericalDuration;
392
    /// assert_eq!(1.days().whole_days(), 1);
393
    /// assert_eq!((-1).days().whole_days(), -1);
394
    /// assert_eq!(23.hours().whole_days(), 0);
395
    /// assert_eq!((-23).hours().whole_days(), 0);
396
    /// ```
397
0
    pub const fn whole_days(self) -> i64 {
398
0
        self.whole_seconds() / 86_400
399
0
    }
400
401
    /// Get the number of whole hours in the duration.
402
    ///
403
    /// ```rust
404
    /// # use time::ext::NumericalDuration;
405
    /// assert_eq!(1.hours().whole_hours(), 1);
406
    /// assert_eq!((-1).hours().whole_hours(), -1);
407
    /// assert_eq!(59.minutes().whole_hours(), 0);
408
    /// assert_eq!((-59).minutes().whole_hours(), 0);
409
    /// ```
410
0
    pub const fn whole_hours(self) -> i64 {
411
0
        self.whole_seconds() / 3_600
412
0
    }
413
414
    /// Get the number of whole minutes in the duration.
415
    ///
416
    /// ```rust
417
    /// # use time::ext::NumericalDuration;
418
    /// assert_eq!(1.minutes().whole_minutes(), 1);
419
    /// assert_eq!((-1).minutes().whole_minutes(), -1);
420
    /// assert_eq!(59.seconds().whole_minutes(), 0);
421
    /// assert_eq!((-59).seconds().whole_minutes(), 0);
422
    /// ```
423
0
    pub const fn whole_minutes(self) -> i64 {
424
0
        self.whole_seconds() / 60
425
0
    }
426
427
    /// Get the number of whole seconds in the duration.
428
    ///
429
    /// ```rust
430
    /// # use time::ext::NumericalDuration;
431
    /// assert_eq!(1.seconds().whole_seconds(), 1);
432
    /// assert_eq!((-1).seconds().whole_seconds(), -1);
433
    /// assert_eq!(1.minutes().whole_seconds(), 60);
434
    /// assert_eq!((-1).minutes().whole_seconds(), -60);
435
    /// ```
436
0
    pub const fn whole_seconds(self) -> i64 {
437
0
        self.seconds
438
0
    }
439
440
    /// Get the number of fractional seconds in the duration.
441
    ///
442
    /// ```rust
443
    /// # use time::ext::NumericalDuration;
444
    /// assert_eq!(1.5.seconds().as_seconds_f64(), 1.5);
445
    /// assert_eq!((-1.5).seconds().as_seconds_f64(), -1.5);
446
    /// ```
447
0
    pub fn as_seconds_f64(self) -> f64 {
448
0
        self.seconds as f64 + self.nanoseconds as f64 / 1_000_000_000.
449
0
    }
450
451
    /// Get the number of fractional seconds in the duration.
452
    ///
453
    /// ```rust
454
    /// # use time::ext::NumericalDuration;
455
    /// assert_eq!(1.5.seconds().as_seconds_f32(), 1.5);
456
    /// assert_eq!((-1.5).seconds().as_seconds_f32(), -1.5);
457
    /// ```
458
0
    pub fn as_seconds_f32(self) -> f32 {
459
0
        self.seconds as f32 + self.nanoseconds as f32 / 1_000_000_000.
460
0
    }
461
462
    /// Get the number of whole milliseconds in the duration.
463
    ///
464
    /// ```rust
465
    /// # use time::ext::NumericalDuration;
466
    /// assert_eq!(1.seconds().whole_milliseconds(), 1_000);
467
    /// assert_eq!((-1).seconds().whole_milliseconds(), -1_000);
468
    /// assert_eq!(1.milliseconds().whole_milliseconds(), 1);
469
    /// assert_eq!((-1).milliseconds().whole_milliseconds(), -1);
470
    /// ```
471
0
    pub const fn whole_milliseconds(self) -> i128 {
472
0
        self.seconds as i128 * 1_000 + self.nanoseconds as i128 / 1_000_000
473
0
    }
474
475
    /// Get the number of milliseconds past the number of whole seconds.
476
    ///
477
    /// Always in the range `-1_000..1_000`.
478
    ///
479
    /// ```rust
480
    /// # use time::ext::NumericalDuration;
481
    /// assert_eq!(1.4.seconds().subsec_milliseconds(), 400);
482
    /// assert_eq!((-1.4).seconds().subsec_milliseconds(), -400);
483
    /// ```
484
    // Allow the lint, as the value is guaranteed to be less than 1000.
485
0
    pub const fn subsec_milliseconds(self) -> i16 {
486
0
        (self.nanoseconds / 1_000_000) as _
487
0
    }
488
489
    /// Get the number of whole microseconds in the duration.
490
    ///
491
    /// ```rust
492
    /// # use time::ext::NumericalDuration;
493
    /// assert_eq!(1.milliseconds().whole_microseconds(), 1_000);
494
    /// assert_eq!((-1).milliseconds().whole_microseconds(), -1_000);
495
    /// assert_eq!(1.microseconds().whole_microseconds(), 1);
496
    /// assert_eq!((-1).microseconds().whole_microseconds(), -1);
497
    /// ```
498
0
    pub const fn whole_microseconds(self) -> i128 {
499
0
        self.seconds as i128 * 1_000_000 + self.nanoseconds as i128 / 1_000
500
0
    }
501
502
    /// Get the number of microseconds past the number of whole seconds.
503
    ///
504
    /// Always in the range `-1_000_000..1_000_000`.
505
    ///
506
    /// ```rust
507
    /// # use time::ext::NumericalDuration;
508
    /// assert_eq!(1.0004.seconds().subsec_microseconds(), 400);
509
    /// assert_eq!((-1.0004).seconds().subsec_microseconds(), -400);
510
    /// ```
511
0
    pub const fn subsec_microseconds(self) -> i32 {
512
0
        self.nanoseconds / 1_000
513
0
    }
514
515
    /// Get the number of nanoseconds in the duration.
516
    ///
517
    /// ```rust
518
    /// # use time::ext::NumericalDuration;
519
    /// assert_eq!(1.microseconds().whole_nanoseconds(), 1_000);
520
    /// assert_eq!((-1).microseconds().whole_nanoseconds(), -1_000);
521
    /// assert_eq!(1.nanoseconds().whole_nanoseconds(), 1);
522
    /// assert_eq!((-1).nanoseconds().whole_nanoseconds(), -1);
523
    /// ```
524
0
    pub const fn whole_nanoseconds(self) -> i128 {
525
0
        self.seconds as i128 * 1_000_000_000 + self.nanoseconds as i128
526
0
    }
527
528
    /// Get the number of nanoseconds past the number of whole seconds.
529
    ///
530
    /// The returned value will always be in the range `-1_000_000_000..1_000_000_000`.
531
    ///
532
    /// ```rust
533
    /// # use time::ext::NumericalDuration;
534
    /// assert_eq!(1.000_000_400.seconds().subsec_nanoseconds(), 400);
535
    /// assert_eq!((-1.000_000_400).seconds().subsec_nanoseconds(), -400);
536
    /// ```
537
0
    pub const fn subsec_nanoseconds(self) -> i32 {
538
0
        self.nanoseconds
539
0
    }
540
    // endregion getters
541
542
    // region: checked arithmetic
543
    /// Computes `self + rhs`, returning `None` if an overflow occurred.
544
    ///
545
    /// ```rust
546
    /// # use time::{Duration, ext::NumericalDuration};
547
    /// assert_eq!(5.seconds().checked_add(5.seconds()), Some(10.seconds()));
548
    /// assert_eq!(Duration::MAX.checked_add(1.nanoseconds()), None);
549
    /// assert_eq!((-5).seconds().checked_add(5.seconds()), Some(0.seconds()));
550
    /// ```
551
0
    pub const fn checked_add(self, rhs: Self) -> Option<Self> {
552
0
        let mut seconds = const_try_opt!(self.seconds.checked_add(rhs.seconds));
553
0
        let mut nanoseconds = self.nanoseconds + rhs.nanoseconds;
554
0
555
0
        if nanoseconds >= 1_000_000_000 || seconds < 0 && nanoseconds > 0 {
556
0
            nanoseconds -= 1_000_000_000;
557
0
            seconds = const_try_opt!(seconds.checked_add(1));
558
0
        } else if nanoseconds <= -1_000_000_000 || seconds > 0 && nanoseconds < 0 {
559
0
            nanoseconds += 1_000_000_000;
560
0
            seconds = const_try_opt!(seconds.checked_sub(1));
561
0
        }
562
563
0
        Some(Self::new_unchecked(seconds, nanoseconds))
564
0
    }
565
566
    /// Computes `self - rhs`, returning `None` if an overflow occurred.
567
    ///
568
    /// ```rust
569
    /// # use time::{Duration, ext::NumericalDuration};
570
    /// assert_eq!(5.seconds().checked_sub(5.seconds()), Some(Duration::ZERO));
571
    /// assert_eq!(Duration::MIN.checked_sub(1.nanoseconds()), None);
572
    /// assert_eq!(5.seconds().checked_sub(10.seconds()), Some((-5).seconds()));
573
    /// ```
574
0
    pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
575
0
        let mut seconds = const_try_opt!(self.seconds.checked_sub(rhs.seconds));
576
0
        let mut nanoseconds = self.nanoseconds - rhs.nanoseconds;
577
0
578
0
        if nanoseconds >= 1_000_000_000 || seconds < 0 && nanoseconds > 0 {
579
0
            nanoseconds -= 1_000_000_000;
580
0
            seconds = const_try_opt!(seconds.checked_add(1));
581
0
        } else if nanoseconds <= -1_000_000_000 || seconds > 0 && nanoseconds < 0 {
582
0
            nanoseconds += 1_000_000_000;
583
0
            seconds = const_try_opt!(seconds.checked_sub(1));
584
0
        }
585
586
0
        Some(Self::new_unchecked(seconds, nanoseconds))
587
0
    }
588
589
    /// Computes `self * rhs`, returning `None` if an overflow occurred.
590
    ///
591
    /// ```rust
592
    /// # use time::{Duration, ext::NumericalDuration};
593
    /// assert_eq!(5.seconds().checked_mul(2), Some(10.seconds()));
594
    /// assert_eq!(5.seconds().checked_mul(-2), Some((-10).seconds()));
595
    /// assert_eq!(5.seconds().checked_mul(0), Some(0.seconds()));
596
    /// assert_eq!(Duration::MAX.checked_mul(2), None);
597
    /// assert_eq!(Duration::MIN.checked_mul(2), None);
598
    /// ```
599
0
    pub const fn checked_mul(self, rhs: i32) -> Option<Self> {
600
0
        // Multiply nanoseconds as i64, because it cannot overflow that way.
601
0
        let total_nanos = self.nanoseconds as i64 * rhs as i64;
602
0
        let extra_secs = total_nanos / 1_000_000_000;
603
0
        let nanoseconds = (total_nanos % 1_000_000_000) as _;
604
0
        let seconds = const_try_opt!(
605
0
            const_try_opt!(self.seconds.checked_mul(rhs as _)).checked_add(extra_secs)
606
        );
607
608
0
        Some(Self::new_unchecked(seconds, nanoseconds))
609
0
    }
610
611
    /// Computes `self / rhs`, returning `None` if `rhs == 0` or if the result would overflow.
612
    ///
613
    /// ```rust
614
    /// # use time::ext::NumericalDuration;
615
    /// assert_eq!(10.seconds().checked_div(2), Some(5.seconds()));
616
    /// assert_eq!(10.seconds().checked_div(-2), Some((-5).seconds()));
617
    /// assert_eq!(1.seconds().checked_div(0), None);
618
    /// ```
619
0
    pub const fn checked_div(self, rhs: i32) -> Option<Self> {
620
0
        let seconds = const_try_opt!(self.seconds.checked_div(rhs as i64));
621
0
        let carry = self.seconds - seconds * (rhs as i64);
622
0
        let extra_nanos = const_try_opt!((carry * 1_000_000_000).checked_div(rhs as i64));
623
0
        let nanoseconds = const_try_opt!(self.nanoseconds.checked_div(rhs)) + (extra_nanos as i32);
624
0
625
0
        Some(Self::new_unchecked(seconds, nanoseconds))
626
0
    }
627
    // endregion checked arithmetic
628
629
    // region: saturating arithmetic
630
    /// Computes `self + rhs`, saturating if an overflow occurred.
631
    ///
632
    /// ```rust
633
    /// # use time::{Duration, ext::NumericalDuration};
634
    /// assert_eq!(5.seconds().saturating_add(5.seconds()), 10.seconds());
635
    /// assert_eq!(Duration::MAX.saturating_add(1.nanoseconds()), Duration::MAX);
636
    /// assert_eq!(
637
    ///     Duration::MIN.saturating_add((-1).nanoseconds()),
638
    ///     Duration::MIN
639
    /// );
640
    /// assert_eq!((-5).seconds().saturating_add(5.seconds()), Duration::ZERO);
641
    /// ```
642
0
    pub const fn saturating_add(self, rhs: Self) -> Self {
643
0
        let (mut seconds, overflow) = self.seconds.overflowing_add(rhs.seconds);
644
0
        if overflow {
645
0
            if self.seconds > 0 {
646
0
                return Self::MAX;
647
0
            }
648
0
            return Self::MIN;
649
0
        }
650
0
        let mut nanoseconds = self.nanoseconds + rhs.nanoseconds;
651
0
652
0
        if nanoseconds >= 1_000_000_000 || seconds < 0 && nanoseconds > 0 {
653
0
            nanoseconds -= 1_000_000_000;
654
0
            seconds = match seconds.checked_add(1) {
655
0
                Some(seconds) => seconds,
656
0
                None => return Self::MAX,
657
            };
658
0
        } else if nanoseconds <= -1_000_000_000 || seconds > 0 && nanoseconds < 0 {
659
0
            nanoseconds += 1_000_000_000;
660
0
            seconds = match seconds.checked_sub(1) {
661
0
                Some(seconds) => seconds,
662
0
                None => return Self::MIN,
663
            };
664
0
        }
665
666
0
        Self::new_unchecked(seconds, nanoseconds)
667
0
    }
668
669
    /// Computes `self - rhs`, saturating if an overflow occurred.
670
    ///
671
    /// ```rust
672
    /// # use time::{Duration, ext::NumericalDuration};
673
    /// assert_eq!(5.seconds().saturating_sub(5.seconds()), Duration::ZERO);
674
    /// assert_eq!(Duration::MIN.saturating_sub(1.nanoseconds()), Duration::MIN);
675
    /// assert_eq!(
676
    ///     Duration::MAX.saturating_sub((-1).nanoseconds()),
677
    ///     Duration::MAX
678
    /// );
679
    /// assert_eq!(5.seconds().saturating_sub(10.seconds()), (-5).seconds());
680
    /// ```
681
0
    pub const fn saturating_sub(self, rhs: Self) -> Self {
682
0
        let (mut seconds, overflow) = self.seconds.overflowing_sub(rhs.seconds);
683
0
        if overflow {
684
0
            if self.seconds > 0 {
685
0
                return Self::MAX;
686
0
            }
687
0
            return Self::MIN;
688
0
        }
689
0
        let mut nanoseconds = self.nanoseconds - rhs.nanoseconds;
690
0
691
0
        if nanoseconds >= 1_000_000_000 || seconds < 0 && nanoseconds > 0 {
692
0
            nanoseconds -= 1_000_000_000;
693
0
            seconds = match seconds.checked_add(1) {
694
0
                Some(seconds) => seconds,
695
0
                None => return Self::MAX,
696
            };
697
0
        } else if nanoseconds <= -1_000_000_000 || seconds > 0 && nanoseconds < 0 {
698
0
            nanoseconds += 1_000_000_000;
699
0
            seconds = match seconds.checked_sub(1) {
700
0
                Some(seconds) => seconds,
701
0
                None => return Self::MIN,
702
            };
703
0
        }
704
705
0
        Self::new_unchecked(seconds, nanoseconds)
706
0
    }
707
708
    /// Computes `self * rhs`, saturating if an overflow occurred.
709
    ///
710
    /// ```rust
711
    /// # use time::{Duration, ext::NumericalDuration};
712
    /// assert_eq!(5.seconds().saturating_mul(2), 10.seconds());
713
    /// assert_eq!(5.seconds().saturating_mul(-2), (-10).seconds());
714
    /// assert_eq!(5.seconds().saturating_mul(0), Duration::ZERO);
715
    /// assert_eq!(Duration::MAX.saturating_mul(2), Duration::MAX);
716
    /// assert_eq!(Duration::MIN.saturating_mul(2), Duration::MIN);
717
    /// assert_eq!(Duration::MAX.saturating_mul(-2), Duration::MIN);
718
    /// assert_eq!(Duration::MIN.saturating_mul(-2), Duration::MAX);
719
    /// ```
720
0
    pub const fn saturating_mul(self, rhs: i32) -> Self {
721
0
        // Multiply nanoseconds as i64, because it cannot overflow that way.
722
0
        let total_nanos = self.nanoseconds as i64 * rhs as i64;
723
0
        let extra_secs = total_nanos / 1_000_000_000;
724
0
        let nanoseconds = (total_nanos % 1_000_000_000) as _;
725
0
        let (seconds, overflow1) = self.seconds.overflowing_mul(rhs as _);
726
0
        if overflow1 {
727
0
            if self.seconds > 0 && rhs > 0 || self.seconds < 0 && rhs < 0 {
728
0
                return Self::MAX;
729
0
            }
730
0
            return Self::MIN;
731
0
        }
732
0
        let (seconds, overflow2) = seconds.overflowing_add(extra_secs);
733
0
        if overflow2 {
734
0
            if self.seconds > 0 && rhs > 0 {
735
0
                return Self::MAX;
736
0
            }
737
0
            return Self::MIN;
738
0
        }
739
0
740
0
        Self::new_unchecked(seconds, nanoseconds)
741
0
    }
742
    // endregion saturating arithmetic
743
744
    /// Runs a closure, returning the duration of time it took to run. The return value of the
745
    /// closure is provided in the second part of the tuple.
746
    #[cfg(feature = "std")]
747
0
    pub fn time_fn<T>(f: impl FnOnce() -> T) -> (Self, T) {
748
0
        let start = Instant::now();
749
0
        let return_value = f();
750
0
        let end = Instant::now();
751
0
752
0
        (end - start, return_value)
753
0
    }
754
}
755
756
// region: trait impls
757
/// The format returned by this implementation is not stable and must not be relied upon.
758
///
759
/// By default this produces an exact, full-precision printout of the duration.
760
/// For a concise, rounded printout instead, you can use the `.N` format specifier:
761
///
762
/// ```
763
/// # use time::Duration;
764
/// #
765
/// let duration = Duration::new(123456, 789011223);
766
/// println!("{duration:.3}");
767
/// ```
768
///
769
/// For the purposes of this implementation, a day is exactly 24 hours and a minute is exactly 60
770
/// seconds.
771
impl fmt::Display for Duration {
772
0
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
773
0
        if self.is_negative() {
774
0
            f.write_str("-")?;
775
0
        }
776
777
0
        if let Some(_precision) = f.precision() {
778
            // Concise, rounded representation.
779
780
0
            if self.is_zero() {
781
                // Write a zero value with the requested precision.
782
0
                return (0.).fmt(f).and_then(|_| f.write_str("s"));
783
0
            }
784
0
785
0
            /// Format the first item that produces a value greater than 1 and then break.
786
0
            macro_rules! item {
787
0
                ($name:literal, $value:expr) => {
788
0
                    let value = $value;
789
0
                    if value >= 1.0 {
790
0
                        return value.fmt(f).and_then(|_| f.write_str($name));
791
0
                    }
792
0
                };
793
0
            }
794
0
795
0
            // Even if this produces a de-normal float, because we're rounding we don't really care.
796
0
            let seconds = self.unsigned_abs().as_secs_f64();
797
0
798
0
            item!("d", seconds / 86_400.);
799
0
            item!("h", seconds / 3_600.);
800
0
            item!("m", seconds / 60.);
801
0
            item!("s", seconds);
802
0
            item!("ms", seconds * 1_000.);
803
0
            item!("µs", seconds * 1_000_000.);
804
0
            item!("ns", seconds * 1_000_000_000.);
805
        } else {
806
            // Precise, but verbose representation.
807
808
0
            if self.is_zero() {
809
0
                return f.write_str("0s");
810
0
            }
811
0
812
0
            /// Format a single item.
813
0
            macro_rules! item {
814
0
                ($name:literal, $value:expr) => {
815
0
                    match $value {
816
0
                        0 => Ok(()),
817
0
                        value => value.fmt(f).and_then(|_| f.write_str($name)),
818
0
                    }
819
0
                };
820
0
            }
821
0
822
0
            let seconds = self.seconds.unsigned_abs();
823
0
            let nanoseconds = self.nanoseconds.unsigned_abs();
824
825
0
            item!("d", seconds / 86_400)?;
826
0
            item!("h", seconds / 3_600 % 24)?;
827
0
            item!("m", seconds / 60 % 60)?;
828
0
            item!("s", seconds % 60)?;
829
0
            item!("ms", nanoseconds / 1_000_000)?;
830
0
            item!("µs", nanoseconds / 1_000 % 1_000)?;
831
0
            item!("ns", nanoseconds % 1_000)?;
832
        }
833
834
0
        Ok(())
835
0
    }
836
}
837
838
impl TryFrom<StdDuration> for Duration {
839
    type Error = error::ConversionRange;
840
841
0
    fn try_from(original: StdDuration) -> Result<Self, error::ConversionRange> {
842
0
        Ok(Self::new(
843
0
            original
844
0
                .as_secs()
845
0
                .try_into()
846
0
                .map_err(|_| error::ConversionRange)?,
847
0
            original.subsec_nanos() as _,
848
        ))
849
0
    }
850
}
851
852
impl TryFrom<Duration> for StdDuration {
853
    type Error = error::ConversionRange;
854
855
0
    fn try_from(duration: Duration) -> Result<Self, error::ConversionRange> {
856
0
        Ok(Self::new(
857
0
            duration
858
0
                .seconds
859
0
                .try_into()
860
0
                .map_err(|_| error::ConversionRange)?,
861
0
            duration
862
0
                .nanoseconds
863
0
                .try_into()
864
0
                .map_err(|_| error::ConversionRange)?,
865
        ))
866
0
    }
867
}
868
869
impl Add for Duration {
870
    type Output = Self;
871
872
0
    fn add(self, rhs: Self) -> Self::Output {
873
0
        self.checked_add(rhs)
874
0
            .expect("overflow when adding durations")
875
0
    }
876
}
877
878
impl Add<StdDuration> for Duration {
879
    type Output = Self;
880
881
0
    fn add(self, std_duration: StdDuration) -> Self::Output {
882
0
        self + Self::try_from(std_duration)
883
0
            .expect("overflow converting `std::time::Duration` to `time::Duration`")
884
0
    }
885
}
886
887
impl Add<Duration> for StdDuration {
888
    type Output = Duration;
889
890
0
    fn add(self, rhs: Duration) -> Self::Output {
891
0
        rhs + self
892
0
    }
893
}
894
895
impl_add_assign!(Duration: Self, StdDuration);
896
897
impl AddAssign<Duration> for StdDuration {
898
0
    fn add_assign(&mut self, rhs: Duration) {
899
0
        *self = (*self + rhs).try_into().expect(
900
0
            "Cannot represent a resulting duration in std. Try `let x = x + rhs;`, which will \
901
0
             change the type.",
902
0
        );
903
0
    }
904
}
905
906
impl Neg for Duration {
907
    type Output = Self;
908
909
0
    fn neg(self) -> Self::Output {
910
0
        Self::new_unchecked(-self.seconds, -self.nanoseconds)
911
0
    }
912
}
913
914
impl Sub for Duration {
915
    type Output = Self;
916
917
0
    fn sub(self, rhs: Self) -> Self::Output {
918
0
        self.checked_sub(rhs)
919
0
            .expect("overflow when subtracting durations")
920
0
    }
921
}
922
923
impl Sub<StdDuration> for Duration {
924
    type Output = Self;
925
926
0
    fn sub(self, rhs: StdDuration) -> Self::Output {
927
0
        self - Self::try_from(rhs)
928
0
            .expect("overflow converting `std::time::Duration` to `time::Duration`")
929
0
    }
930
}
931
932
impl Sub<Duration> for StdDuration {
933
    type Output = Duration;
934
935
0
    fn sub(self, rhs: Duration) -> Self::Output {
936
0
        Duration::try_from(self)
937
0
            .expect("overflow converting `std::time::Duration` to `time::Duration`")
938
0
            - rhs
939
0
    }
940
}
941
942
impl_sub_assign!(Duration: Self, StdDuration);
943
944
impl SubAssign<Duration> for StdDuration {
945
0
    fn sub_assign(&mut self, rhs: Duration) {
946
0
        *self = (*self - rhs).try_into().expect(
947
0
            "Cannot represent a resulting duration in std. Try `let x = x - rhs;`, which will \
948
0
             change the type.",
949
0
        );
950
0
    }
951
}
952
953
/// Implement `Mul` (reflexively) and `Div` for `Duration` for various types.
954
macro_rules! duration_mul_div_int {
955
    ($($type:ty),+) => {$(
956
        impl Mul<$type> for Duration {
957
            type Output = Self;
958
959
0
            fn mul(self, rhs: $type) -> Self::Output {
960
0
                Self::nanoseconds_i128(
961
0
                    self.whole_nanoseconds()
962
0
                        .checked_mul(rhs as _)
963
0
                        .expect("overflow when multiplying duration")
964
0
                )
965
0
            }
Unexecuted instantiation: <time::duration::Duration as core::ops::arith::Mul<i32>>::mul
Unexecuted instantiation: <time::duration::Duration as core::ops::arith::Mul<u16>>::mul
Unexecuted instantiation: <time::duration::Duration as core::ops::arith::Mul<i16>>::mul
Unexecuted instantiation: <time::duration::Duration as core::ops::arith::Mul<u8>>::mul
Unexecuted instantiation: <time::duration::Duration as core::ops::arith::Mul<u32>>::mul
Unexecuted instantiation: <time::duration::Duration as core::ops::arith::Mul<i8>>::mul
966
        }
967
968
        impl Mul<Duration> for $type {
969
            type Output = Duration;
970
971
0
            fn mul(self, rhs: Duration) -> Self::Output {
972
0
                rhs * self
973
0
            }
Unexecuted instantiation: <i16 as core::ops::arith::Mul<time::duration::Duration>>::mul
Unexecuted instantiation: <u8 as core::ops::arith::Mul<time::duration::Duration>>::mul
Unexecuted instantiation: <i8 as core::ops::arith::Mul<time::duration::Duration>>::mul
Unexecuted instantiation: <u32 as core::ops::arith::Mul<time::duration::Duration>>::mul
Unexecuted instantiation: <i32 as core::ops::arith::Mul<time::duration::Duration>>::mul
Unexecuted instantiation: <u16 as core::ops::arith::Mul<time::duration::Duration>>::mul
974
        }
975
976
        impl Div<$type> for Duration {
977
            type Output = Self;
978
979
0
            fn div(self, rhs: $type) -> Self::Output {
980
0
                Self::nanoseconds_i128(self.whole_nanoseconds() / rhs as i128)
981
0
            }
Unexecuted instantiation: <time::duration::Duration as core::ops::arith::Div<i32>>::div
Unexecuted instantiation: <time::duration::Duration as core::ops::arith::Div<u16>>::div
Unexecuted instantiation: <time::duration::Duration as core::ops::arith::Div<i16>>::div
Unexecuted instantiation: <time::duration::Duration as core::ops::arith::Div<u8>>::div
Unexecuted instantiation: <time::duration::Duration as core::ops::arith::Div<u32>>::div
Unexecuted instantiation: <time::duration::Duration as core::ops::arith::Div<i8>>::div
982
        }
983
    )+};
984
}
985
duration_mul_div_int![i8, i16, i32, u8, u16, u32];
986
987
impl Mul<f32> for Duration {
988
    type Output = Self;
989
990
0
    fn mul(self, rhs: f32) -> Self::Output {
991
0
        Self::seconds_f32(self.as_seconds_f32() * rhs)
992
0
    }
993
}
994
995
impl Mul<Duration> for f32 {
996
    type Output = Duration;
997
998
0
    fn mul(self, rhs: Duration) -> Self::Output {
999
0
        rhs * self
1000
0
    }
1001
}
1002
1003
impl Mul<f64> for Duration {
1004
    type Output = Self;
1005
1006
0
    fn mul(self, rhs: f64) -> Self::Output {
1007
0
        Self::seconds_f64(self.as_seconds_f64() * rhs)
1008
0
    }
1009
}
1010
1011
impl Mul<Duration> for f64 {
1012
    type Output = Duration;
1013
1014
0
    fn mul(self, rhs: Duration) -> Self::Output {
1015
0
        rhs * self
1016
0
    }
1017
}
1018
1019
impl_mul_assign!(Duration: i8, i16, i32, u8, u16, u32, f32, f64);
1020
1021
impl Div<f32> for Duration {
1022
    type Output = Self;
1023
1024
0
    fn div(self, rhs: f32) -> Self::Output {
1025
0
        Self::seconds_f32(self.as_seconds_f32() / rhs)
1026
0
    }
1027
}
1028
1029
impl Div<f64> for Duration {
1030
    type Output = Self;
1031
1032
0
    fn div(self, rhs: f64) -> Self::Output {
1033
0
        Self::seconds_f64(self.as_seconds_f64() / rhs)
1034
0
    }
1035
}
1036
1037
impl_div_assign!(Duration: i8, i16, i32, u8, u16, u32, f32, f64);
1038
1039
impl Div for Duration {
1040
    type Output = f64;
1041
1042
0
    fn div(self, rhs: Self) -> Self::Output {
1043
0
        self.as_seconds_f64() / rhs.as_seconds_f64()
1044
0
    }
1045
}
1046
1047
impl Div<StdDuration> for Duration {
1048
    type Output = f64;
1049
1050
0
    fn div(self, rhs: StdDuration) -> Self::Output {
1051
0
        self.as_seconds_f64() / rhs.as_secs_f64()
1052
0
    }
1053
}
1054
1055
impl Div<Duration> for StdDuration {
1056
    type Output = f64;
1057
1058
0
    fn div(self, rhs: Duration) -> Self::Output {
1059
0
        self.as_secs_f64() / rhs.as_seconds_f64()
1060
0
    }
1061
}
1062
1063
impl PartialEq<StdDuration> for Duration {
1064
0
    fn eq(&self, rhs: &StdDuration) -> bool {
1065
0
        Ok(*self) == Self::try_from(*rhs)
1066
0
    }
1067
}
1068
1069
impl PartialEq<Duration> for StdDuration {
1070
0
    fn eq(&self, rhs: &Duration) -> bool {
1071
0
        rhs == self
1072
0
    }
1073
}
1074
1075
impl PartialOrd<StdDuration> for Duration {
1076
0
    fn partial_cmp(&self, rhs: &StdDuration) -> Option<Ordering> {
1077
0
        if rhs.as_secs() > i64::MAX as _ {
1078
0
            return Some(Ordering::Less);
1079
0
        }
1080
0
1081
0
        Some(
1082
0
            self.seconds
1083
0
                .cmp(&(rhs.as_secs() as _))
1084
0
                .then_with(|| self.nanoseconds.cmp(&(rhs.subsec_nanos() as _))),
1085
0
        )
1086
0
    }
1087
}
1088
1089
impl PartialOrd<Duration> for StdDuration {
1090
0
    fn partial_cmp(&self, rhs: &Duration) -> Option<Ordering> {
1091
0
        rhs.partial_cmp(self).map(Ordering::reverse)
1092
0
    }
1093
}
1094
1095
impl Sum for Duration {
1096
0
    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
1097
0
        iter.reduce(|a, b| a + b).unwrap_or_default()
1098
0
    }
1099
}
1100
1101
impl<'a> Sum<&'a Self> for Duration {
1102
0
    fn sum<I: Iterator<Item = &'a Self>>(iter: I) -> Self {
1103
0
        iter.copied().sum()
1104
0
    }
1105
}
1106
// endregion trait impls