Coverage Report

Created: 2025-07-23 06:18

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