chrono/
time_delta.rs

1// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
11//! Temporal quantification
12
13use core::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign};
14use core::time::Duration;
15use core::{fmt, i64};
16#[cfg(feature = "std")]
17use std::error::Error;
18
19use crate::{expect, try_opt};
20
21#[cfg(any(feature = "rkyv", feature = "rkyv-16", feature = "rkyv-32", feature = "rkyv-64"))]
22use rkyv::{Archive, Deserialize, Serialize};
23
24/// The number of nanoseconds in a microsecond.
25const NANOS_PER_MICRO: i32 = 1000;
26/// The number of nanoseconds in a millisecond.
27const NANOS_PER_MILLI: i32 = 1_000_000;
28/// The number of nanoseconds in seconds.
29pub(crate) const NANOS_PER_SEC: i32 = 1_000_000_000;
30/// The number of microseconds per second.
31const MICROS_PER_SEC: i64 = 1_000_000;
32/// The number of milliseconds per second.
33const MILLIS_PER_SEC: i64 = 1000;
34/// The number of seconds in a minute.
35const SECS_PER_MINUTE: i64 = 60;
36/// The number of seconds in an hour.
37const SECS_PER_HOUR: i64 = 3600;
38/// The number of (non-leap) seconds in days.
39const SECS_PER_DAY: i64 = 86_400;
40/// The number of (non-leap) seconds in a week.
41const SECS_PER_WEEK: i64 = 604_800;
42
43/// Time duration with nanosecond precision.
44///
45/// This also allows for negative durations; see individual methods for details.
46///
47/// A `TimeDelta` is represented internally as a complement of seconds and
48/// nanoseconds. The range is restricted to that of `i64` milliseconds, with the
49/// minimum value notably being set to `-i64::MAX` rather than allowing the full
50/// range of `i64::MIN`. This is to allow easy flipping of sign, so that for
51/// instance `abs()` can be called without any checks.
52#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
53#[cfg_attr(
54    any(feature = "rkyv", feature = "rkyv-16", feature = "rkyv-32", feature = "rkyv-64"),
55    derive(Archive, Deserialize, Serialize),
56    archive(compare(PartialEq, PartialOrd)),
57    archive_attr(derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash))
58)]
59#[cfg_attr(feature = "rkyv-validation", archive(check_bytes))]
60pub struct TimeDelta {
61    secs: i64,
62    nanos: i32, // Always 0 <= nanos < NANOS_PER_SEC
63}
64
65/// The minimum possible `TimeDelta`: `-i64::MAX` milliseconds.
66pub(crate) const MIN: TimeDelta = TimeDelta {
67    secs: -i64::MAX / MILLIS_PER_SEC - 1,
68    nanos: NANOS_PER_SEC + (-i64::MAX % MILLIS_PER_SEC) as i32 * NANOS_PER_MILLI,
69};
70
71/// The maximum possible `TimeDelta`: `i64::MAX` milliseconds.
72pub(crate) const MAX: TimeDelta = TimeDelta {
73    secs: i64::MAX / MILLIS_PER_SEC,
74    nanos: (i64::MAX % MILLIS_PER_SEC) as i32 * NANOS_PER_MILLI,
75};
76
77impl TimeDelta {
78    /// Makes a new `TimeDelta` with given number of seconds and nanoseconds.
79    ///
80    /// # Errors
81    ///
82    /// Returns `None` when the duration is out of bounds, or if `nanos` ≥ 1,000,000,000.
83    pub const fn new(secs: i64, nanos: u32) -> Option<TimeDelta> {
84        if secs < MIN.secs
85            || secs > MAX.secs
86            || nanos >= 1_000_000_000
87            || (secs == MAX.secs && nanos > MAX.nanos as u32)
88            || (secs == MIN.secs && nanos < MIN.nanos as u32)
89        {
90            return None;
91        }
92        Some(TimeDelta { secs, nanos: nanos as i32 })
93    }
94
95    /// Makes a new `TimeDelta` with the given number of weeks.
96    ///
97    /// Equivalent to `TimeDelta::seconds(weeks * 7 * 24 * 60 * 60)` with
98    /// overflow checks.
99    ///
100    /// # Panics
101    ///
102    /// Panics when the duration is out of bounds.
103    #[inline]
104    #[must_use]
105    pub const fn weeks(weeks: i64) -> TimeDelta {
106        expect(TimeDelta::try_weeks(weeks), "TimeDelta::weeks out of bounds")
107    }
108
109    /// Makes a new `TimeDelta` with the given number of weeks.
110    ///
111    /// Equivalent to `TimeDelta::try_seconds(weeks * 7 * 24 * 60 * 60)` with
112    /// overflow checks.
113    ///
114    /// # Errors
115    ///
116    /// Returns `None` when the `TimeDelta` would be out of bounds.
117    #[inline]
118    pub const fn try_weeks(weeks: i64) -> Option<TimeDelta> {
119        TimeDelta::try_seconds(try_opt!(weeks.checked_mul(SECS_PER_WEEK)))
120    }
121
122    /// Makes a new `TimeDelta` with the given number of days.
123    ///
124    /// Equivalent to `TimeDelta::seconds(days * 24 * 60 * 60)` with overflow
125    /// checks.
126    ///
127    /// # Panics
128    ///
129    /// Panics when the `TimeDelta` would be out of bounds.
130    #[inline]
131    #[must_use]
132    pub const fn days(days: i64) -> TimeDelta {
133        expect(TimeDelta::try_days(days), "TimeDelta::days out of bounds")
134    }
135
136    /// Makes a new `TimeDelta` with the given number of days.
137    ///
138    /// Equivalent to `TimeDelta::try_seconds(days * 24 * 60 * 60)` with overflow
139    /// checks.
140    ///
141    /// # Errors
142    ///
143    /// Returns `None` when the `TimeDelta` would be out of bounds.
144    #[inline]
145    pub const fn try_days(days: i64) -> Option<TimeDelta> {
146        TimeDelta::try_seconds(try_opt!(days.checked_mul(SECS_PER_DAY)))
147    }
148
149    /// Makes a new `TimeDelta` with the given number of hours.
150    ///
151    /// Equivalent to `TimeDelta::seconds(hours * 60 * 60)` with overflow checks.
152    ///
153    /// # Panics
154    ///
155    /// Panics when the `TimeDelta` would be out of bounds.
156    #[inline]
157    #[must_use]
158    pub const fn hours(hours: i64) -> TimeDelta {
159        expect(TimeDelta::try_hours(hours), "TimeDelta::hours out of bounds")
160    }
161
162    /// Makes a new `TimeDelta` with the given number of hours.
163    ///
164    /// Equivalent to `TimeDelta::try_seconds(hours * 60 * 60)` with overflow checks.
165    ///
166    /// # Errors
167    ///
168    /// Returns `None` when the `TimeDelta` would be out of bounds.
169    #[inline]
170    pub const fn try_hours(hours: i64) -> Option<TimeDelta> {
171        TimeDelta::try_seconds(try_opt!(hours.checked_mul(SECS_PER_HOUR)))
172    }
173
174    /// Makes a new `TimeDelta` with the given number of minutes.
175    ///
176    /// Equivalent to `TimeDelta::seconds(minutes * 60)` with overflow checks.
177    ///
178    /// # Panics
179    ///
180    /// Panics when the `TimeDelta` would be out of bounds.
181    #[inline]
182    #[must_use]
183    pub const fn minutes(minutes: i64) -> TimeDelta {
184        expect(TimeDelta::try_minutes(minutes), "TimeDelta::minutes out of bounds")
185    }
186
187    /// Makes a new `TimeDelta` with the given number of minutes.
188    ///
189    /// Equivalent to `TimeDelta::try_seconds(minutes * 60)` with overflow checks.
190    ///
191    /// # Errors
192    ///
193    /// Returns `None` when the `TimeDelta` would be out of bounds.
194    #[inline]
195    pub const fn try_minutes(minutes: i64) -> Option<TimeDelta> {
196        TimeDelta::try_seconds(try_opt!(minutes.checked_mul(SECS_PER_MINUTE)))
197    }
198
199    /// Makes a new `TimeDelta` with the given number of seconds.
200    ///
201    /// # Panics
202    ///
203    /// Panics when `seconds` is more than `i64::MAX / 1_000` or less than `-i64::MAX / 1_000`
204    /// (in this context, this is the same as `i64::MIN / 1_000` due to rounding).
205    #[inline]
206    #[must_use]
207    pub const fn seconds(seconds: i64) -> TimeDelta {
208        expect(TimeDelta::try_seconds(seconds), "TimeDelta::seconds out of bounds")
209    }
210
211    /// Makes a new `TimeDelta` with the given number of seconds.
212    ///
213    /// # Errors
214    ///
215    /// Returns `None` when `seconds` is more than `i64::MAX / 1_000` or less than
216    /// `-i64::MAX / 1_000` (in this context, this is the same as `i64::MIN / 1_000` due to
217    /// rounding).
218    #[inline]
219    pub const fn try_seconds(seconds: i64) -> Option<TimeDelta> {
220        TimeDelta::new(seconds, 0)
221    }
222
223    /// Makes a new `TimeDelta` with the given number of milliseconds.
224    ///
225    /// # Panics
226    ///
227    /// Panics when the `TimeDelta` would be out of bounds, i.e. when `milliseconds` is more than
228    /// `i64::MAX` or less than `-i64::MAX`. Notably, this is not the same as `i64::MIN`.
229    #[inline]
230    pub const fn milliseconds(milliseconds: i64) -> TimeDelta {
231        expect(TimeDelta::try_milliseconds(milliseconds), "TimeDelta::milliseconds out of bounds")
232    }
233
234    /// Makes a new `TimeDelta` with the given number of milliseconds.
235    ///
236    /// # Errors
237    ///
238    /// Returns `None` the `TimeDelta` would be out of bounds, i.e. when `milliseconds` is more
239    /// than `i64::MAX` or less than `-i64::MAX`. Notably, this is not the same as `i64::MIN`.
240    #[inline]
241    pub const fn try_milliseconds(milliseconds: i64) -> Option<TimeDelta> {
242        // We don't need to compare against MAX, as this function accepts an
243        // i64, and MAX is aligned to i64::MAX milliseconds.
244        if milliseconds < -i64::MAX {
245            return None;
246        }
247        let (secs, millis) = div_mod_floor_64(milliseconds, MILLIS_PER_SEC);
248        let d = TimeDelta { secs, nanos: millis as i32 * NANOS_PER_MILLI };
249        Some(d)
250    }
251
252    /// Makes a new `TimeDelta` with the given number of microseconds.
253    ///
254    /// The number of microseconds acceptable by this constructor is less than
255    /// the total number that can actually be stored in a `TimeDelta`, so it is
256    /// not possible to specify a value that would be out of bounds. This
257    /// function is therefore infallible.
258    #[inline]
259    pub const fn microseconds(microseconds: i64) -> TimeDelta {
260        let (secs, micros) = div_mod_floor_64(microseconds, MICROS_PER_SEC);
261        let nanos = micros as i32 * NANOS_PER_MICRO;
262        TimeDelta { secs, nanos }
263    }
264
265    /// Makes a new `TimeDelta` with the given number of nanoseconds.
266    ///
267    /// The number of nanoseconds acceptable by this constructor is less than
268    /// the total number that can actually be stored in a `TimeDelta`, so it is
269    /// not possible to specify a value that would be out of bounds. This
270    /// function is therefore infallible.
271    #[inline]
272    pub const fn nanoseconds(nanos: i64) -> TimeDelta {
273        let (secs, nanos) = div_mod_floor_64(nanos, NANOS_PER_SEC as i64);
274        TimeDelta { secs, nanos: nanos as i32 }
275    }
276
277    /// Returns the total number of whole weeks in the `TimeDelta`.
278    #[inline]
279    pub const fn num_weeks(&self) -> i64 {
280        self.num_days() / 7
281    }
282
283    /// Returns the total number of whole days in the `TimeDelta`.
284    pub const fn num_days(&self) -> i64 {
285        self.num_seconds() / SECS_PER_DAY
286    }
287
288    /// Returns the total number of whole hours in the `TimeDelta`.
289    #[inline]
290    pub const fn num_hours(&self) -> i64 {
291        self.num_seconds() / SECS_PER_HOUR
292    }
293
294    /// Returns the total number of whole minutes in the `TimeDelta`.
295    #[inline]
296    pub const fn num_minutes(&self) -> i64 {
297        self.num_seconds() / SECS_PER_MINUTE
298    }
299
300    /// Returns the total number of whole seconds in the `TimeDelta`.
301    pub const fn num_seconds(&self) -> i64 {
302        // If secs is negative, nanos should be subtracted from the duration.
303        if self.secs < 0 && self.nanos > 0 {
304            self.secs + 1
305        } else {
306            self.secs
307        }
308    }
309
310    /// Returns the number of nanoseconds such that
311    /// `subsec_nanos() + num_seconds() * NANOS_PER_SEC` is the total number of
312    /// nanoseconds in the `TimeDelta`.
313    pub const fn subsec_nanos(&self) -> i32 {
314        if self.secs < 0 && self.nanos > 0 {
315            self.nanos - NANOS_PER_SEC
316        } else {
317            self.nanos
318        }
319    }
320
321    /// Returns the total number of whole milliseconds in the `TimeDelta`.
322    pub const fn num_milliseconds(&self) -> i64 {
323        // A proper TimeDelta will not overflow, because MIN and MAX are defined such
324        // that the range is within the bounds of an i64, from -i64::MAX through to
325        // +i64::MAX inclusive. Notably, i64::MIN is excluded from this range.
326        let secs_part = self.num_seconds() * MILLIS_PER_SEC;
327        let nanos_part = self.subsec_nanos() / NANOS_PER_MILLI;
328        secs_part + nanos_part as i64
329    }
330
331    /// Returns the total number of whole microseconds in the `TimeDelta`,
332    /// or `None` on overflow (exceeding 2^63 microseconds in either direction).
333    pub const fn num_microseconds(&self) -> Option<i64> {
334        let secs_part = try_opt!(self.num_seconds().checked_mul(MICROS_PER_SEC));
335        let nanos_part = self.subsec_nanos() / NANOS_PER_MICRO;
336        secs_part.checked_add(nanos_part as i64)
337    }
338
339    /// Returns the total number of whole nanoseconds in the `TimeDelta`,
340    /// or `None` on overflow (exceeding 2^63 nanoseconds in either direction).
341    pub const fn num_nanoseconds(&self) -> Option<i64> {
342        let secs_part = try_opt!(self.num_seconds().checked_mul(NANOS_PER_SEC as i64));
343        let nanos_part = self.subsec_nanos();
344        secs_part.checked_add(nanos_part as i64)
345    }
346
347    /// Add two `TimeDelta`s, returning `None` if overflow occurred.
348    #[must_use]
349    pub const fn checked_add(&self, rhs: &TimeDelta) -> Option<TimeDelta> {
350        // No overflow checks here because we stay comfortably within the range of an `i64`.
351        // Range checks happen in `TimeDelta::new`.
352        let mut secs = self.secs + rhs.secs;
353        let mut nanos = self.nanos + rhs.nanos;
354        if nanos >= NANOS_PER_SEC {
355            nanos -= NANOS_PER_SEC;
356            secs += 1;
357        }
358        TimeDelta::new(secs, nanos as u32)
359    }
360
361    /// Subtract two `TimeDelta`s, returning `None` if overflow occurred.
362    #[must_use]
363    pub const fn checked_sub(&self, rhs: &TimeDelta) -> Option<TimeDelta> {
364        // No overflow checks here because we stay comfortably within the range of an `i64`.
365        // Range checks happen in `TimeDelta::new`.
366        let mut secs = self.secs - rhs.secs;
367        let mut nanos = self.nanos - rhs.nanos;
368        if nanos < 0 {
369            nanos += NANOS_PER_SEC;
370            secs -= 1;
371        }
372        TimeDelta::new(secs, nanos as u32)
373    }
374
375    /// Multiply a `TimeDelta` with a i32, returning `None` if overflow occurred.
376    #[must_use]
377    pub const fn checked_mul(&self, rhs: i32) -> Option<TimeDelta> {
378        // Multiply nanoseconds as i64, because it cannot overflow that way.
379        let total_nanos = self.nanos as i64 * rhs as i64;
380        let (extra_secs, nanos) = div_mod_floor_64(total_nanos, NANOS_PER_SEC as i64);
381        // Multiply seconds as i128 to prevent overflow
382        let secs: i128 = self.secs as i128 * rhs as i128 + extra_secs as i128;
383        if secs <= i64::MIN as i128 || secs >= i64::MAX as i128 {
384            return None;
385        };
386        Some(TimeDelta { secs: secs as i64, nanos: nanos as i32 })
387    }
388
389    /// Divide a `TimeDelta` with a i32, returning `None` if dividing by 0.
390    #[must_use]
391    pub const fn checked_div(&self, rhs: i32) -> Option<TimeDelta> {
392        if rhs == 0 {
393            return None;
394        }
395        let secs = self.secs / rhs as i64;
396        let carry = self.secs % rhs as i64;
397        let extra_nanos = carry * NANOS_PER_SEC as i64 / rhs as i64;
398        let nanos = self.nanos / rhs + extra_nanos as i32;
399
400        let (secs, nanos) = match nanos {
401            i32::MIN..=-1 => (secs - 1, nanos + NANOS_PER_SEC),
402            NANOS_PER_SEC..=i32::MAX => (secs + 1, nanos - NANOS_PER_SEC),
403            _ => (secs, nanos),
404        };
405
406        Some(TimeDelta { secs, nanos })
407    }
408
409    /// Returns the `TimeDelta` as an absolute (non-negative) value.
410    #[inline]
411    pub const fn abs(&self) -> TimeDelta {
412        if self.secs < 0 && self.nanos != 0 {
413            TimeDelta { secs: (self.secs + 1).abs(), nanos: NANOS_PER_SEC - self.nanos }
414        } else {
415            TimeDelta { secs: self.secs.abs(), nanos: self.nanos }
416        }
417    }
418
419    /// The minimum possible `TimeDelta`: `-i64::MAX` milliseconds.
420    #[inline]
421    pub const fn min_value() -> TimeDelta {
422        MIN
423    }
424
425    /// The maximum possible `TimeDelta`: `i64::MAX` milliseconds.
426    #[inline]
427    pub const fn max_value() -> TimeDelta {
428        MAX
429    }
430
431    /// A `TimeDelta` where the stored seconds and nanoseconds are equal to zero.
432    #[inline]
433    pub const fn zero() -> TimeDelta {
434        TimeDelta { secs: 0, nanos: 0 }
435    }
436
437    /// Returns `true` if the `TimeDelta` equals `TimeDelta::zero()`.
438    #[inline]
439    pub const fn is_zero(&self) -> bool {
440        self.secs == 0 && self.nanos == 0
441    }
442
443    /// Creates a `TimeDelta` object from `std::time::Duration`
444    ///
445    /// This function errors when original duration is larger than the maximum
446    /// value supported for this type.
447    pub const fn from_std(duration: Duration) -> Result<TimeDelta, OutOfRangeError> {
448        // We need to check secs as u64 before coercing to i64
449        if duration.as_secs() > MAX.secs as u64 {
450            return Err(OutOfRangeError(()));
451        }
452        match TimeDelta::new(duration.as_secs() as i64, duration.subsec_nanos()) {
453            Some(d) => Ok(d),
454            None => Err(OutOfRangeError(())),
455        }
456    }
457
458    /// Creates a `std::time::Duration` object from a `TimeDelta`.
459    ///
460    /// This function errors when duration is less than zero. As standard
461    /// library implementation is limited to non-negative values.
462    pub const fn to_std(&self) -> Result<Duration, OutOfRangeError> {
463        if self.secs < 0 {
464            return Err(OutOfRangeError(()));
465        }
466        Ok(Duration::new(self.secs as u64, self.nanos as u32))
467    }
468
469    /// This duplicates `Neg::neg` because trait methods can't be const yet.
470    pub(crate) const fn neg(self) -> TimeDelta {
471        let (secs_diff, nanos) = match self.nanos {
472            0 => (0, 0),
473            nanos => (1, NANOS_PER_SEC - nanos),
474        };
475        TimeDelta { secs: -self.secs - secs_diff, nanos }
476    }
477}
478
479impl Neg for TimeDelta {
480    type Output = TimeDelta;
481
482    #[inline]
483    fn neg(self) -> TimeDelta {
484        let (secs_diff, nanos) = match self.nanos {
485            0 => (0, 0),
486            nanos => (1, NANOS_PER_SEC - nanos),
487        };
488        TimeDelta { secs: -self.secs - secs_diff, nanos }
489    }
490}
491
492impl Add for TimeDelta {
493    type Output = TimeDelta;
494
495    fn add(self, rhs: TimeDelta) -> TimeDelta {
496        self.checked_add(&rhs).expect("`TimeDelta + TimeDelta` overflowed")
497    }
498}
499
500impl Sub for TimeDelta {
501    type Output = TimeDelta;
502
503    fn sub(self, rhs: TimeDelta) -> TimeDelta {
504        self.checked_sub(&rhs).expect("`TimeDelta - TimeDelta` overflowed")
505    }
506}
507
508impl AddAssign for TimeDelta {
509    fn add_assign(&mut self, rhs: TimeDelta) {
510        let new = self.checked_add(&rhs).expect("`TimeDelta + TimeDelta` overflowed");
511        *self = new;
512    }
513}
514
515impl SubAssign for TimeDelta {
516    fn sub_assign(&mut self, rhs: TimeDelta) {
517        let new = self.checked_sub(&rhs).expect("`TimeDelta - TimeDelta` overflowed");
518        *self = new;
519    }
520}
521
522impl Mul<i32> for TimeDelta {
523    type Output = TimeDelta;
524
525    fn mul(self, rhs: i32) -> TimeDelta {
526        self.checked_mul(rhs).expect("`TimeDelta * i32` overflowed")
527    }
528}
529
530impl Div<i32> for TimeDelta {
531    type Output = TimeDelta;
532
533    fn div(self, rhs: i32) -> TimeDelta {
534        self.checked_div(rhs).expect("`i32` is zero")
535    }
536}
537
538impl<'a> core::iter::Sum<&'a TimeDelta> for TimeDelta {
539    fn sum<I: Iterator<Item = &'a TimeDelta>>(iter: I) -> TimeDelta {
540        iter.fold(TimeDelta::zero(), |acc, x| acc + *x)
541    }
542}
543
544impl core::iter::Sum<TimeDelta> for TimeDelta {
545    fn sum<I: Iterator<Item = TimeDelta>>(iter: I) -> TimeDelta {
546        iter.fold(TimeDelta::zero(), |acc, x| acc + x)
547    }
548}
549
550impl fmt::Display for TimeDelta {
551    /// Format a `TimeDelta` using the [ISO 8601] format
552    ///
553    /// [ISO 8601]: https://en.wikipedia.org/wiki/ISO_8601#Durations
554    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
555        // technically speaking, negative duration is not valid ISO 8601,
556        // but we need to print it anyway.
557        let (abs, sign) = if self.secs < 0 { (-*self, "-") } else { (*self, "") };
558
559        write!(f, "{}P", sign)?;
560        // Plenty of ways to encode an empty string. `P0D` is short and not too strange.
561        if abs.secs == 0 && abs.nanos == 0 {
562            return f.write_str("0D");
563        }
564
565        f.write_fmt(format_args!("T{}", abs.secs))?;
566
567        if abs.nanos > 0 {
568            // Count the number of significant digits, while removing all trailing zero's.
569            let mut figures = 9usize;
570            let mut fraction_digits = abs.nanos;
571            loop {
572                let div = fraction_digits / 10;
573                let last_digit = fraction_digits % 10;
574                if last_digit != 0 {
575                    break;
576                }
577                fraction_digits = div;
578                figures -= 1;
579            }
580            f.write_fmt(format_args!(".{:01$}", fraction_digits, figures))?;
581        }
582        f.write_str("S")?;
583        Ok(())
584    }
585}
586
587/// Represents error when converting `TimeDelta` to/from a standard library
588/// implementation
589///
590/// The `std::time::Duration` supports a range from zero to `u64::MAX`
591/// *seconds*, while this module supports signed range of up to
592/// `i64::MAX` of *milliseconds*.
593#[derive(Debug, Clone, Copy, PartialEq, Eq)]
594pub struct OutOfRangeError(());
595
596impl fmt::Display for OutOfRangeError {
597    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
598        write!(f, "Source duration value is out of range for the target type")
599    }
600}
601
602#[cfg(feature = "std")]
603impl Error for OutOfRangeError {
604    #[allow(deprecated)]
605    fn description(&self) -> &str {
606        "out of range error"
607    }
608}
609
610#[inline]
611const fn div_mod_floor_64(this: i64, other: i64) -> (i64, i64) {
612    (this.div_euclid(other), this.rem_euclid(other))
613}
614
615#[cfg(all(feature = "arbitrary", feature = "std"))]
616impl arbitrary::Arbitrary<'_> for TimeDelta {
617    fn arbitrary(u: &mut arbitrary::Unstructured) -> arbitrary::Result<TimeDelta> {
618        const MIN_SECS: i64 = -i64::MAX / MILLIS_PER_SEC - 1;
619        const MAX_SECS: i64 = i64::MAX / MILLIS_PER_SEC;
620
621        let secs: i64 = u.int_in_range(MIN_SECS..=MAX_SECS)?;
622        let nanos: i32 = u.int_in_range(0..=(NANOS_PER_SEC - 1))?;
623        let duration = TimeDelta { secs, nanos };
624
625        if duration < MIN || duration > MAX {
626            Err(arbitrary::Error::IncorrectFormat)
627        } else {
628            Ok(duration)
629        }
630    }
631}
632
633#[cfg(test)]
634mod tests {
635    use super::OutOfRangeError;
636    use super::{TimeDelta, MAX, MIN};
637    use crate::expect;
638    use core::time::Duration;
639
640    #[test]
641    fn test_duration() {
642        let days = |d| TimeDelta::try_days(d).unwrap();
643        let seconds = |s| TimeDelta::try_seconds(s).unwrap();
644
645        assert!(seconds(1) != TimeDelta::zero());
646        assert_eq!(seconds(1) + seconds(2), seconds(3));
647        assert_eq!(seconds(86_399) + seconds(4), days(1) + seconds(3));
648        assert_eq!(days(10) - seconds(1000), seconds(863_000));
649        assert_eq!(days(10) - seconds(1_000_000), seconds(-136_000));
650        assert_eq!(
651            days(2) + seconds(86_399) + TimeDelta::nanoseconds(1_234_567_890),
652            days(3) + TimeDelta::nanoseconds(234_567_890)
653        );
654        assert_eq!(-days(3), days(-3));
655        assert_eq!(-(days(3) + seconds(70)), days(-4) + seconds(86_400 - 70));
656
657        let mut d = TimeDelta::default();
658        d += TimeDelta::try_minutes(1).unwrap();
659        d -= seconds(30);
660        assert_eq!(d, seconds(30));
661    }
662
663    #[test]
664    fn test_duration_num_days() {
665        assert_eq!(TimeDelta::zero().num_days(), 0);
666        assert_eq!(TimeDelta::try_days(1).unwrap().num_days(), 1);
667        assert_eq!(TimeDelta::try_days(-1).unwrap().num_days(), -1);
668        assert_eq!(TimeDelta::try_seconds(86_399).unwrap().num_days(), 0);
669        assert_eq!(TimeDelta::try_seconds(86_401).unwrap().num_days(), 1);
670        assert_eq!(TimeDelta::try_seconds(-86_399).unwrap().num_days(), 0);
671        assert_eq!(TimeDelta::try_seconds(-86_401).unwrap().num_days(), -1);
672        assert_eq!(TimeDelta::try_days(i32::MAX as i64).unwrap().num_days(), i32::MAX as i64);
673        assert_eq!(TimeDelta::try_days(i32::MIN as i64).unwrap().num_days(), i32::MIN as i64);
674    }
675
676    #[test]
677    fn test_duration_num_seconds() {
678        assert_eq!(TimeDelta::zero().num_seconds(), 0);
679        assert_eq!(TimeDelta::try_seconds(1).unwrap().num_seconds(), 1);
680        assert_eq!(TimeDelta::try_seconds(-1).unwrap().num_seconds(), -1);
681        assert_eq!(TimeDelta::try_milliseconds(999).unwrap().num_seconds(), 0);
682        assert_eq!(TimeDelta::try_milliseconds(1001).unwrap().num_seconds(), 1);
683        assert_eq!(TimeDelta::try_milliseconds(-999).unwrap().num_seconds(), 0);
684        assert_eq!(TimeDelta::try_milliseconds(-1001).unwrap().num_seconds(), -1);
685    }
686
687    #[test]
688    fn test_duration_seconds_max_allowed() {
689        let duration = TimeDelta::try_seconds(i64::MAX / 1_000).unwrap();
690        assert_eq!(duration.num_seconds(), i64::MAX / 1_000);
691        assert_eq!(
692            duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
693            i64::MAX as i128 / 1_000 * 1_000_000_000
694        );
695    }
696
697    #[test]
698    fn test_duration_seconds_max_overflow() {
699        assert!(TimeDelta::try_seconds(i64::MAX / 1_000 + 1).is_none());
700    }
701
702    #[test]
703    #[should_panic(expected = "TimeDelta::seconds out of bounds")]
704    fn test_duration_seconds_max_overflow_panic() {
705        let _ = TimeDelta::seconds(i64::MAX / 1_000 + 1);
706    }
707
708    #[test]
709    fn test_duration_seconds_min_allowed() {
710        let duration = TimeDelta::try_seconds(i64::MIN / 1_000).unwrap(); // Same as -i64::MAX / 1_000 due to rounding
711        assert_eq!(duration.num_seconds(), i64::MIN / 1_000); // Same as -i64::MAX / 1_000 due to rounding
712        assert_eq!(
713            duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
714            -i64::MAX as i128 / 1_000 * 1_000_000_000
715        );
716    }
717
718    #[test]
719    fn test_duration_seconds_min_underflow() {
720        assert!(TimeDelta::try_seconds(-i64::MAX / 1_000 - 1).is_none());
721    }
722
723    #[test]
724    #[should_panic(expected = "TimeDelta::seconds out of bounds")]
725    fn test_duration_seconds_min_underflow_panic() {
726        let _ = TimeDelta::seconds(-i64::MAX / 1_000 - 1);
727    }
728
729    #[test]
730    fn test_duration_num_milliseconds() {
731        assert_eq!(TimeDelta::zero().num_milliseconds(), 0);
732        assert_eq!(TimeDelta::try_milliseconds(1).unwrap().num_milliseconds(), 1);
733        assert_eq!(TimeDelta::try_milliseconds(-1).unwrap().num_milliseconds(), -1);
734        assert_eq!(TimeDelta::microseconds(999).num_milliseconds(), 0);
735        assert_eq!(TimeDelta::microseconds(1001).num_milliseconds(), 1);
736        assert_eq!(TimeDelta::microseconds(-999).num_milliseconds(), 0);
737        assert_eq!(TimeDelta::microseconds(-1001).num_milliseconds(), -1);
738    }
739
740    #[test]
741    fn test_duration_milliseconds_max_allowed() {
742        // The maximum number of milliseconds acceptable through the constructor is
743        // equal to the number that can be stored in a TimeDelta.
744        let duration = TimeDelta::try_milliseconds(i64::MAX).unwrap();
745        assert_eq!(duration.num_milliseconds(), i64::MAX);
746        assert_eq!(
747            duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
748            i64::MAX as i128 * 1_000_000
749        );
750    }
751
752    #[test]
753    fn test_duration_milliseconds_max_overflow() {
754        // Here we ensure that trying to add one millisecond to the maximum storable
755        // value will fail.
756        assert!(TimeDelta::try_milliseconds(i64::MAX)
757            .unwrap()
758            .checked_add(&TimeDelta::try_milliseconds(1).unwrap())
759            .is_none());
760    }
761
762    #[test]
763    fn test_duration_milliseconds_min_allowed() {
764        // The minimum number of milliseconds acceptable through the constructor is
765        // not equal to the number that can be stored in a TimeDelta - there is a
766        // difference of one (i64::MIN vs -i64::MAX).
767        let duration = TimeDelta::try_milliseconds(-i64::MAX).unwrap();
768        assert_eq!(duration.num_milliseconds(), -i64::MAX);
769        assert_eq!(
770            duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
771            -i64::MAX as i128 * 1_000_000
772        );
773    }
774
775    #[test]
776    fn test_duration_milliseconds_min_underflow() {
777        // Here we ensure that trying to subtract one millisecond from the minimum
778        // storable value will fail.
779        assert!(TimeDelta::try_milliseconds(-i64::MAX)
780            .unwrap()
781            .checked_sub(&TimeDelta::try_milliseconds(1).unwrap())
782            .is_none());
783    }
784
785    #[test]
786    #[should_panic(expected = "TimeDelta::milliseconds out of bounds")]
787    fn test_duration_milliseconds_min_underflow_panic() {
788        // Here we ensure that trying to create a value one millisecond below the
789        // minimum storable value will fail. This test is necessary because the
790        // storable range is -i64::MAX, but the constructor type of i64 will allow
791        // i64::MIN, which is one value below.
792        let _ = TimeDelta::milliseconds(i64::MIN); // Same as -i64::MAX - 1
793    }
794
795    #[test]
796    fn test_duration_num_microseconds() {
797        assert_eq!(TimeDelta::zero().num_microseconds(), Some(0));
798        assert_eq!(TimeDelta::microseconds(1).num_microseconds(), Some(1));
799        assert_eq!(TimeDelta::microseconds(-1).num_microseconds(), Some(-1));
800        assert_eq!(TimeDelta::nanoseconds(999).num_microseconds(), Some(0));
801        assert_eq!(TimeDelta::nanoseconds(1001).num_microseconds(), Some(1));
802        assert_eq!(TimeDelta::nanoseconds(-999).num_microseconds(), Some(0));
803        assert_eq!(TimeDelta::nanoseconds(-1001).num_microseconds(), Some(-1));
804
805        // overflow checks
806        const MICROS_PER_DAY: i64 = 86_400_000_000;
807        assert_eq!(
808            TimeDelta::try_days(i64::MAX / MICROS_PER_DAY).unwrap().num_microseconds(),
809            Some(i64::MAX / MICROS_PER_DAY * MICROS_PER_DAY)
810        );
811        assert_eq!(
812            TimeDelta::try_days(-i64::MAX / MICROS_PER_DAY).unwrap().num_microseconds(),
813            Some(-i64::MAX / MICROS_PER_DAY * MICROS_PER_DAY)
814        );
815        assert_eq!(
816            TimeDelta::try_days(i64::MAX / MICROS_PER_DAY + 1).unwrap().num_microseconds(),
817            None
818        );
819        assert_eq!(
820            TimeDelta::try_days(-i64::MAX / MICROS_PER_DAY - 1).unwrap().num_microseconds(),
821            None
822        );
823    }
824    #[test]
825    fn test_duration_microseconds_max_allowed() {
826        // The number of microseconds acceptable through the constructor is far
827        // fewer than the number that can actually be stored in a TimeDelta, so this
828        // is not a particular insightful test.
829        let duration = TimeDelta::microseconds(i64::MAX);
830        assert_eq!(duration.num_microseconds(), Some(i64::MAX));
831        assert_eq!(
832            duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
833            i64::MAX as i128 * 1_000
834        );
835        // Here we create a TimeDelta with the maximum possible number of
836        // microseconds by creating a TimeDelta with the maximum number of
837        // milliseconds and then checking that the number of microseconds matches
838        // the storage limit.
839        let duration = TimeDelta::try_milliseconds(i64::MAX).unwrap();
840        assert!(duration.num_microseconds().is_none());
841        assert_eq!(
842            duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
843            i64::MAX as i128 * 1_000_000
844        );
845    }
846    #[test]
847    fn test_duration_microseconds_max_overflow() {
848        // This test establishes that a TimeDelta can store more microseconds than
849        // are representable through the return of duration.num_microseconds().
850        let duration = TimeDelta::microseconds(i64::MAX) + TimeDelta::microseconds(1);
851        assert!(duration.num_microseconds().is_none());
852        assert_eq!(
853            duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
854            (i64::MAX as i128 + 1) * 1_000
855        );
856        // Here we ensure that trying to add one microsecond to the maximum storable
857        // value will fail.
858        assert!(TimeDelta::try_milliseconds(i64::MAX)
859            .unwrap()
860            .checked_add(&TimeDelta::microseconds(1))
861            .is_none());
862    }
863    #[test]
864    fn test_duration_microseconds_min_allowed() {
865        // The number of microseconds acceptable through the constructor is far
866        // fewer than the number that can actually be stored in a TimeDelta, so this
867        // is not a particular insightful test.
868        let duration = TimeDelta::microseconds(i64::MIN);
869        assert_eq!(duration.num_microseconds(), Some(i64::MIN));
870        assert_eq!(
871            duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
872            i64::MIN as i128 * 1_000
873        );
874        // Here we create a TimeDelta with the minimum possible number of
875        // microseconds by creating a TimeDelta with the minimum number of
876        // milliseconds and then checking that the number of microseconds matches
877        // the storage limit.
878        let duration = TimeDelta::try_milliseconds(-i64::MAX).unwrap();
879        assert!(duration.num_microseconds().is_none());
880        assert_eq!(
881            duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
882            -i64::MAX as i128 * 1_000_000
883        );
884    }
885    #[test]
886    fn test_duration_microseconds_min_underflow() {
887        // This test establishes that a TimeDelta can store more microseconds than
888        // are representable through the return of duration.num_microseconds().
889        let duration = TimeDelta::microseconds(i64::MIN) - TimeDelta::microseconds(1);
890        assert!(duration.num_microseconds().is_none());
891        assert_eq!(
892            duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
893            (i64::MIN as i128 - 1) * 1_000
894        );
895        // Here we ensure that trying to subtract one microsecond from the minimum
896        // storable value will fail.
897        assert!(TimeDelta::try_milliseconds(-i64::MAX)
898            .unwrap()
899            .checked_sub(&TimeDelta::microseconds(1))
900            .is_none());
901    }
902
903    #[test]
904    fn test_duration_num_nanoseconds() {
905        assert_eq!(TimeDelta::zero().num_nanoseconds(), Some(0));
906        assert_eq!(TimeDelta::nanoseconds(1).num_nanoseconds(), Some(1));
907        assert_eq!(TimeDelta::nanoseconds(-1).num_nanoseconds(), Some(-1));
908
909        // overflow checks
910        const NANOS_PER_DAY: i64 = 86_400_000_000_000;
911        assert_eq!(
912            TimeDelta::try_days(i64::MAX / NANOS_PER_DAY).unwrap().num_nanoseconds(),
913            Some(i64::MAX / NANOS_PER_DAY * NANOS_PER_DAY)
914        );
915        assert_eq!(
916            TimeDelta::try_days(-i64::MAX / NANOS_PER_DAY).unwrap().num_nanoseconds(),
917            Some(-i64::MAX / NANOS_PER_DAY * NANOS_PER_DAY)
918        );
919        assert_eq!(
920            TimeDelta::try_days(i64::MAX / NANOS_PER_DAY + 1).unwrap().num_nanoseconds(),
921            None
922        );
923        assert_eq!(
924            TimeDelta::try_days(-i64::MAX / NANOS_PER_DAY - 1).unwrap().num_nanoseconds(),
925            None
926        );
927    }
928    #[test]
929    fn test_duration_nanoseconds_max_allowed() {
930        // The number of nanoseconds acceptable through the constructor is far fewer
931        // than the number that can actually be stored in a TimeDelta, so this is not
932        // a particular insightful test.
933        let duration = TimeDelta::nanoseconds(i64::MAX);
934        assert_eq!(duration.num_nanoseconds(), Some(i64::MAX));
935        assert_eq!(
936            duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
937            i64::MAX as i128
938        );
939        // Here we create a TimeDelta with the maximum possible number of nanoseconds
940        // by creating a TimeDelta with the maximum number of milliseconds and then
941        // checking that the number of nanoseconds matches the storage limit.
942        let duration = TimeDelta::try_milliseconds(i64::MAX).unwrap();
943        assert!(duration.num_nanoseconds().is_none());
944        assert_eq!(
945            duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
946            i64::MAX as i128 * 1_000_000
947        );
948    }
949
950    #[test]
951    fn test_duration_nanoseconds_max_overflow() {
952        // This test establishes that a TimeDelta can store more nanoseconds than are
953        // representable through the return of duration.num_nanoseconds().
954        let duration = TimeDelta::nanoseconds(i64::MAX) + TimeDelta::nanoseconds(1);
955        assert!(duration.num_nanoseconds().is_none());
956        assert_eq!(
957            duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
958            i64::MAX as i128 + 1
959        );
960        // Here we ensure that trying to add one nanosecond to the maximum storable
961        // value will fail.
962        assert!(TimeDelta::try_milliseconds(i64::MAX)
963            .unwrap()
964            .checked_add(&TimeDelta::nanoseconds(1))
965            .is_none());
966    }
967
968    #[test]
969    fn test_duration_nanoseconds_min_allowed() {
970        // The number of nanoseconds acceptable through the constructor is far fewer
971        // than the number that can actually be stored in a TimeDelta, so this is not
972        // a particular insightful test.
973        let duration = TimeDelta::nanoseconds(i64::MIN);
974        assert_eq!(duration.num_nanoseconds(), Some(i64::MIN));
975        assert_eq!(
976            duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
977            i64::MIN as i128
978        );
979        // Here we create a TimeDelta with the minimum possible number of nanoseconds
980        // by creating a TimeDelta with the minimum number of milliseconds and then
981        // checking that the number of nanoseconds matches the storage limit.
982        let duration = TimeDelta::try_milliseconds(-i64::MAX).unwrap();
983        assert!(duration.num_nanoseconds().is_none());
984        assert_eq!(
985            duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
986            -i64::MAX as i128 * 1_000_000
987        );
988    }
989
990    #[test]
991    fn test_duration_nanoseconds_min_underflow() {
992        // This test establishes that a TimeDelta can store more nanoseconds than are
993        // representable through the return of duration.num_nanoseconds().
994        let duration = TimeDelta::nanoseconds(i64::MIN) - TimeDelta::nanoseconds(1);
995        assert!(duration.num_nanoseconds().is_none());
996        assert_eq!(
997            duration.secs as i128 * 1_000_000_000 + duration.nanos as i128,
998            i64::MIN as i128 - 1
999        );
1000        // Here we ensure that trying to subtract one nanosecond from the minimum
1001        // storable value will fail.
1002        assert!(TimeDelta::try_milliseconds(-i64::MAX)
1003            .unwrap()
1004            .checked_sub(&TimeDelta::nanoseconds(1))
1005            .is_none());
1006    }
1007
1008    #[test]
1009    fn test_max() {
1010        assert_eq!(
1011            MAX.secs as i128 * 1_000_000_000 + MAX.nanos as i128,
1012            i64::MAX as i128 * 1_000_000
1013        );
1014        assert_eq!(MAX, TimeDelta::try_milliseconds(i64::MAX).unwrap());
1015        assert_eq!(MAX.num_milliseconds(), i64::MAX);
1016        assert_eq!(MAX.num_microseconds(), None);
1017        assert_eq!(MAX.num_nanoseconds(), None);
1018    }
1019
1020    #[test]
1021    fn test_min() {
1022        assert_eq!(
1023            MIN.secs as i128 * 1_000_000_000 + MIN.nanos as i128,
1024            -i64::MAX as i128 * 1_000_000
1025        );
1026        assert_eq!(MIN, TimeDelta::try_milliseconds(-i64::MAX).unwrap());
1027        assert_eq!(MIN.num_milliseconds(), -i64::MAX);
1028        assert_eq!(MIN.num_microseconds(), None);
1029        assert_eq!(MIN.num_nanoseconds(), None);
1030    }
1031
1032    #[test]
1033    fn test_duration_ord() {
1034        let milliseconds = |ms| TimeDelta::try_milliseconds(ms).unwrap();
1035
1036        assert!(milliseconds(1) < milliseconds(2));
1037        assert!(milliseconds(2) > milliseconds(1));
1038        assert!(milliseconds(-1) > milliseconds(-2));
1039        assert!(milliseconds(-2) < milliseconds(-1));
1040        assert!(milliseconds(-1) < milliseconds(1));
1041        assert!(milliseconds(1) > milliseconds(-1));
1042        assert!(milliseconds(0) < milliseconds(1));
1043        assert!(milliseconds(0) > milliseconds(-1));
1044        assert!(milliseconds(1_001) < milliseconds(1_002));
1045        assert!(milliseconds(-1_001) > milliseconds(-1_002));
1046        assert!(TimeDelta::nanoseconds(1_234_567_890) < TimeDelta::nanoseconds(1_234_567_891));
1047        assert!(TimeDelta::nanoseconds(-1_234_567_890) > TimeDelta::nanoseconds(-1_234_567_891));
1048        assert!(milliseconds(i64::MAX) > milliseconds(i64::MAX - 1));
1049        assert!(milliseconds(-i64::MAX) < milliseconds(-i64::MAX + 1));
1050    }
1051
1052    #[test]
1053    fn test_duration_checked_ops() {
1054        let milliseconds = |ms| TimeDelta::try_milliseconds(ms).unwrap();
1055        let seconds = |s| TimeDelta::try_seconds(s).unwrap();
1056
1057        assert_eq!(
1058            milliseconds(i64::MAX).checked_add(&milliseconds(0)),
1059            Some(milliseconds(i64::MAX))
1060        );
1061        assert_eq!(
1062            milliseconds(i64::MAX - 1).checked_add(&TimeDelta::microseconds(999)),
1063            Some(milliseconds(i64::MAX - 2) + TimeDelta::microseconds(1999))
1064        );
1065        assert!(milliseconds(i64::MAX).checked_add(&TimeDelta::microseconds(1000)).is_none());
1066        assert!(milliseconds(i64::MAX).checked_add(&TimeDelta::nanoseconds(1)).is_none());
1067
1068        assert_eq!(
1069            milliseconds(-i64::MAX).checked_sub(&milliseconds(0)),
1070            Some(milliseconds(-i64::MAX))
1071        );
1072        assert_eq!(
1073            milliseconds(-i64::MAX + 1).checked_sub(&TimeDelta::microseconds(999)),
1074            Some(milliseconds(-i64::MAX + 2) - TimeDelta::microseconds(1999))
1075        );
1076        assert!(milliseconds(-i64::MAX).checked_sub(&milliseconds(1)).is_none());
1077        assert!(milliseconds(-i64::MAX).checked_sub(&TimeDelta::nanoseconds(1)).is_none());
1078
1079        assert!(seconds(i64::MAX / 1000).checked_mul(2000).is_none());
1080        assert!(seconds(i64::MIN / 1000).checked_mul(2000).is_none());
1081        assert!(seconds(1).checked_div(0).is_none());
1082    }
1083
1084    #[test]
1085    fn test_duration_abs() {
1086        let milliseconds = |ms| TimeDelta::try_milliseconds(ms).unwrap();
1087
1088        assert_eq!(milliseconds(1300).abs(), milliseconds(1300));
1089        assert_eq!(milliseconds(1000).abs(), milliseconds(1000));
1090        assert_eq!(milliseconds(300).abs(), milliseconds(300));
1091        assert_eq!(milliseconds(0).abs(), milliseconds(0));
1092        assert_eq!(milliseconds(-300).abs(), milliseconds(300));
1093        assert_eq!(milliseconds(-700).abs(), milliseconds(700));
1094        assert_eq!(milliseconds(-1000).abs(), milliseconds(1000));
1095        assert_eq!(milliseconds(-1300).abs(), milliseconds(1300));
1096        assert_eq!(milliseconds(-1700).abs(), milliseconds(1700));
1097        assert_eq!(milliseconds(-i64::MAX).abs(), milliseconds(i64::MAX));
1098    }
1099
1100    #[test]
1101    #[allow(clippy::erasing_op)]
1102    fn test_duration_mul() {
1103        assert_eq!(TimeDelta::zero() * i32::MAX, TimeDelta::zero());
1104        assert_eq!(TimeDelta::zero() * i32::MIN, TimeDelta::zero());
1105        assert_eq!(TimeDelta::nanoseconds(1) * 0, TimeDelta::zero());
1106        assert_eq!(TimeDelta::nanoseconds(1) * 1, TimeDelta::nanoseconds(1));
1107        assert_eq!(TimeDelta::nanoseconds(1) * 1_000_000_000, TimeDelta::try_seconds(1).unwrap());
1108        assert_eq!(TimeDelta::nanoseconds(1) * -1_000_000_000, -TimeDelta::try_seconds(1).unwrap());
1109        assert_eq!(-TimeDelta::nanoseconds(1) * 1_000_000_000, -TimeDelta::try_seconds(1).unwrap());
1110        assert_eq!(
1111            TimeDelta::nanoseconds(30) * 333_333_333,
1112            TimeDelta::try_seconds(10).unwrap() - TimeDelta::nanoseconds(10)
1113        );
1114        assert_eq!(
1115            (TimeDelta::nanoseconds(1)
1116                + TimeDelta::try_seconds(1).unwrap()
1117                + TimeDelta::try_days(1).unwrap())
1118                * 3,
1119            TimeDelta::nanoseconds(3)
1120                + TimeDelta::try_seconds(3).unwrap()
1121                + TimeDelta::try_days(3).unwrap()
1122        );
1123        assert_eq!(
1124            TimeDelta::try_milliseconds(1500).unwrap() * -2,
1125            TimeDelta::try_seconds(-3).unwrap()
1126        );
1127        assert_eq!(
1128            TimeDelta::try_milliseconds(-1500).unwrap() * 2,
1129            TimeDelta::try_seconds(-3).unwrap()
1130        );
1131    }
1132
1133    #[test]
1134    fn test_duration_div() {
1135        assert_eq!(TimeDelta::zero() / i32::MAX, TimeDelta::zero());
1136        assert_eq!(TimeDelta::zero() / i32::MIN, TimeDelta::zero());
1137        assert_eq!(TimeDelta::nanoseconds(123_456_789) / 1, TimeDelta::nanoseconds(123_456_789));
1138        assert_eq!(TimeDelta::nanoseconds(123_456_789) / -1, -TimeDelta::nanoseconds(123_456_789));
1139        assert_eq!(-TimeDelta::nanoseconds(123_456_789) / -1, TimeDelta::nanoseconds(123_456_789));
1140        assert_eq!(-TimeDelta::nanoseconds(123_456_789) / 1, -TimeDelta::nanoseconds(123_456_789));
1141        assert_eq!(TimeDelta::try_seconds(1).unwrap() / 3, TimeDelta::nanoseconds(333_333_333));
1142        assert_eq!(TimeDelta::try_seconds(4).unwrap() / 3, TimeDelta::nanoseconds(1_333_333_333));
1143        assert_eq!(
1144            TimeDelta::try_seconds(-1).unwrap() / 2,
1145            TimeDelta::try_milliseconds(-500).unwrap()
1146        );
1147        assert_eq!(
1148            TimeDelta::try_seconds(1).unwrap() / -2,
1149            TimeDelta::try_milliseconds(-500).unwrap()
1150        );
1151        assert_eq!(
1152            TimeDelta::try_seconds(-1).unwrap() / -2,
1153            TimeDelta::try_milliseconds(500).unwrap()
1154        );
1155        assert_eq!(TimeDelta::try_seconds(-4).unwrap() / 3, TimeDelta::nanoseconds(-1_333_333_333));
1156        assert_eq!(TimeDelta::try_seconds(-4).unwrap() / -3, TimeDelta::nanoseconds(1_333_333_333));
1157    }
1158
1159    #[test]
1160    fn test_duration_sum() {
1161        let duration_list_1 = [TimeDelta::zero(), TimeDelta::try_seconds(1).unwrap()];
1162        let sum_1: TimeDelta = duration_list_1.iter().sum();
1163        assert_eq!(sum_1, TimeDelta::try_seconds(1).unwrap());
1164
1165        let duration_list_2 = [
1166            TimeDelta::zero(),
1167            TimeDelta::try_seconds(1).unwrap(),
1168            TimeDelta::try_seconds(6).unwrap(),
1169            TimeDelta::try_seconds(10).unwrap(),
1170        ];
1171        let sum_2: TimeDelta = duration_list_2.iter().sum();
1172        assert_eq!(sum_2, TimeDelta::try_seconds(17).unwrap());
1173
1174        let duration_arr = [
1175            TimeDelta::zero(),
1176            TimeDelta::try_seconds(1).unwrap(),
1177            TimeDelta::try_seconds(6).unwrap(),
1178            TimeDelta::try_seconds(10).unwrap(),
1179        ];
1180        let sum_3: TimeDelta = duration_arr.into_iter().sum();
1181        assert_eq!(sum_3, TimeDelta::try_seconds(17).unwrap());
1182    }
1183
1184    #[test]
1185    fn test_duration_fmt() {
1186        assert_eq!(TimeDelta::zero().to_string(), "P0D");
1187        assert_eq!(TimeDelta::try_days(42).unwrap().to_string(), "PT3628800S");
1188        assert_eq!(TimeDelta::try_days(-42).unwrap().to_string(), "-PT3628800S");
1189        assert_eq!(TimeDelta::try_seconds(42).unwrap().to_string(), "PT42S");
1190        assert_eq!(TimeDelta::try_milliseconds(42).unwrap().to_string(), "PT0.042S");
1191        assert_eq!(TimeDelta::microseconds(42).to_string(), "PT0.000042S");
1192        assert_eq!(TimeDelta::nanoseconds(42).to_string(), "PT0.000000042S");
1193        assert_eq!(
1194            (TimeDelta::try_days(7).unwrap() + TimeDelta::try_milliseconds(6543).unwrap())
1195                .to_string(),
1196            "PT604806.543S"
1197        );
1198        assert_eq!(TimeDelta::try_seconds(-86_401).unwrap().to_string(), "-PT86401S");
1199        assert_eq!(TimeDelta::nanoseconds(-1).to_string(), "-PT0.000000001S");
1200
1201        // the format specifier should have no effect on `TimeDelta`
1202        assert_eq!(
1203            format!(
1204                "{:30}",
1205                TimeDelta::try_days(1).unwrap() + TimeDelta::try_milliseconds(2345).unwrap()
1206            ),
1207            "PT86402.345S"
1208        );
1209    }
1210
1211    #[test]
1212    fn test_to_std() {
1213        assert_eq!(TimeDelta::try_seconds(1).unwrap().to_std(), Ok(Duration::new(1, 0)));
1214        assert_eq!(TimeDelta::try_seconds(86_401).unwrap().to_std(), Ok(Duration::new(86_401, 0)));
1215        assert_eq!(
1216            TimeDelta::try_milliseconds(123).unwrap().to_std(),
1217            Ok(Duration::new(0, 123_000_000))
1218        );
1219        assert_eq!(
1220            TimeDelta::try_milliseconds(123_765).unwrap().to_std(),
1221            Ok(Duration::new(123, 765_000_000))
1222        );
1223        assert_eq!(TimeDelta::nanoseconds(777).to_std(), Ok(Duration::new(0, 777)));
1224        assert_eq!(MAX.to_std(), Ok(Duration::new(9_223_372_036_854_775, 807_000_000)));
1225        assert_eq!(TimeDelta::try_seconds(-1).unwrap().to_std(), Err(OutOfRangeError(())));
1226        assert_eq!(TimeDelta::try_milliseconds(-1).unwrap().to_std(), Err(OutOfRangeError(())));
1227    }
1228
1229    #[test]
1230    fn test_from_std() {
1231        assert_eq!(
1232            Ok(TimeDelta::try_seconds(1).unwrap()),
1233            TimeDelta::from_std(Duration::new(1, 0))
1234        );
1235        assert_eq!(
1236            Ok(TimeDelta::try_seconds(86_401).unwrap()),
1237            TimeDelta::from_std(Duration::new(86_401, 0))
1238        );
1239        assert_eq!(
1240            Ok(TimeDelta::try_milliseconds(123).unwrap()),
1241            TimeDelta::from_std(Duration::new(0, 123_000_000))
1242        );
1243        assert_eq!(
1244            Ok(TimeDelta::try_milliseconds(123_765).unwrap()),
1245            TimeDelta::from_std(Duration::new(123, 765_000_000))
1246        );
1247        assert_eq!(Ok(TimeDelta::nanoseconds(777)), TimeDelta::from_std(Duration::new(0, 777)));
1248        assert_eq!(Ok(MAX), TimeDelta::from_std(Duration::new(9_223_372_036_854_775, 807_000_000)));
1249        assert_eq!(
1250            TimeDelta::from_std(Duration::new(9_223_372_036_854_776, 0)),
1251            Err(OutOfRangeError(()))
1252        );
1253        assert_eq!(
1254            TimeDelta::from_std(Duration::new(9_223_372_036_854_775, 807_000_001)),
1255            Err(OutOfRangeError(()))
1256        );
1257    }
1258
1259    #[test]
1260    fn test_duration_const() {
1261        const ONE_WEEK: TimeDelta = expect(TimeDelta::try_weeks(1), "");
1262        const ONE_DAY: TimeDelta = expect(TimeDelta::try_days(1), "");
1263        const ONE_HOUR: TimeDelta = expect(TimeDelta::try_hours(1), "");
1264        const ONE_MINUTE: TimeDelta = expect(TimeDelta::try_minutes(1), "");
1265        const ONE_SECOND: TimeDelta = expect(TimeDelta::try_seconds(1), "");
1266        const ONE_MILLI: TimeDelta = expect(TimeDelta::try_milliseconds(1), "");
1267        const ONE_MICRO: TimeDelta = TimeDelta::microseconds(1);
1268        const ONE_NANO: TimeDelta = TimeDelta::nanoseconds(1);
1269        let combo: TimeDelta = ONE_WEEK
1270            + ONE_DAY
1271            + ONE_HOUR
1272            + ONE_MINUTE
1273            + ONE_SECOND
1274            + ONE_MILLI
1275            + ONE_MICRO
1276            + ONE_NANO;
1277
1278        assert!(ONE_WEEK != TimeDelta::zero());
1279        assert!(ONE_DAY != TimeDelta::zero());
1280        assert!(ONE_HOUR != TimeDelta::zero());
1281        assert!(ONE_MINUTE != TimeDelta::zero());
1282        assert!(ONE_SECOND != TimeDelta::zero());
1283        assert!(ONE_MILLI != TimeDelta::zero());
1284        assert!(ONE_MICRO != TimeDelta::zero());
1285        assert!(ONE_NANO != TimeDelta::zero());
1286        assert_eq!(
1287            combo,
1288            TimeDelta::try_seconds(86400 * 7 + 86400 + 3600 + 60 + 1).unwrap()
1289                + TimeDelta::nanoseconds(1 + 1_000 + 1_000_000)
1290        );
1291    }
1292
1293    #[test]
1294    #[cfg(feature = "rkyv-validation")]
1295    fn test_rkyv_validation() {
1296        let duration = TimeDelta::try_seconds(1).unwrap();
1297        let bytes = rkyv::to_bytes::<_, 16>(&duration).unwrap();
1298        assert_eq!(rkyv::from_bytes::<TimeDelta>(&bytes).unwrap(), duration);
1299    }
1300}