Skip to main content

time/
duration.rs

1//! The [`Duration`] struct and its associated `impl`s.
2
3use core::cmp::Ordering;
4use core::fmt;
5use core::hash::{Hash, Hasher};
6use core::iter::Sum;
7use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
8use core::time::Duration as StdDuration;
9#[cfg(feature = "std")]
10use std::time::SystemTime;
11
12use deranged::RangedI32;
13use num_conv::prelude::*;
14
15#[cfg(feature = "std")]
16#[expect(deprecated)]
17use crate::Instant;
18use crate::error;
19use crate::internal_macros::const_try_opt;
20use crate::unit::*;
21
22#[derive(Debug)]
23enum FloatConstructorError {
24    Nan,
25    NegOverflow,
26    PosOverflow,
27}
28
29/// By explicitly inserting this enum where padding is expected, the compiler is able to better
30/// perform niche value optimization.
31#[repr(u32)]
32#[derive(Debug, Clone, Copy)]
33pub(crate) enum Padding {
34    #[allow(clippy::missing_docs_in_private_items)]
35    Optimize,
36}
37
38/// The type of the `nanosecond` field of `Duration`.
39type Nanoseconds =
40    RangedI32<{ -Nanosecond::per_t::<i32>(Second) + 1 }, { Nanosecond::per_t::<i32>(Second) - 1 }>;
41
42/// A span of time with nanosecond precision.
43///
44/// Each `Duration` is composed of a whole number of seconds and a fractional part represented in
45/// nanoseconds.
46///
47/// This implementation allows for negative durations, unlike [`core::time::Duration`].
48#[repr(C)]
49#[derive(Clone, Copy)]
50pub struct Duration {
51    /// Number of whole seconds.
52    seconds: i64,
53    /// Number of nanoseconds within the second. The sign always matches the `seconds` field.
54    // Sign must match that of `seconds` (though this is not a safety requirement).
55    nanoseconds: Nanoseconds,
56    _padding: Padding,
57}
58
59impl fmt::Debug for Duration {
60    #[inline]
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        f.debug_struct("Duration")
63            .field("seconds", &self.seconds)
64            .field("nanoseconds", &self.nanoseconds)
65            .finish()
66    }
67}
68
69impl PartialEq for Duration {
70    #[inline]
71    fn eq(&self, other: &Self) -> bool {
72        self.as_int_for_equality() == other.as_int_for_equality()
73    }
74}
75
76impl Eq for Duration {}
77
78impl PartialOrd for Duration {
79    #[inline]
80    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
81        Some(self.cmp(other))
82    }
83}
84
85impl Ord for Duration {
86    #[inline]
87    fn cmp(&self, other: &Self) -> Ordering {
88        self.seconds
89            .cmp(&other.seconds)
90            .then_with(|| self.nanoseconds.cmp(&other.nanoseconds))
91    }
92}
93
94impl Hash for Duration {
95    fn hash<H>(&self, state: &mut H)
96    where
97        H: Hasher,
98    {
99        self.as_int_for_equality().hash(state);
100    }
101}
102
103impl Default for Duration {
104    #[inline]
105    fn default() -> Self {
106        Self::ZERO
107    }
108}
109
110/// This is adapted from the [`std` implementation][std], which uses mostly bit
111/// operations to ensure the highest precision:
112///
113/// Changes from `std` are marked and explained below.
114///
115/// [std]: https://github.com/rust-lang/rust/blob/3a37c2f0523c87147b64f1b8099fc9df22e8c53e/library/core/src/time.rs#L1262-L1340
116#[rustfmt::skip] // Skip `rustfmt` because it reformats the arguments of the macro weirdly.
117macro_rules! try_from_secs {
118    (
119        secs = $secs: expr,
120        mantissa_bits = $mant_bits: literal,
121        exponent_bits = $exp_bits: literal,
122        offset = $offset: literal,
123        bits_ty = $bits_ty:ty,
124        bits_ty_signed = $bits_ty_signed:ty,
125        double_ty = $double_ty:ty,
126        float_ty = $float_ty:ty,
127    ) => {{
128        'value: {
129            const MIN_EXP: i16 = 1 - (1i16 << $exp_bits) / 2;
130            const MANT_MASK: $bits_ty = (1 << $mant_bits) - 1;
131            const EXP_MASK: $bits_ty = (1 << $exp_bits) - 1;
132
133            // Change from std: No error check for negative values necessary.
134
135            let bits = $secs.to_bits();
136            let mant = (bits & MANT_MASK) | (MANT_MASK + 1);
137            let exp = ((bits >> $mant_bits) & EXP_MASK) as i16 + MIN_EXP;
138
139            let (secs, nanos) = if exp < -31 {
140                // the input represents less than 1ns and can not be rounded to it
141                (0u64, 0u32)
142            } else if exp < 0 {
143                // the input is less than 1 second
144                let t = (mant as $double_ty) << ($offset + exp);
145                let nanos_offset = $mant_bits + $offset;
146                #[allow(trivial_numeric_casts)]
147                let nanos_tmp = Nanosecond::per_t::<u128>(Second) * t as u128;
148                let nanos = (nanos_tmp >> nanos_offset) as u32;
149
150                let rem_mask = (1 << nanos_offset) - 1;
151                let rem_msb_mask = 1 << (nanos_offset - 1);
152                let rem = nanos_tmp & rem_mask;
153                let is_tie = rem == rem_msb_mask;
154                let is_even = (nanos & 1) == 0;
155                let rem_msb = nanos_tmp & rem_msb_mask == 0;
156                let add_ns = !(rem_msb || (is_even && is_tie));
157
158                // f32 does not have enough precision to trigger the second branch
159                // since it can not represent numbers between 0.999_999_940_395 and 1.0.
160                let nanos = nanos + add_ns as u32;
161                if ($mant_bits == 23) || (nanos != Nanosecond::per_t::<u32>(Second)) {
162                    (0, nanos)
163                } else {
164                    (1, 0)
165                }
166            } else if exp < $mant_bits {
167                #[allow(trivial_numeric_casts)]
168                let secs = (mant >> ($mant_bits - exp)) as u64;
169                let t = ((mant << exp) & MANT_MASK) as $double_ty;
170                let nanos_offset = $mant_bits;
171                let nanos_tmp = Nanosecond::per_t::<$double_ty>(Second) * t;
172                let nanos = (nanos_tmp >> nanos_offset) as u32;
173
174                let rem_mask = (1 << nanos_offset) - 1;
175                let rem_msb_mask = 1 << (nanos_offset - 1);
176                let rem = nanos_tmp & rem_mask;
177                let is_tie = rem == rem_msb_mask;
178                let is_even = (nanos & 1) == 0;
179                let rem_msb = nanos_tmp & rem_msb_mask == 0;
180                let add_ns = !(rem_msb || (is_even && is_tie));
181
182                // f32 does not have enough precision to trigger the second branch.
183                // For example, it can not represent numbers between 1.999_999_880...
184                // and 2.0. Bigger values result in even smaller precision of the
185                // fractional part.
186                let nanos = nanos + add_ns as u32;
187                if ($mant_bits == 23) || (nanos != Nanosecond::per_t::<u32>(Second)) {
188                    (secs, nanos)
189                } else {
190                    (secs + 1, 0)
191                }
192            } else if exp < 63 {
193                // Change from std: The exponent here is 63 instead of 64,
194                // because i64::MAX + 1 is 2^63.
195
196                // the input has no fractional part
197                #[allow(trivial_numeric_casts)]
198                let secs = (mant as u64) << (exp - $mant_bits);
199                (secs, 0)
200            } else if bits == (i64::MIN as $float_ty).to_bits() {
201                // Change from std: Signed integers are asymmetrical in that
202                // iN::MIN is -iN::MAX - 1. So for example i8 covers the
203                // following numbers -128..=127. The check above (exp < 63)
204                // doesn't cover i64::MIN as that is -2^63, so we have this
205                // additional case to handle the asymmetry of iN::MIN.
206                break 'value Ok(Self::new_ranged_unchecked(i64::MIN, Nanoseconds::new_static::<0>()));
207            } else if $secs.is_nan() {
208                // Change from std: std doesn't differentiate between the error
209                // cases.
210                break 'value Err(FloatConstructorError::Nan);
211            } else if $secs.is_sign_negative() {
212                break 'value Err(FloatConstructorError::NegOverflow);
213            } else {
214                break 'value Err(FloatConstructorError::PosOverflow);
215            };
216
217            // Change from std: All the code is mostly unmodified in that it
218            // simply calculates an unsigned integer. Here we extract the sign
219            // bit and assign it to the number. We basically manually do two's
220            // complement here, we could also use an if and just negate the
221            // numbers based on the sign, but it turns out to be quite a bit
222            // slower.
223            let mask = (bits as $bits_ty_signed) >> ($mant_bits + $exp_bits);
224            #[allow(trivial_numeric_casts)]
225            let secs_signed = ((secs as i64) ^ (mask as i64)) - (mask as i64);
226            #[allow(trivial_numeric_casts)]
227            let nanos_signed = ((nanos as i32) ^ (mask as i32)) - (mask as i32);
228            // Safety: `nanos_signed` is in range.
229            Ok(unsafe { Self::new_unchecked(secs_signed, nanos_signed) })
230        }
231    }};
232}
233
234impl Duration {
235    const fn as_int_for_equality(self) -> i128 {
236        // Safety: There are no padding bytes that are not permitted to be read.
237        unsafe { core::mem::transmute(self) }
238    }
239
240    /// Equivalent to `0.seconds()`.
241    ///
242    /// ```rust
243    /// # use time::{Duration, ext::NumericalDuration};
244    /// assert_eq!(Duration::ZERO, 0.seconds());
245    /// ```
246    pub const ZERO: Self = Self::seconds(0);
247
248    /// Equivalent to `1.nanoseconds()`.
249    ///
250    /// ```rust
251    /// # use time::{Duration, ext::NumericalDuration};
252    /// assert_eq!(Duration::NANOSECOND, 1.nanoseconds());
253    /// ```
254    pub const NANOSECOND: Self = Self::nanoseconds(1);
255
256    /// Equivalent to `1.microseconds()`.
257    ///
258    /// ```rust
259    /// # use time::{Duration, ext::NumericalDuration};
260    /// assert_eq!(Duration::MICROSECOND, 1.microseconds());
261    /// ```
262    pub const MICROSECOND: Self = Self::microseconds(1);
263
264    /// Equivalent to `1.milliseconds()`.
265    ///
266    /// ```rust
267    /// # use time::{Duration, ext::NumericalDuration};
268    /// assert_eq!(Duration::MILLISECOND, 1.milliseconds());
269    /// ```
270    pub const MILLISECOND: Self = Self::milliseconds(1);
271
272    /// Equivalent to `1.seconds()`.
273    ///
274    /// ```rust
275    /// # use time::{Duration, ext::NumericalDuration};
276    /// assert_eq!(Duration::SECOND, 1.seconds());
277    /// ```
278    pub const SECOND: Self = Self::seconds(1);
279
280    /// Equivalent to `1.minutes()`.
281    ///
282    /// ```rust
283    /// # use time::{Duration, ext::NumericalDuration};
284    /// assert_eq!(Duration::MINUTE, 1.minutes());
285    /// ```
286    pub const MINUTE: Self = Self::minutes(1);
287
288    /// Equivalent to `1.hours()`.
289    ///
290    /// ```rust
291    /// # use time::{Duration, ext::NumericalDuration};
292    /// assert_eq!(Duration::HOUR, 1.hours());
293    /// ```
294    pub const HOUR: Self = Self::hours(1);
295
296    /// Equivalent to `1.days()`.
297    ///
298    /// ```rust
299    /// # use time::{Duration, ext::NumericalDuration};
300    /// assert_eq!(Duration::DAY, 1.days());
301    /// ```
302    pub const DAY: Self = Self::days(1);
303
304    /// Equivalent to `1.weeks()`.
305    ///
306    /// ```rust
307    /// # use time::{Duration, ext::NumericalDuration};
308    /// assert_eq!(Duration::WEEK, 1.weeks());
309    /// ```
310    pub const WEEK: Self = Self::weeks(1);
311
312    /// The minimum possible duration. Adding any negative duration to this will cause an overflow.
313    pub const MIN: Self = Self::new_ranged(i64::MIN, Nanoseconds::MIN);
314
315    /// The maximum possible duration. Adding any positive duration to this will cause an overflow.
316    pub const MAX: Self = Self::new_ranged(i64::MAX, Nanoseconds::MAX);
317
318    /// Check if a duration is exactly zero.
319    ///
320    /// ```rust
321    /// # use time::ext::NumericalDuration;
322    /// assert!(0.seconds().is_zero());
323    /// assert!(!1.nanoseconds().is_zero());
324    /// ```
325    #[inline]
326    pub const fn is_zero(self) -> bool {
327        self.as_int_for_equality() == Self::ZERO.as_int_for_equality()
328    }
329
330    /// Check if a duration is negative.
331    ///
332    /// ```rust
333    /// # use time::ext::NumericalDuration;
334    /// assert!((-1).seconds().is_negative());
335    /// assert!(!0.seconds().is_negative());
336    /// assert!(!1.seconds().is_negative());
337    /// ```
338    #[inline]
339    pub const fn is_negative(self) -> bool {
340        self.seconds < 0 || self.nanoseconds.get() < 0
341    }
342
343    /// Check if a duration is positive.
344    ///
345    /// ```rust
346    /// # use time::ext::NumericalDuration;
347    /// assert!(1.seconds().is_positive());
348    /// assert!(!0.seconds().is_positive());
349    /// assert!(!(-1).seconds().is_positive());
350    /// ```
351    #[inline]
352    pub const fn is_positive(self) -> bool {
353        self.seconds > 0 || self.nanoseconds.get() > 0
354    }
355
356    /// Get the absolute value of the duration.
357    ///
358    /// This method saturates the returned value if it would otherwise overflow.
359    ///
360    /// ```rust
361    /// # use time::ext::NumericalDuration;
362    /// assert_eq!(1.seconds().abs(), 1.seconds());
363    /// assert_eq!(0.seconds().abs(), 0.seconds());
364    /// assert_eq!((-1).seconds().abs(), 1.seconds());
365    /// ```
366    #[inline]
367    pub const fn abs(self) -> Self {
368        match self.seconds.checked_abs() {
369            Some(seconds) => Self::new_ranged_unchecked(seconds, self.nanoseconds.abs()),
370            None => Self::MAX,
371        }
372    }
373
374    /// Convert the existing `Duration` to a `std::time::Duration` and its sign. This returns a
375    /// [`std::time::Duration`] and does not saturate the returned value (unlike [`Duration::abs`]).
376    ///
377    /// ```rust
378    /// # use time::ext::{NumericalDuration, NumericalStdDuration};
379    /// assert_eq!(1.seconds().unsigned_abs(), 1.std_seconds());
380    /// assert_eq!(0.seconds().unsigned_abs(), 0.std_seconds());
381    /// assert_eq!((-1).seconds().unsigned_abs(), 1.std_seconds());
382    /// ```
383    #[inline]
384    pub const fn unsigned_abs(self) -> StdDuration {
385        StdDuration::new(
386            self.seconds.unsigned_abs(),
387            self.nanoseconds.get().unsigned_abs(),
388        )
389    }
390
391    /// Create a new `Duration` without checking the validity of the components.
392    ///
393    /// # Safety
394    ///
395    /// - `nanoseconds` must be in the range `-999_999_999..=999_999_999`.
396    ///
397    /// While the sign of `nanoseconds` is required to be the same as the sign of `seconds`, this is
398    /// not a safety invariant.
399    #[inline]
400    #[track_caller]
401    pub(crate) const unsafe fn new_unchecked(seconds: i64, nanoseconds: i32) -> Self {
402        Self::new_ranged_unchecked(
403            seconds,
404            // Safety: The caller must uphold the safety invariants.
405            unsafe { Nanoseconds::new_unchecked(nanoseconds) },
406        )
407    }
408
409    /// Create a new `Duration` without checking the validity of the components.
410    #[inline]
411    #[track_caller]
412    pub(crate) const fn new_ranged_unchecked(seconds: i64, nanoseconds: Nanoseconds) -> Self {
413        if seconds < 0 {
414            debug_assert!(nanoseconds.get() <= 0);
415        } else if seconds > 0 {
416            debug_assert!(nanoseconds.get() >= 0);
417        }
418
419        Self {
420            seconds,
421            nanoseconds,
422            _padding: Padding::Optimize,
423        }
424    }
425
426    /// Create a new `Duration` with the provided seconds and nanoseconds. If nanoseconds is at
427    /// least ±10<sup>9</sup>, it will wrap to the number of seconds.
428    ///
429    /// ```rust
430    /// # use time::{Duration, ext::NumericalDuration};
431    /// assert_eq!(Duration::new(1, 0), 1.seconds());
432    /// assert_eq!(Duration::new(-1, 0), (-1).seconds());
433    /// assert_eq!(Duration::new(1, 2_000_000_000), 3.seconds());
434    /// ```
435    ///
436    /// # Panics
437    ///
438    /// This may panic if an overflow occurs.
439    #[inline]
440    #[track_caller]
441    pub const fn new(mut seconds: i64, mut nanoseconds: i32) -> Self {
442        seconds = seconds
443            .checked_add(nanoseconds as i64 / Nanosecond::per_t::<i64>(Second))
444            .expect("overflow constructing `time::Duration`");
445        nanoseconds %= Nanosecond::per_t::<i32>(Second);
446
447        if seconds > 0 && nanoseconds < 0 {
448            // `seconds` cannot overflow here because it is positive.
449            seconds -= 1;
450            nanoseconds += Nanosecond::per_t::<i32>(Second);
451        } else if seconds < 0 && nanoseconds > 0 {
452            // `seconds` cannot overflow here because it is negative.
453            seconds += 1;
454            nanoseconds -= Nanosecond::per_t::<i32>(Second);
455        }
456
457        // Safety: `nanoseconds` is in range due to the modulus above.
458        unsafe { Self::new_unchecked(seconds, nanoseconds) }
459    }
460
461    /// Create a new `Duration` with the provided seconds and nanoseconds.
462    #[inline]
463    pub(crate) const fn new_ranged(mut seconds: i64, mut nanoseconds: Nanoseconds) -> Self {
464        if seconds > 0 && nanoseconds.get() < 0 {
465            // `seconds` cannot overflow here because it is positive.
466            seconds -= 1;
467            // Safety: `nanoseconds` is negative with a maximum of 999,999,999, so adding a billion
468            // to it is guaranteed to result in an in-range value.
469            nanoseconds = unsafe {
470                Nanoseconds::new_unchecked(nanoseconds.get() + Nanosecond::per_t::<i32>(Second))
471            };
472        } else if seconds < 0 && nanoseconds.get() > 0 {
473            // `seconds` cannot overflow here because it is negative.
474            seconds += 1;
475            // Safety: `nanoseconds` is positive with a minimum of -999,999,999, so subtracting a
476            // billion from it is guaranteed to result in an in-range value.
477            nanoseconds = unsafe {
478                Nanoseconds::new_unchecked(nanoseconds.get() - Nanosecond::per_t::<i32>(Second))
479            };
480        }
481
482        Self::new_ranged_unchecked(seconds, nanoseconds)
483    }
484
485    /// Create a new `Duration` with the given number of weeks. Equivalent to
486    /// `Duration::seconds(weeks * 604_800)`.
487    ///
488    /// ```rust
489    /// # use time::{Duration, ext::NumericalDuration};
490    /// assert_eq!(Duration::weeks(1), 604_800.seconds());
491    /// ```
492    ///
493    /// # Panics
494    ///
495    /// This may panic if an overflow occurs.
496    #[inline]
497    #[track_caller]
498    pub const fn weeks(weeks: i64) -> Self {
499        Self::seconds(
500            weeks
501                .checked_mul(Second::per_t(Week))
502                .expect("overflow constructing `time::Duration`"),
503        )
504    }
505
506    /// Create a new `Duration` with the given number of days. Equivalent to
507    /// `Duration::seconds(days * 86_400)`.
508    ///
509    /// ```rust
510    /// # use time::{Duration, ext::NumericalDuration};
511    /// assert_eq!(Duration::days(1), 86_400.seconds());
512    /// ```
513    ///
514    /// # Panics
515    ///
516    /// This may panic if an overflow occurs.
517    #[inline]
518    #[track_caller]
519    pub const fn days(days: i64) -> Self {
520        Self::seconds(
521            days.checked_mul(Second::per_t(Day))
522                .expect("overflow constructing `time::Duration`"),
523        )
524    }
525
526    /// Create a new `Duration` with the given number of hours. Equivalent to
527    /// `Duration::seconds(hours * 3_600)`.
528    ///
529    /// ```rust
530    /// # use time::{Duration, ext::NumericalDuration};
531    /// assert_eq!(Duration::hours(1), 3_600.seconds());
532    /// ```
533    ///
534    /// # Panics
535    ///
536    /// This may panic if an overflow occurs.
537    #[inline]
538    #[track_caller]
539    pub const fn hours(hours: i64) -> Self {
540        Self::seconds(
541            hours
542                .checked_mul(Second::per_t(Hour))
543                .expect("overflow constructing `time::Duration`"),
544        )
545    }
546
547    /// Create a new `Duration` with the given number of minutes. Equivalent to
548    /// `Duration::seconds(minutes * 60)`.
549    ///
550    /// ```rust
551    /// # use time::{Duration, ext::NumericalDuration};
552    /// assert_eq!(Duration::minutes(1), 60.seconds());
553    /// ```
554    ///
555    /// # Panics
556    ///
557    /// This may panic if an overflow occurs.
558    #[inline]
559    #[track_caller]
560    pub const fn minutes(minutes: i64) -> Self {
561        Self::seconds(
562            minutes
563                .checked_mul(Second::per_t(Minute))
564                .expect("overflow constructing `time::Duration`"),
565        )
566    }
567
568    /// Create a new `Duration` with the given number of seconds.
569    ///
570    /// ```rust
571    /// # use time::{Duration, ext::NumericalDuration};
572    /// assert_eq!(Duration::seconds(1), 1_000.milliseconds());
573    /// ```
574    #[inline]
575    pub const fn seconds(seconds: i64) -> Self {
576        Self::new_ranged_unchecked(seconds, Nanoseconds::new_static::<0>())
577    }
578
579    /// Create a new `Duration` from the specified number of seconds represented as `f64`.
580    ///
581    /// If the value is `NaN` or out of bounds, an error is returned that can be handled in the
582    /// desired manner by the caller.
583    #[inline]
584    const fn try_seconds_f64(seconds: f64) -> Result<Self, FloatConstructorError> {
585        try_from_secs!(
586            secs = seconds,
587            mantissa_bits = 52,
588            exponent_bits = 11,
589            offset = 44,
590            bits_ty = u64,
591            bits_ty_signed = i64,
592            double_ty = u128,
593            float_ty = f64,
594        )
595    }
596
597    /// Create a new `Duration` from the specified number of seconds represented as `f32`.
598    ///
599    /// If the value is `NaN` or out of bounds, an error is returned that can be handled in the
600    /// desired manner by the caller.
601    #[inline]
602    const fn try_seconds_f32(seconds: f32) -> Result<Self, FloatConstructorError> {
603        try_from_secs!(
604            secs = seconds,
605            mantissa_bits = 23,
606            exponent_bits = 8,
607            offset = 41,
608            bits_ty = u32,
609            bits_ty_signed = i32,
610            double_ty = u64,
611            float_ty = f32,
612        )
613    }
614
615    /// Creates a new `Duration` from the specified number of seconds represented as `f64`.
616    ///
617    /// ```rust
618    /// # use time::{Duration, ext::NumericalDuration};
619    /// assert_eq!(Duration::seconds_f64(0.5), 0.5.seconds());
620    /// assert_eq!(Duration::seconds_f64(-0.5), (-0.5).seconds());
621    /// ```
622    #[inline]
623    #[track_caller]
624    pub const fn seconds_f64(seconds: f64) -> Self {
625        match Self::try_seconds_f64(seconds) {
626            Ok(duration) => duration,
627            Err(FloatConstructorError::Nan) => {
628                panic!("passed NaN to `time::Duration::seconds_f64`");
629            }
630            Err(FloatConstructorError::NegOverflow | FloatConstructorError::PosOverflow) => {
631                panic!("overflow constructing `time::Duration`");
632            }
633        }
634    }
635
636    /// Creates a new `Duration` from the specified number of seconds represented as `f32`.
637    ///
638    /// ```rust
639    /// # use time::{Duration, ext::NumericalDuration};
640    /// assert_eq!(Duration::seconds_f32(0.5), 0.5.seconds());
641    /// assert_eq!(Duration::seconds_f32(-0.5), (-0.5).seconds());
642    /// ```
643    #[inline]
644    #[track_caller]
645    pub const fn seconds_f32(seconds: f32) -> Self {
646        match Self::try_seconds_f32(seconds) {
647            Ok(duration) => duration,
648            Err(FloatConstructorError::Nan) => {
649                panic!("passed NaN to `time::Duration::seconds_f32`");
650            }
651            Err(FloatConstructorError::NegOverflow | FloatConstructorError::PosOverflow) => {
652                panic!("overflow constructing `time::Duration`");
653            }
654        }
655    }
656
657    /// Creates a new `Duration` from the specified number of seconds
658    /// represented as `f64`. Any values that are out of bounds are saturated at
659    /// the minimum or maximum respectively. `NaN` gets turned into a `Duration`
660    /// of 0 seconds.
661    ///
662    /// ```rust
663    /// # use time::{Duration, ext::NumericalDuration};
664    /// assert_eq!(Duration::saturating_seconds_f64(0.5), 0.5.seconds());
665    /// assert_eq!(Duration::saturating_seconds_f64(-0.5), (-0.5).seconds());
666    /// assert_eq!(
667    ///     Duration::saturating_seconds_f64(f64::NAN),
668    ///     Duration::new(0, 0),
669    /// );
670    /// assert_eq!(
671    ///     Duration::saturating_seconds_f64(f64::NEG_INFINITY),
672    ///     Duration::MIN,
673    /// );
674    /// assert_eq!(
675    ///     Duration::saturating_seconds_f64(f64::INFINITY),
676    ///     Duration::MAX,
677    /// );
678    /// ```
679    #[inline]
680    pub const fn saturating_seconds_f64(seconds: f64) -> Self {
681        match Self::try_seconds_f64(seconds) {
682            Ok(duration) => duration,
683            Err(FloatConstructorError::Nan) => Self::ZERO,
684            Err(FloatConstructorError::NegOverflow) => Self::MIN,
685            Err(FloatConstructorError::PosOverflow) => Self::MAX,
686        }
687    }
688
689    /// Creates a new `Duration` from the specified number of seconds
690    /// represented as `f32`. Any values that are out of bounds are saturated at
691    /// the minimum or maximum respectively. `NaN` gets turned into a `Duration`
692    /// of 0 seconds.
693    ///
694    /// ```rust
695    /// # use time::{Duration, ext::NumericalDuration};
696    /// assert_eq!(Duration::saturating_seconds_f32(0.5), 0.5.seconds());
697    /// assert_eq!(Duration::saturating_seconds_f32(-0.5), (-0.5).seconds());
698    /// assert_eq!(
699    ///     Duration::saturating_seconds_f32(f32::NAN),
700    ///     Duration::new(0, 0),
701    /// );
702    /// assert_eq!(
703    ///     Duration::saturating_seconds_f32(f32::NEG_INFINITY),
704    ///     Duration::MIN,
705    /// );
706    /// assert_eq!(
707    ///     Duration::saturating_seconds_f32(f32::INFINITY),
708    ///     Duration::MAX,
709    /// );
710    /// ```
711    #[inline]
712    pub const fn saturating_seconds_f32(seconds: f32) -> Self {
713        match Self::try_seconds_f32(seconds) {
714            Ok(duration) => duration,
715            Err(FloatConstructorError::Nan) => Self::ZERO,
716            Err(FloatConstructorError::NegOverflow) => Self::MIN,
717            Err(FloatConstructorError::PosOverflow) => Self::MAX,
718        }
719    }
720
721    /// Creates a new `Duration` from the specified number of seconds
722    /// represented as `f64`. Returns `None` if the `Duration` can't be
723    /// represented.
724    ///
725    /// ```rust
726    /// # use time::{Duration, ext::NumericalDuration};
727    /// assert_eq!(Duration::checked_seconds_f64(0.5), Some(0.5.seconds()));
728    /// assert_eq!(Duration::checked_seconds_f64(-0.5), Some((-0.5).seconds()));
729    /// assert_eq!(Duration::checked_seconds_f64(f64::NAN), None);
730    /// assert_eq!(Duration::checked_seconds_f64(f64::NEG_INFINITY), None);
731    /// assert_eq!(Duration::checked_seconds_f64(f64::INFINITY), None);
732    /// ```
733    #[inline]
734    pub const fn checked_seconds_f64(seconds: f64) -> Option<Self> {
735        match Self::try_seconds_f64(seconds) {
736            Ok(duration) => Some(duration),
737            Err(_) => None,
738        }
739    }
740
741    /// Creates a new `Duration` from the specified number of seconds
742    /// represented as `f32`. Returns `None` if the `Duration` can't be
743    /// represented.
744    ///
745    /// ```rust
746    /// # use time::{Duration, ext::NumericalDuration};
747    /// assert_eq!(Duration::checked_seconds_f32(0.5), Some(0.5.seconds()));
748    /// assert_eq!(Duration::checked_seconds_f32(-0.5), Some((-0.5).seconds()));
749    /// assert_eq!(Duration::checked_seconds_f32(f32::NAN), None);
750    /// assert_eq!(Duration::checked_seconds_f32(f32::NEG_INFINITY), None);
751    /// assert_eq!(Duration::checked_seconds_f32(f32::INFINITY), None);
752    /// ```
753    #[inline]
754    pub const fn checked_seconds_f32(seconds: f32) -> Option<Self> {
755        match Self::try_seconds_f32(seconds) {
756            Ok(duration) => Some(duration),
757            Err(_) => None,
758        }
759    }
760
761    /// Create a new `Duration` with the given number of milliseconds.
762    ///
763    /// ```rust
764    /// # use time::{Duration, ext::NumericalDuration};
765    /// assert_eq!(Duration::milliseconds(1), 1_000.microseconds());
766    /// assert_eq!(Duration::milliseconds(-1), (-1_000).microseconds());
767    /// ```
768    #[inline]
769    pub const fn milliseconds(milliseconds: i64) -> Self {
770        // Safety: `nanoseconds` is guaranteed to be in range because of the modulus.
771        unsafe {
772            Self::new_unchecked(
773                milliseconds / Millisecond::per_t::<i64>(Second),
774                (milliseconds % Millisecond::per_t::<i64>(Second)
775                    * Nanosecond::per_t::<i64>(Millisecond)) as i32,
776            )
777        }
778    }
779
780    /// Create a new `Duration` with the given number of microseconds.
781    ///
782    /// ```rust
783    /// # use time::{Duration, ext::NumericalDuration};
784    /// assert_eq!(Duration::microseconds(1), 1_000.nanoseconds());
785    /// assert_eq!(Duration::microseconds(-1), (-1_000).nanoseconds());
786    /// ```
787    #[inline]
788    pub const fn microseconds(microseconds: i64) -> Self {
789        // Safety: `nanoseconds` is guaranteed to be in range because of the modulus.
790        unsafe {
791            Self::new_unchecked(
792                microseconds / Microsecond::per_t::<i64>(Second),
793                (microseconds % Microsecond::per_t::<i64>(Second)
794                    * Nanosecond::per_t::<i64>(Microsecond)) as i32,
795            )
796        }
797    }
798
799    /// Create a new `Duration` with the given number of nanoseconds.
800    ///
801    /// ```rust
802    /// # use time::{Duration, ext::NumericalDuration};
803    /// assert_eq!(Duration::nanoseconds(1), 1.microseconds() / 1_000);
804    /// assert_eq!(Duration::nanoseconds(-1), (-1).microseconds() / 1_000);
805    /// ```
806    #[inline]
807    pub const fn nanoseconds(nanoseconds: i64) -> Self {
808        // Safety: `nanoseconds` is guaranteed to be in range because of the modulus.
809        unsafe {
810            Self::new_unchecked(
811                nanoseconds / Nanosecond::per_t::<i64>(Second),
812                (nanoseconds % Nanosecond::per_t::<i64>(Second)) as i32,
813            )
814        }
815    }
816
817    /// Create a new `Duration` with the given number of nanoseconds.
818    ///
819    /// ```rust
820    /// # use time::{Duration, ext::NumericalDuration};
821    /// assert_eq!(
822    ///     Duration::nanoseconds_i128(1_234_567_890),
823    ///     1.seconds() + 234_567_890.nanoseconds()
824    /// );
825    /// ```
826    ///
827    /// # Panics
828    ///
829    /// This may panic if an overflow occurs. This may happen because the input range cannot be
830    /// fully mapped to the output.
831    #[inline]
832    #[track_caller]
833    pub const fn nanoseconds_i128(nanoseconds: i128) -> Self {
834        let seconds = nanoseconds / Nanosecond::per_t::<i128>(Second);
835        let nanoseconds = nanoseconds % Nanosecond::per_t::<i128>(Second);
836
837        if seconds > i64::MAX as i128 || seconds < i64::MIN as i128 {
838            panic!("overflow constructing `time::Duration`");
839        }
840
841        // Safety: `nanoseconds` is guaranteed to be in range because of the modulus above.
842        unsafe { Self::new_unchecked(seconds as i64, nanoseconds as i32) }
843    }
844
845    /// Get the number of whole weeks in the duration.
846    ///
847    /// ```rust
848    /// # use time::ext::NumericalDuration;
849    /// assert_eq!(1.weeks().whole_weeks(), 1);
850    /// assert_eq!((-1).weeks().whole_weeks(), -1);
851    /// assert_eq!(6.days().whole_weeks(), 0);
852    /// assert_eq!((-6).days().whole_weeks(), 0);
853    /// ```
854    #[inline]
855    pub const fn whole_weeks(self) -> i64 {
856        self.whole_seconds() / Second::per_t::<i64>(Week)
857    }
858
859    /// Get the number of whole days in the duration.
860    ///
861    /// ```rust
862    /// # use time::ext::NumericalDuration;
863    /// assert_eq!(1.days().whole_days(), 1);
864    /// assert_eq!((-1).days().whole_days(), -1);
865    /// assert_eq!(23.hours().whole_days(), 0);
866    /// assert_eq!((-23).hours().whole_days(), 0);
867    /// ```
868    #[inline]
869    pub const fn whole_days(self) -> i64 {
870        self.whole_seconds() / Second::per_t::<i64>(Day)
871    }
872
873    /// Get the number of whole hours in the duration.
874    ///
875    /// ```rust
876    /// # use time::ext::NumericalDuration;
877    /// assert_eq!(1.hours().whole_hours(), 1);
878    /// assert_eq!((-1).hours().whole_hours(), -1);
879    /// assert_eq!(59.minutes().whole_hours(), 0);
880    /// assert_eq!((-59).minutes().whole_hours(), 0);
881    /// ```
882    #[inline]
883    pub const fn whole_hours(self) -> i64 {
884        self.whole_seconds() / Second::per_t::<i64>(Hour)
885    }
886
887    /// Get the number of whole minutes in the duration.
888    ///
889    /// ```rust
890    /// # use time::ext::NumericalDuration;
891    /// assert_eq!(1.minutes().whole_minutes(), 1);
892    /// assert_eq!((-1).minutes().whole_minutes(), -1);
893    /// assert_eq!(59.seconds().whole_minutes(), 0);
894    /// assert_eq!((-59).seconds().whole_minutes(), 0);
895    /// ```
896    #[inline]
897    pub const fn whole_minutes(self) -> i64 {
898        self.whole_seconds() / Second::per_t::<i64>(Minute)
899    }
900
901    /// Get the number of whole seconds in the duration.
902    ///
903    /// ```rust
904    /// # use time::ext::NumericalDuration;
905    /// assert_eq!(1.seconds().whole_seconds(), 1);
906    /// assert_eq!((-1).seconds().whole_seconds(), -1);
907    /// assert_eq!(1.minutes().whole_seconds(), 60);
908    /// assert_eq!((-1).minutes().whole_seconds(), -60);
909    /// ```
910    #[inline]
911    pub const fn whole_seconds(self) -> i64 {
912        self.seconds
913    }
914
915    /// Get the number of fractional seconds in the duration.
916    ///
917    /// ```rust
918    /// # use time::ext::NumericalDuration;
919    /// assert_eq!(1.5.seconds().as_seconds_f64(), 1.5);
920    /// assert_eq!((-1.5).seconds().as_seconds_f64(), -1.5);
921    /// ```
922    #[inline]
923    pub const fn as_seconds_f64(self) -> f64 {
924        self.seconds as f64 + self.nanoseconds.get() as f64 / Nanosecond::per_t::<f64>(Second)
925    }
926
927    /// Get the number of fractional seconds in the duration.
928    ///
929    /// ```rust
930    /// # use time::ext::NumericalDuration;
931    /// assert_eq!(1.5.seconds().as_seconds_f32(), 1.5);
932    /// assert_eq!((-1.5).seconds().as_seconds_f32(), -1.5);
933    /// ```
934    #[inline]
935    pub const fn as_seconds_f32(self) -> f32 {
936        self.seconds as f32 + self.nanoseconds.get() as f32 / Nanosecond::per_t::<f32>(Second)
937    }
938
939    /// Get the number of whole milliseconds in the duration.
940    ///
941    /// ```rust
942    /// # use time::ext::NumericalDuration;
943    /// assert_eq!(1.seconds().whole_milliseconds(), 1_000);
944    /// assert_eq!((-1).seconds().whole_milliseconds(), -1_000);
945    /// assert_eq!(1.milliseconds().whole_milliseconds(), 1);
946    /// assert_eq!((-1).milliseconds().whole_milliseconds(), -1);
947    /// ```
948    #[inline]
949    pub const fn whole_milliseconds(self) -> i128 {
950        self.seconds as i128 * Millisecond::per_t::<i128>(Second)
951            + self.nanoseconds.get() as i128 / Nanosecond::per_t::<i128>(Millisecond)
952    }
953
954    /// Get the number of milliseconds past the number of whole seconds.
955    ///
956    /// Always in the range `-999..=999`.
957    ///
958    /// ```rust
959    /// # use time::ext::NumericalDuration;
960    /// assert_eq!(1.4.seconds().subsec_milliseconds(), 400);
961    /// assert_eq!((-1.4).seconds().subsec_milliseconds(), -400);
962    /// ```
963    #[inline]
964    pub const fn subsec_milliseconds(self) -> i16 {
965        (self.nanoseconds.get() / Nanosecond::per_t::<i32>(Millisecond)) as i16
966    }
967
968    /// Get the number of whole microseconds in the duration.
969    ///
970    /// ```rust
971    /// # use time::ext::NumericalDuration;
972    /// assert_eq!(1.milliseconds().whole_microseconds(), 1_000);
973    /// assert_eq!((-1).milliseconds().whole_microseconds(), -1_000);
974    /// assert_eq!(1.microseconds().whole_microseconds(), 1);
975    /// assert_eq!((-1).microseconds().whole_microseconds(), -1);
976    /// ```
977    #[inline]
978    pub const fn whole_microseconds(self) -> i128 {
979        self.seconds as i128 * Microsecond::per_t::<i128>(Second)
980            + self.nanoseconds.get() as i128 / Nanosecond::per_t::<i128>(Microsecond)
981    }
982
983    /// Get the number of microseconds past the number of whole seconds.
984    ///
985    /// Always in the range `-999_999..=999_999`.
986    ///
987    /// ```rust
988    /// # use time::ext::NumericalDuration;
989    /// assert_eq!(1.0004.seconds().subsec_microseconds(), 400);
990    /// assert_eq!((-1.0004).seconds().subsec_microseconds(), -400);
991    /// ```
992    #[inline]
993    pub const fn subsec_microseconds(self) -> i32 {
994        self.nanoseconds.get() / Nanosecond::per_t::<i32>(Microsecond)
995    }
996
997    /// Get the number of nanoseconds in the duration.
998    ///
999    /// ```rust
1000    /// # use time::ext::NumericalDuration;
1001    /// assert_eq!(1.microseconds().whole_nanoseconds(), 1_000);
1002    /// assert_eq!((-1).microseconds().whole_nanoseconds(), -1_000);
1003    /// assert_eq!(1.nanoseconds().whole_nanoseconds(), 1);
1004    /// assert_eq!((-1).nanoseconds().whole_nanoseconds(), -1);
1005    /// ```
1006    #[inline]
1007    pub const fn whole_nanoseconds(self) -> i128 {
1008        self.seconds as i128 * Nanosecond::per_t::<i128>(Second) + self.nanoseconds.get() as i128
1009    }
1010
1011    /// Get the number of nanoseconds past the number of whole seconds.
1012    ///
1013    /// The returned value will always be in the range `-999_999_999..=999_999_999`.
1014    ///
1015    /// ```rust
1016    /// # use time::ext::NumericalDuration;
1017    /// assert_eq!(1.000_000_400.seconds().subsec_nanoseconds(), 400);
1018    /// assert_eq!((-1.000_000_400).seconds().subsec_nanoseconds(), -400);
1019    /// ```
1020    #[inline]
1021    pub const fn subsec_nanoseconds(self) -> i32 {
1022        self.nanoseconds.get()
1023    }
1024
1025    /// Get the number of nanoseconds past the number of whole seconds.
1026    #[cfg(feature = "quickcheck")]
1027    #[inline]
1028    pub(crate) const fn subsec_nanoseconds_ranged(self) -> Nanoseconds {
1029        self.nanoseconds
1030    }
1031
1032    /// Computes `self + rhs`, returning `None` if an overflow occurred.
1033    ///
1034    /// ```rust
1035    /// # use time::{Duration, ext::NumericalDuration};
1036    /// assert_eq!(5.seconds().checked_add(5.seconds()), Some(10.seconds()));
1037    /// assert_eq!(Duration::MAX.checked_add(1.nanoseconds()), None);
1038    /// assert_eq!((-5).seconds().checked_add(5.seconds()), Some(0.seconds()));
1039    /// ```
1040    #[inline]
1041    pub const fn checked_add(self, rhs: Self) -> Option<Self> {
1042        let mut seconds = const_try_opt!(self.seconds.checked_add(rhs.seconds));
1043        let mut nanoseconds = self.nanoseconds.get() + rhs.nanoseconds.get();
1044
1045        if nanoseconds >= Nanosecond::per_t(Second) || seconds < 0 && nanoseconds > 0 {
1046            nanoseconds -= Nanosecond::per_t::<i32>(Second);
1047            seconds = const_try_opt!(seconds.checked_add(1));
1048        } else if nanoseconds <= -Nanosecond::per_t::<i32>(Second) || seconds > 0 && nanoseconds < 0
1049        {
1050            nanoseconds += Nanosecond::per_t::<i32>(Second);
1051            seconds = const_try_opt!(seconds.checked_sub(1));
1052        }
1053
1054        // Safety: `nanoseconds` is guaranteed to be in range because of the overflow handling.
1055        unsafe { Some(Self::new_unchecked(seconds, nanoseconds)) }
1056    }
1057
1058    /// Computes `self - rhs`, returning `None` if an overflow occurred.
1059    ///
1060    /// ```rust
1061    /// # use time::{Duration, ext::NumericalDuration};
1062    /// assert_eq!(5.seconds().checked_sub(5.seconds()), Some(Duration::ZERO));
1063    /// assert_eq!(Duration::MIN.checked_sub(1.nanoseconds()), None);
1064    /// assert_eq!(5.seconds().checked_sub(10.seconds()), Some((-5).seconds()));
1065    /// ```
1066    #[inline]
1067    pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
1068        let mut seconds = const_try_opt!(self.seconds.checked_sub(rhs.seconds));
1069        let mut nanoseconds = self.nanoseconds.get() - rhs.nanoseconds.get();
1070
1071        if nanoseconds >= Nanosecond::per_t(Second) || seconds < 0 && nanoseconds > 0 {
1072            nanoseconds -= Nanosecond::per_t::<i32>(Second);
1073            seconds = const_try_opt!(seconds.checked_add(1));
1074        } else if nanoseconds <= -Nanosecond::per_t::<i32>(Second) || seconds > 0 && nanoseconds < 0
1075        {
1076            nanoseconds += Nanosecond::per_t::<i32>(Second);
1077            seconds = const_try_opt!(seconds.checked_sub(1));
1078        }
1079
1080        // Safety: `nanoseconds` is guaranteed to be in range because of the overflow handling.
1081        unsafe { Some(Self::new_unchecked(seconds, nanoseconds)) }
1082    }
1083
1084    /// Computes `self * rhs`, returning `None` if an overflow occurred.
1085    ///
1086    /// ```rust
1087    /// # use time::{Duration, ext::NumericalDuration};
1088    /// assert_eq!(5.seconds().checked_mul(2), Some(10.seconds()));
1089    /// assert_eq!(5.seconds().checked_mul(-2), Some((-10).seconds()));
1090    /// assert_eq!(5.seconds().checked_mul(0), Some(0.seconds()));
1091    /// assert_eq!(Duration::MAX.checked_mul(2), None);
1092    /// assert_eq!(Duration::MIN.checked_mul(2), None);
1093    /// ```
1094    #[inline]
1095    pub const fn checked_mul(self, rhs: i32) -> Option<Self> {
1096        // Multiply nanoseconds as i64, because it cannot overflow that way.
1097        let total_nanos = self.nanoseconds.get() as i64 * rhs as i64;
1098        let extra_secs = total_nanos / Nanosecond::per_t::<i64>(Second);
1099        let nanoseconds = (total_nanos % Nanosecond::per_t::<i64>(Second)) as i32;
1100        let seconds = const_try_opt!(
1101            const_try_opt!(self.seconds.checked_mul(rhs as i64)).checked_add(extra_secs)
1102        );
1103
1104        // Safety: `nanoseconds` is guaranteed to be in range because of the modulus above.
1105        unsafe { Some(Self::new_unchecked(seconds, nanoseconds)) }
1106    }
1107
1108    /// Computes `self / rhs`, returning `None` if `rhs == 0` or if the result would overflow.
1109    ///
1110    /// ```rust
1111    /// # use time::ext::NumericalDuration;
1112    /// assert_eq!(10.seconds().checked_div(2), Some(5.seconds()));
1113    /// assert_eq!(10.seconds().checked_div(-2), Some((-5).seconds()));
1114    /// assert_eq!(1.seconds().checked_div(0), None);
1115    /// ```
1116    #[inline]
1117    pub const fn checked_div(self, rhs: i32) -> Option<Self> {
1118        let (secs, extra_secs) = (
1119            const_try_opt!(self.seconds.checked_div(rhs as i64)),
1120            self.seconds % (rhs as i64),
1121        );
1122        let (mut nanos, extra_nanos) = (self.nanoseconds.get() / rhs, self.nanoseconds.get() % rhs);
1123        nanos += ((extra_secs * (Nanosecond::per_t::<i64>(Second)) + extra_nanos as i64)
1124            / (rhs as i64)) as i32;
1125
1126        // Safety: `nanoseconds` is in range.
1127        unsafe { Some(Self::new_unchecked(secs, nanos)) }
1128    }
1129
1130    /// Computes `-self`, returning `None` if the result would overflow.
1131    ///
1132    /// ```rust
1133    /// # use time::ext::NumericalDuration;
1134    /// # use time::Duration;
1135    /// assert_eq!(5.seconds().checked_neg(), Some((-5).seconds()));
1136    /// assert_eq!(Duration::MIN.checked_neg(), None);
1137    /// ```
1138    #[inline]
1139    pub const fn checked_neg(self) -> Option<Self> {
1140        if self.seconds == i64::MIN {
1141            None
1142        } else {
1143            Some(Self::new_ranged_unchecked(
1144                -self.seconds,
1145                self.nanoseconds.neg(),
1146            ))
1147        }
1148    }
1149
1150    /// Computes `self + rhs`, saturating if an overflow occurred.
1151    ///
1152    /// ```rust
1153    /// # use time::{Duration, ext::NumericalDuration};
1154    /// assert_eq!(5.seconds().saturating_add(5.seconds()), 10.seconds());
1155    /// assert_eq!(Duration::MAX.saturating_add(1.nanoseconds()), Duration::MAX);
1156    /// assert_eq!(
1157    ///     Duration::MIN.saturating_add((-1).nanoseconds()),
1158    ///     Duration::MIN
1159    /// );
1160    /// assert_eq!((-5).seconds().saturating_add(5.seconds()), Duration::ZERO);
1161    /// ```
1162    #[inline]
1163    pub const fn saturating_add(self, rhs: Self) -> Self {
1164        let (mut seconds, overflow) = self.seconds.overflowing_add(rhs.seconds);
1165        if overflow {
1166            if self.seconds > 0 {
1167                return Self::MAX;
1168            }
1169            return Self::MIN;
1170        }
1171        let mut nanoseconds = self.nanoseconds.get() + rhs.nanoseconds.get();
1172
1173        if nanoseconds >= Nanosecond::per_t(Second) || seconds < 0 && nanoseconds > 0 {
1174            nanoseconds -= Nanosecond::per_t::<i32>(Second);
1175            seconds = match seconds.checked_add(1) {
1176                Some(seconds) => seconds,
1177                None => return Self::MAX,
1178            };
1179        } else if nanoseconds <= -Nanosecond::per_t::<i32>(Second) || seconds > 0 && nanoseconds < 0
1180        {
1181            nanoseconds += Nanosecond::per_t::<i32>(Second);
1182            seconds = match seconds.checked_sub(1) {
1183                Some(seconds) => seconds,
1184                None => return Self::MIN,
1185            };
1186        }
1187
1188        // Safety: `nanoseconds` is guaranteed to be in range because of the overflow handling.
1189        unsafe { Self::new_unchecked(seconds, nanoseconds) }
1190    }
1191
1192    /// Computes `self - rhs`, saturating if an overflow occurred.
1193    ///
1194    /// ```rust
1195    /// # use time::{Duration, ext::NumericalDuration};
1196    /// assert_eq!(5.seconds().saturating_sub(5.seconds()), Duration::ZERO);
1197    /// assert_eq!(Duration::MIN.saturating_sub(1.nanoseconds()), Duration::MIN);
1198    /// assert_eq!(
1199    ///     Duration::MAX.saturating_sub((-1).nanoseconds()),
1200    ///     Duration::MAX
1201    /// );
1202    /// assert_eq!(5.seconds().saturating_sub(10.seconds()), (-5).seconds());
1203    /// ```
1204    #[inline]
1205    pub const fn saturating_sub(self, rhs: Self) -> Self {
1206        let (mut seconds, overflow) = self.seconds.overflowing_sub(rhs.seconds);
1207        if overflow {
1208            if self.seconds > 0 {
1209                return Self::MAX;
1210            }
1211            return Self::MIN;
1212        }
1213        let mut nanoseconds = self.nanoseconds.get() - rhs.nanoseconds.get();
1214
1215        if nanoseconds >= Nanosecond::per_t(Second) || seconds < 0 && nanoseconds > 0 {
1216            nanoseconds -= Nanosecond::per_t::<i32>(Second);
1217            seconds = match seconds.checked_add(1) {
1218                Some(seconds) => seconds,
1219                None => return Self::MAX,
1220            };
1221        } else if nanoseconds <= -Nanosecond::per_t::<i32>(Second) || seconds > 0 && nanoseconds < 0
1222        {
1223            nanoseconds += Nanosecond::per_t::<i32>(Second);
1224            seconds = match seconds.checked_sub(1) {
1225                Some(seconds) => seconds,
1226                None => return Self::MIN,
1227            };
1228        }
1229
1230        // Safety: `nanoseconds` is guaranteed to be in range because of the overflow handling.
1231        unsafe { Self::new_unchecked(seconds, nanoseconds) }
1232    }
1233
1234    /// Computes `self * rhs`, saturating if an overflow occurred.
1235    ///
1236    /// ```rust
1237    /// # use time::{Duration, ext::NumericalDuration};
1238    /// assert_eq!(5.seconds().saturating_mul(2), 10.seconds());
1239    /// assert_eq!(5.seconds().saturating_mul(-2), (-10).seconds());
1240    /// assert_eq!(5.seconds().saturating_mul(0), Duration::ZERO);
1241    /// assert_eq!(Duration::MAX.saturating_mul(2), Duration::MAX);
1242    /// assert_eq!(Duration::MIN.saturating_mul(2), Duration::MIN);
1243    /// assert_eq!(Duration::MAX.saturating_mul(-2), Duration::MIN);
1244    /// assert_eq!(Duration::MIN.saturating_mul(-2), Duration::MAX);
1245    /// ```
1246    #[inline]
1247    pub const fn saturating_mul(self, rhs: i32) -> Self {
1248        // Multiply nanoseconds as i64, because it cannot overflow that way.
1249        let total_nanos = self.nanoseconds.get() as i64 * rhs as i64;
1250        let extra_secs = total_nanos / Nanosecond::per_t::<i64>(Second);
1251        let nanoseconds = (total_nanos % Nanosecond::per_t::<i64>(Second)) as i32;
1252        let (seconds, overflow1) = self.seconds.overflowing_mul(rhs as i64);
1253        if overflow1 {
1254            if self.seconds > 0 && rhs > 0 || self.seconds < 0 && rhs < 0 {
1255                return Self::MAX;
1256            }
1257            return Self::MIN;
1258        }
1259        let (seconds, overflow2) = seconds.overflowing_add(extra_secs);
1260        if overflow2 {
1261            if self.seconds > 0 && rhs > 0 {
1262                return Self::MAX;
1263            }
1264            return Self::MIN;
1265        }
1266
1267        // Safety: `nanoseconds` is guaranteed to be in range because of to the modulus above.
1268        unsafe { Self::new_unchecked(seconds, nanoseconds) }
1269    }
1270
1271    /// Runs a closure, returning the duration of time it took to run. The return value of the
1272    /// closure is provided in the second part of the tuple.
1273    #[cfg(feature = "std")]
1274    #[doc(hidden)]
1275    #[inline]
1276    #[track_caller]
1277    #[deprecated(
1278        since = "0.3.32",
1279        note = "extremely limited use case, not intended for benchmarking"
1280    )]
1281    #[expect(deprecated)]
1282    pub fn time_fn<T>(f: impl FnOnce() -> T) -> (Self, T) {
1283        let start = Instant::now();
1284        let return_value = f();
1285        let end = Instant::now();
1286
1287        (end - start, return_value)
1288    }
1289}
1290
1291/// The format returned by this implementation is not stable and must not be relied upon.
1292///
1293/// By default this produces an exact, full-precision printout of the duration.
1294/// For a concise, rounded printout instead, you can use the `.N` format specifier:
1295///
1296/// ```
1297/// # use time::Duration;
1298/// #
1299/// let duration = Duration::new(123456, 789011223);
1300/// println!("{duration:.3}");
1301/// ```
1302///
1303/// For the purposes of this implementation, a day is exactly 24 hours and a minute is exactly 60
1304/// seconds.
1305impl fmt::Display for Duration {
1306    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1307        if self.is_negative() {
1308            f.write_str("-")?;
1309        }
1310
1311        if let Some(_precision) = f.precision() {
1312            // Concise, rounded representation.
1313
1314            if self.is_zero() {
1315                // Write a zero value with the requested precision.
1316                return (0.).fmt(f).and_then(|_| f.write_str("s"));
1317            }
1318
1319            /// Format the first item that produces a value greater than 1 and then break.
1320            macro_rules! item {
1321                ($name:literal, $value:expr) => {
1322                    let value = $value;
1323                    if value >= 1.0 {
1324                        return value.fmt(f).and_then(|_| f.write_str($name));
1325                    }
1326                };
1327            }
1328
1329            // Even if this produces a de-normal float, because we're rounding we don't really care.
1330            let seconds = self.unsigned_abs().as_secs_f64();
1331
1332            item!("d", seconds / Second::per_t::<f64>(Day));
1333            item!("h", seconds / Second::per_t::<f64>(Hour));
1334            item!("m", seconds / Second::per_t::<f64>(Minute));
1335            item!("s", seconds);
1336            item!("ms", seconds * Millisecond::per_t::<f64>(Second));
1337            item!("µs", seconds * Microsecond::per_t::<f64>(Second));
1338            item!("ns", seconds * Nanosecond::per_t::<f64>(Second));
1339        } else {
1340            // Precise, but verbose representation.
1341
1342            if self.is_zero() {
1343                return f.write_str("0s");
1344            }
1345
1346            /// Format a single item.
1347            macro_rules! item {
1348                ($name:literal, $value:expr) => {
1349                    match $value {
1350                        0 => Ok(()),
1351                        value => value.fmt(f).and_then(|_| f.write_str($name)),
1352                    }
1353                };
1354            }
1355
1356            let seconds = self.seconds.unsigned_abs();
1357            let nanoseconds = self.nanoseconds.get().unsigned_abs();
1358
1359            item!("d", seconds / Second::per_t::<u64>(Day))?;
1360            item!(
1361                "h",
1362                seconds / Second::per_t::<u64>(Hour) % Hour::per_t::<u64>(Day)
1363            )?;
1364            item!(
1365                "m",
1366                seconds / Second::per_t::<u64>(Minute) % Minute::per_t::<u64>(Hour)
1367            )?;
1368            item!("s", seconds % Second::per_t::<u64>(Minute))?;
1369            item!("ms", nanoseconds / Nanosecond::per_t::<u32>(Millisecond))?;
1370            item!(
1371                "µs",
1372                nanoseconds / Nanosecond::per_t::<u32>(Microsecond)
1373                    % Microsecond::per_t::<u32>(Millisecond)
1374            )?;
1375            item!("ns", nanoseconds % Nanosecond::per_t::<u32>(Microsecond))?;
1376        }
1377
1378        Ok(())
1379    }
1380}
1381
1382impl TryFrom<StdDuration> for Duration {
1383    type Error = error::ConversionRange;
1384
1385    #[inline]
1386    fn try_from(original: StdDuration) -> Result<Self, error::ConversionRange> {
1387        Ok(Self::new(
1388            original
1389                .as_secs()
1390                .try_into()
1391                .map_err(|_| error::ConversionRange)?,
1392            original.subsec_nanos().cast_signed(),
1393        ))
1394    }
1395}
1396
1397impl TryFrom<Duration> for StdDuration {
1398    type Error = error::ConversionRange;
1399
1400    #[inline]
1401    fn try_from(duration: Duration) -> Result<Self, error::ConversionRange> {
1402        Ok(Self::new(
1403            duration
1404                .seconds
1405                .try_into()
1406                .map_err(|_| error::ConversionRange)?,
1407            duration
1408                .nanoseconds
1409                .get()
1410                .try_into()
1411                .map_err(|_| error::ConversionRange)?,
1412        ))
1413    }
1414}
1415
1416impl Add for Duration {
1417    type Output = Self;
1418
1419    /// # Panics
1420    ///
1421    /// This may panic if an overflow occurs.
1422    #[inline]
1423    #[track_caller]
1424    fn add(self, rhs: Self) -> Self::Output {
1425        self.checked_add(rhs)
1426            .expect("overflow when adding durations")
1427    }
1428}
1429
1430impl Add<StdDuration> for Duration {
1431    type Output = Self;
1432
1433    /// # Panics
1434    ///
1435    /// This may panic if an overflow occurs.
1436    #[inline]
1437    #[track_caller]
1438    fn add(self, std_duration: StdDuration) -> Self::Output {
1439        self + Self::try_from(std_duration)
1440            .expect("overflow converting `std::time::Duration` to `time::Duration`")
1441    }
1442}
1443
1444impl Add<Duration> for StdDuration {
1445    type Output = Duration;
1446
1447    /// # Panics
1448    ///
1449    /// This may panic if an overflow occurs.
1450    #[inline]
1451    #[track_caller]
1452    fn add(self, rhs: Duration) -> Self::Output {
1453        rhs + self
1454    }
1455}
1456
1457impl AddAssign<Self> for Duration {
1458    /// # Panics
1459    ///
1460    /// This may panic if an overflow occurs.
1461    #[inline]
1462    #[track_caller]
1463    fn add_assign(&mut self, rhs: Self) {
1464        *self = *self + rhs;
1465    }
1466}
1467
1468impl AddAssign<StdDuration> for Duration {
1469    /// # Panics
1470    ///
1471    /// This may panic if an overflow occurs.
1472    #[inline]
1473    #[track_caller]
1474    fn add_assign(&mut self, rhs: StdDuration) {
1475        *self = *self + rhs;
1476    }
1477}
1478
1479impl AddAssign<Duration> for StdDuration {
1480    /// # Panics
1481    ///
1482    /// This may panic if the resulting addition cannot be represented.
1483    #[inline]
1484    #[track_caller]
1485    fn add_assign(&mut self, rhs: Duration) {
1486        *self = (*self + rhs).try_into().expect(
1487            "Cannot represent a resulting duration in std. Try `let x = x + rhs;`, which will \
1488             change the type.",
1489        );
1490    }
1491}
1492
1493impl Neg for Duration {
1494    type Output = Self;
1495
1496    /// # Panics
1497    ///
1498    /// This may panic if an overflow occurs.
1499    #[inline]
1500    #[track_caller]
1501    fn neg(self) -> Self::Output {
1502        self.checked_neg().expect("overflow when negating duration")
1503    }
1504}
1505
1506impl Sub for Duration {
1507    type Output = Self;
1508
1509    /// # Panics
1510    ///
1511    /// This may panic if an overflow occurs.
1512    #[inline]
1513    #[track_caller]
1514    fn sub(self, rhs: Self) -> Self::Output {
1515        self.checked_sub(rhs)
1516            .expect("overflow when subtracting durations")
1517    }
1518}
1519
1520impl Sub<StdDuration> for Duration {
1521    type Output = Self;
1522
1523    /// # Panics
1524    ///
1525    /// This may panic if an overflow occurs.
1526    #[inline]
1527    #[track_caller]
1528    fn sub(self, rhs: StdDuration) -> Self::Output {
1529        self - Self::try_from(rhs)
1530            .expect("overflow converting `std::time::Duration` to `time::Duration`")
1531    }
1532}
1533
1534impl Sub<Duration> for StdDuration {
1535    type Output = Duration;
1536
1537    /// # Panics
1538    ///
1539    /// This may panic if an overflow occurs.
1540    #[inline]
1541    #[track_caller]
1542    fn sub(self, rhs: Duration) -> Self::Output {
1543        Duration::try_from(self)
1544            .expect("overflow converting `std::time::Duration` to `time::Duration`")
1545            - rhs
1546    }
1547}
1548
1549impl SubAssign<Self> for Duration {
1550    /// # Panics
1551    ///
1552    /// This may panic if an overflow occurs.
1553    #[inline]
1554    #[track_caller]
1555    fn sub_assign(&mut self, rhs: Self) {
1556        *self = *self - rhs;
1557    }
1558}
1559
1560impl SubAssign<StdDuration> for Duration {
1561    /// # Panics
1562    ///
1563    /// This may panic if an overflow occurs.
1564    #[inline]
1565    #[track_caller]
1566    fn sub_assign(&mut self, rhs: StdDuration) {
1567        *self = *self - rhs;
1568    }
1569}
1570
1571impl SubAssign<Duration> for StdDuration {
1572    /// # Panics
1573    ///
1574    /// This may panic if the resulting subtraction can not be represented.
1575    #[inline]
1576    #[track_caller]
1577    fn sub_assign(&mut self, rhs: Duration) {
1578        *self = (*self - rhs).try_into().expect(
1579            "Cannot represent a resulting duration in std. Try `let x = x - rhs;`, which will \
1580             change the type.",
1581        );
1582    }
1583}
1584
1585/// Given a value and whether it is signed, cast it to the signed version.
1586macro_rules! cast_signed {
1587    (@signed $val:ident) => {
1588        $val
1589    };
1590    (@unsigned $val:ident) => {
1591        $val.cast_signed()
1592    };
1593}
1594
1595/// Implement `Mul` (reflexively), `MulAssign`, `Div`, and `DivAssign` for `Duration` for various
1596/// signed types.
1597macro_rules! duration_mul_div_int {
1598    ($(@$signedness:ident $type:ty),+ $(,)?) => {$(
1599        impl Mul<$type> for Duration {
1600            type Output = Self;
1601
1602            /// # Panics
1603            ///
1604            /// This may panic if an overflow occurs.
1605            #[inline]
1606            #[track_caller]
1607            fn mul(self, rhs: $type) -> Self::Output {
1608                Self::nanoseconds_i128(
1609                    self.whole_nanoseconds()
1610                        .checked_mul(cast_signed!(@$signedness rhs).extend::<i128>())
1611                        .expect("overflow when multiplying duration")
1612                )
1613            }
1614        }
1615
1616        impl Mul<Duration> for $type {
1617            type Output = Duration;
1618
1619            /// # Panics
1620            ///
1621            /// This may panic if an overflow occurs.
1622            #[inline]
1623            #[track_caller]
1624            fn mul(self, rhs: Duration) -> Self::Output {
1625                rhs * self
1626            }
1627        }
1628
1629        impl MulAssign<$type> for Duration {
1630            /// # Panics
1631            ///
1632            /// This may panic if an overflow occurs.
1633            #[inline]
1634            #[track_caller]
1635            fn mul_assign(&mut self, rhs: $type) {
1636                *self = *self * rhs;
1637            }
1638        }
1639
1640        impl Div<$type> for Duration {
1641            type Output = Self;
1642
1643            /// # Panics
1644            ///
1645            /// This may panic if an overflow occurs.
1646            #[inline]
1647            #[track_caller]
1648            fn div(self, rhs: $type) -> Self::Output {
1649                Self::nanoseconds_i128(
1650                    self.whole_nanoseconds() / cast_signed!(@$signedness rhs).extend::<i128>()
1651                )
1652            }
1653        }
1654
1655        impl DivAssign<$type> for Duration {
1656            /// # Panics
1657            ///
1658            /// This may panic if an overflow occurs.
1659            #[inline]
1660            #[track_caller]
1661            fn div_assign(&mut self, rhs: $type) {
1662                *self = *self / rhs;
1663            }
1664        }
1665    )+};
1666}
1667
1668duration_mul_div_int! {
1669    @signed i8,
1670    @signed i16,
1671    @signed i32,
1672    @unsigned u8,
1673    @unsigned u16,
1674    @unsigned u32,
1675}
1676
1677impl Mul<f32> for Duration {
1678    type Output = Self;
1679
1680    /// # Panics
1681    ///
1682    /// This may panic if an overflow occurs.
1683    #[inline]
1684    #[track_caller]
1685    fn mul(self, rhs: f32) -> Self::Output {
1686        Self::seconds_f32(self.as_seconds_f32() * rhs)
1687    }
1688}
1689
1690impl Mul<Duration> for f32 {
1691    type Output = Duration;
1692
1693    /// # Panics
1694    ///
1695    /// This may panic if an overflow occurs.
1696    #[inline]
1697    #[track_caller]
1698    fn mul(self, rhs: Duration) -> Self::Output {
1699        rhs * self
1700    }
1701}
1702
1703impl Mul<f64> for Duration {
1704    type Output = Self;
1705
1706    /// # Panics
1707    ///
1708    /// This may panic if an overflow occurs.
1709    #[inline]
1710    #[track_caller]
1711    fn mul(self, rhs: f64) -> Self::Output {
1712        Self::seconds_f64(self.as_seconds_f64() * rhs)
1713    }
1714}
1715
1716impl Mul<Duration> for f64 {
1717    type Output = Duration;
1718
1719    /// # Panics
1720    ///
1721    /// This may panic if an overflow occurs.
1722    #[inline]
1723    #[track_caller]
1724    fn mul(self, rhs: Duration) -> Self::Output {
1725        rhs * self
1726    }
1727}
1728
1729impl MulAssign<f32> for Duration {
1730    /// # Panics
1731    ///
1732    /// This may panic if an overflow occurs.
1733    #[inline]
1734    #[track_caller]
1735    fn mul_assign(&mut self, rhs: f32) {
1736        *self = *self * rhs;
1737    }
1738}
1739
1740impl MulAssign<f64> for Duration {
1741    /// # Panics
1742    ///
1743    /// This may panic if an overflow occurs.
1744    #[inline]
1745    #[track_caller]
1746    fn mul_assign(&mut self, rhs: f64) {
1747        *self = *self * rhs;
1748    }
1749}
1750
1751impl Div<f32> for Duration {
1752    type Output = Self;
1753
1754    /// # Panics
1755    ///
1756    /// This may panic if an overflow occurs.
1757    #[inline]
1758    #[track_caller]
1759    fn div(self, rhs: f32) -> Self::Output {
1760        Self::seconds_f32(self.as_seconds_f32() / rhs)
1761    }
1762}
1763
1764impl Div<f64> for Duration {
1765    type Output = Self;
1766
1767    /// # Panics
1768    ///
1769    /// This may panic if an overflow occurs.
1770    #[inline]
1771    #[track_caller]
1772    fn div(self, rhs: f64) -> Self::Output {
1773        Self::seconds_f64(self.as_seconds_f64() / rhs)
1774    }
1775}
1776
1777impl DivAssign<f32> for Duration {
1778    /// # Panics
1779    ///
1780    /// This may panic if an overflow occurs.
1781    #[inline]
1782    #[track_caller]
1783    fn div_assign(&mut self, rhs: f32) {
1784        *self = *self / rhs;
1785    }
1786}
1787
1788impl DivAssign<f64> for Duration {
1789    /// # Panics
1790    ///
1791    /// This may panic if an overflow occurs.
1792    #[inline]
1793    #[track_caller]
1794    fn div_assign(&mut self, rhs: f64) {
1795        *self = *self / rhs;
1796    }
1797}
1798
1799impl Div for Duration {
1800    type Output = f64;
1801
1802    #[inline]
1803    #[track_caller]
1804    fn div(self, rhs: Self) -> Self::Output {
1805        self.as_seconds_f64() / rhs.as_seconds_f64()
1806    }
1807}
1808
1809impl Div<StdDuration> for Duration {
1810    type Output = f64;
1811
1812    #[inline]
1813    #[track_caller]
1814    fn div(self, rhs: StdDuration) -> Self::Output {
1815        self.as_seconds_f64() / rhs.as_secs_f64()
1816    }
1817}
1818
1819impl Div<Duration> for StdDuration {
1820    type Output = f64;
1821
1822    #[inline]
1823    #[track_caller]
1824    fn div(self, rhs: Duration) -> Self::Output {
1825        self.as_secs_f64() / rhs.as_seconds_f64()
1826    }
1827}
1828
1829impl PartialEq<StdDuration> for Duration {
1830    #[inline]
1831    fn eq(&self, rhs: &StdDuration) -> bool {
1832        Ok(*self) == Self::try_from(*rhs)
1833    }
1834}
1835
1836impl PartialEq<Duration> for StdDuration {
1837    #[inline]
1838    fn eq(&self, rhs: &Duration) -> bool {
1839        rhs == self
1840    }
1841}
1842
1843impl PartialOrd<StdDuration> for Duration {
1844    #[inline]
1845    fn partial_cmp(&self, rhs: &StdDuration) -> Option<Ordering> {
1846        if rhs.as_secs() > i64::MAX.cast_unsigned() {
1847            return Some(Ordering::Less);
1848        }
1849
1850        Some(
1851            self.seconds
1852                .cmp(&rhs.as_secs().cast_signed())
1853                .then_with(|| {
1854                    self.nanoseconds
1855                        .get()
1856                        .cmp(&rhs.subsec_nanos().cast_signed())
1857                }),
1858        )
1859    }
1860}
1861
1862impl PartialOrd<Duration> for StdDuration {
1863    #[inline]
1864    fn partial_cmp(&self, rhs: &Duration) -> Option<Ordering> {
1865        rhs.partial_cmp(self).map(Ordering::reverse)
1866    }
1867}
1868
1869impl Sum for Duration {
1870    #[inline]
1871    fn sum<I>(iter: I) -> Self
1872    where
1873        I: Iterator<Item = Self>,
1874    {
1875        iter.reduce(|a, b| a + b).unwrap_or_default()
1876    }
1877}
1878
1879impl<'a> Sum<&'a Self> for Duration {
1880    #[inline]
1881    fn sum<I>(iter: I) -> Self
1882    where
1883        I: Iterator<Item = &'a Self>,
1884    {
1885        iter.copied().sum()
1886    }
1887}
1888
1889#[cfg(feature = "std")]
1890impl Add<Duration> for SystemTime {
1891    type Output = Self;
1892
1893    /// # Panics
1894    ///
1895    /// This may panic if an overflow occurs.
1896    #[inline]
1897    #[track_caller]
1898    fn add(self, duration: Duration) -> Self::Output {
1899        if duration.is_zero() {
1900            self
1901        } else if duration.is_positive() {
1902            self + duration.unsigned_abs()
1903        } else {
1904            debug_assert!(duration.is_negative());
1905            self - duration.unsigned_abs()
1906        }
1907    }
1908}
1909
1910#[cfg(feature = "std")]
1911impl AddAssign<Duration> for SystemTime {
1912    /// # Panics
1913    ///
1914    /// This may panic if an overflow occurs.
1915    #[inline]
1916    #[track_caller]
1917    fn add_assign(&mut self, rhs: Duration) {
1918        *self = *self + rhs;
1919    }
1920}
1921
1922#[cfg(feature = "std")]
1923impl Sub<Duration> for SystemTime {
1924    type Output = Self;
1925
1926    #[inline]
1927    #[track_caller]
1928    fn sub(self, duration: Duration) -> Self::Output {
1929        if duration.is_zero() {
1930            self
1931        } else if duration.is_positive() {
1932            self - duration.unsigned_abs()
1933        } else {
1934            debug_assert!(duration.is_negative());
1935            self + duration.unsigned_abs()
1936        }
1937    }
1938}
1939
1940#[cfg(feature = "std")]
1941impl SubAssign<Duration> for SystemTime {
1942    /// # Panics
1943    ///
1944    /// This may panic if an overflow occurs.
1945    #[inline]
1946    #[track_caller]
1947    fn sub_assign(&mut self, rhs: Duration) {
1948        *self = *self - rhs;
1949    }
1950}