1use core::cmp::Ordering;
4use core::fmt;
5use core::hash::{Hash, Hasher};
6use core::iter::Sum;
7use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
8use core::time::Duration as StdDuration;
9#[cfg(feature = "std")]
10use std::time::SystemTime;
11
12use deranged::ri32;
13use num_conv::prelude::*;
14
15#[cfg(feature = "std")]
16#[expect(deprecated)]
17use crate::Instant;
18use crate::error;
19use crate::internal_macros::const_try_opt;
20use crate::unit::*;
21
22#[derive(#[automatically_derived]
impl ::core::fmt::Debug for FloatConstructorError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
FloatConstructorError::Nan => "Nan",
FloatConstructorError::NegOverflow => "NegOverflow",
FloatConstructorError::PosOverflow => "PosOverflow",
})
}
}Debug)]
23enum FloatConstructorError {
24 Nan,
25 NegOverflow,
26 PosOverflow,
27}
28
29#[repr(u32)]
32#[derive(#[automatically_derived]
impl ::core::fmt::Debug for Padding {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f, "Optimize")
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for Padding {
#[inline]
fn clone(&self) -> Padding { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Padding { }Copy)]
33pub(crate) enum Padding {
34 #[allow(clippy::missing_docs_in_private_items)]
35 Optimize,
36}
37
38type Nanoseconds =
40 ri32<{ -Nanosecond::per_t::<i32>(Second) + 1 }, { Nanosecond::per_t::<i32>(Second) - 1 }>;
41
42#[repr(C)]
49#[derive(#[automatically_derived]
impl ::core::clone::Clone for Duration {
#[inline]
fn clone(&self) -> Duration {
let _: ::core::clone::AssertParamIsClone<i64>;
let _: ::core::clone::AssertParamIsClone<Nanoseconds>;
let _: ::core::clone::AssertParamIsClone<Padding>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Duration { }Copy)]
50pub struct Duration {
51 seconds: i64,
53 nanoseconds: Nanoseconds,
56 _padding: Padding,
57}
58
59impl fmt::Debug for Duration {
60 #[inline]
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 f.debug_struct("Duration")
63 .field("seconds", &self.seconds)
64 .field("nanoseconds", &self.nanoseconds)
65 .finish()
66 }
67}
68
69impl PartialEq for Duration {
70 #[inline]
71 fn eq(&self, other: &Self) -> bool {
72 self.as_int_for_equality() == other.as_int_for_equality()
73 }
74}
75
76impl Eq for Duration {}
77
78impl PartialOrd for Duration {
79 #[inline]
80 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
81 Some(self.cmp(other))
82 }
83}
84
85impl Ord for Duration {
86 #[inline]
87 fn cmp(&self, other: &Self) -> Ordering {
88 self.seconds
89 .cmp(&other.seconds)
90 .then_with(|| self.nanoseconds.cmp(&other.nanoseconds))
91 }
92}
93
94impl Hash for Duration {
95 fn hash<H>(&self, state: &mut H)
96 where
97 H: Hasher,
98 {
99 self.as_int_for_equality().hash(state);
100 }
101}
102
103impl Default for Duration {
104 #[inline]
105 fn default() -> Self {
106 Self::ZERO
107 }
108}
109
110#[rustfmt::skip] macro_rules! try_from_secs {
118 (
119 secs = $secs: expr,
120 mantissa_bits = $mant_bits: literal,
121 exponent_bits = $exp_bits: literal,
122 offset = $offset: literal,
123 bits_ty = $bits_ty:ty,
124 bits_ty_signed = $bits_ty_signed:ty,
125 double_ty = $double_ty:ty,
126 float_ty = $float_ty:ty,
127 ) => {{
128 'value: {
129 const MIN_EXP: i16 = 1 - (1i16 << $exp_bits) / 2;
130 const MANT_MASK: $bits_ty = (1 << $mant_bits) - 1;
131 const EXP_MASK: $bits_ty = (1 << $exp_bits) - 1;
132
133 let bits = $secs.to_bits();
136 let mant = (bits & MANT_MASK) | (MANT_MASK + 1);
137 let exp = ((bits >> $mant_bits) & EXP_MASK) as i16 + MIN_EXP;
138
139 let (secs, nanos) = if exp < -31 {
140 (0u64, 0u32)
142 } else if exp < 0 {
143 let t = (mant as $double_ty) << ($offset + exp);
145 let nanos_offset = $mant_bits + $offset;
146 #[allow(trivial_numeric_casts)]
147 let nanos_tmp = Nanosecond::per_t::<u128>(Second) * t as u128;
148 let nanos = (nanos_tmp >> nanos_offset) as u32;
149
150 let rem_mask = (1 << nanos_offset) - 1;
151 let rem_msb_mask = 1 << (nanos_offset - 1);
152 let rem = nanos_tmp & rem_mask;
153 let is_tie = rem == rem_msb_mask;
154 let is_even = (nanos & 1) == 0;
155 let rem_msb = nanos_tmp & rem_msb_mask == 0;
156 let add_ns = !(rem_msb || (is_even && is_tie));
157
158 let nanos = nanos + add_ns as u32;
161 if ($mant_bits == 23) || (nanos != Nanosecond::per_t::<u32>(Second)) {
162 (0, nanos)
163 } else {
164 (1, 0)
165 }
166 } else if exp < $mant_bits {
167 #[allow(trivial_numeric_casts)]
168 let secs = (mant >> ($mant_bits - exp)) as u64;
169 let t = ((mant << exp) & MANT_MASK) as $double_ty;
170 let nanos_offset = $mant_bits;
171 let nanos_tmp = Nanosecond::per_t::<$double_ty>(Second) * t;
172 let nanos = (nanos_tmp >> nanos_offset) as u32;
173
174 let rem_mask = (1 << nanos_offset) - 1;
175 let rem_msb_mask = 1 << (nanos_offset - 1);
176 let rem = nanos_tmp & rem_mask;
177 let is_tie = rem == rem_msb_mask;
178 let is_even = (nanos & 1) == 0;
179 let rem_msb = nanos_tmp & rem_msb_mask == 0;
180 let add_ns = !(rem_msb || (is_even && is_tie));
181
182 let nanos = nanos + add_ns as u32;
187 if ($mant_bits == 23) || (nanos != Nanosecond::per_t::<u32>(Second)) {
188 (secs, nanos)
189 } else {
190 (secs + 1, 0)
191 }
192 } else if exp < 63 {
193 #[allow(trivial_numeric_casts)]
198 let secs = (mant as u64) << (exp - $mant_bits);
199 (secs, 0)
200 } else if bits == (i64::MIN as $float_ty).to_bits() {
201 break 'value Ok(Self::new_ranged_unchecked(i64::MIN, Nanoseconds::new_static::<0>()));
207 } else if $secs.is_nan() {
208 break 'value Err(FloatConstructorError::Nan);
211 } else if $secs.is_sign_negative() {
212 break 'value Err(FloatConstructorError::NegOverflow);
213 } else {
214 break 'value Err(FloatConstructorError::PosOverflow);
215 };
216
217 let mask = (bits as $bits_ty_signed) >> ($mant_bits + $exp_bits);
224 #[allow(trivial_numeric_casts)]
225 let secs_signed = ((secs as i64) ^ (mask as i64)) - (mask as i64);
226 #[allow(trivial_numeric_casts)]
227 let nanos_signed = ((nanos as i32) ^ (mask as i32)) - (mask as i32);
228 Ok(unsafe { Self::new_unchecked(secs_signed, nanos_signed) })
230 }
231 }};
232}
233
234impl Duration {
235 #[inline]
236 const fn as_int_for_equality(self) -> i128 {
237 unsafe { core::mem::transmute(self) }
239 }
240
241 pub const ZERO: Self = Self::seconds(0);
248
249 pub const NANOSECOND: Self = Self::nanoseconds(1);
256
257 pub const MICROSECOND: Self = Self::microseconds(1);
264
265 pub const MILLISECOND: Self = Self::milliseconds(1);
272
273 pub const SECOND: Self = Self::seconds(1);
280
281 pub const MINUTE: Self = Self::minutes(1);
288
289 pub const HOUR: Self = Self::hours(1);
296
297 pub const DAY: Self = Self::days(1);
304
305 pub const WEEK: Self = Self::weeks(1);
312
313 pub const MIN: Self = Self::new_ranged(i64::MIN, Nanoseconds::MIN);
315
316 pub const MAX: Self = Self::new_ranged(i64::MAX, Nanoseconds::MAX);
318
319 #[inline]
327 pub const fn is_zero(self) -> bool {
328 self.as_int_for_equality() == Self::ZERO.as_int_for_equality()
329 }
330
331 #[inline]
340 pub const fn is_negative(self) -> bool {
341 self.seconds < 0 || self.nanoseconds.get() < 0
342 }
343
344 #[inline]
353 pub const fn is_positive(self) -> bool {
354 self.seconds > 0 || self.nanoseconds.get() > 0
355 }
356
357 #[inline]
368 pub const fn abs(self) -> Self {
369 match self.seconds.checked_abs() {
370 Some(seconds) => Self::new_ranged_unchecked(seconds, self.nanoseconds.abs()),
371 None => Self::MAX,
372 }
373 }
374
375 #[inline]
385 pub const fn unsigned_abs(self) -> StdDuration {
386 StdDuration::new(
387 self.seconds.unsigned_abs(),
388 self.nanoseconds.get().unsigned_abs(),
389 )
390 }
391
392 #[inline]
401 #[track_caller]
402 pub(crate) const unsafe fn new_unchecked(seconds: i64, nanoseconds: i32) -> Self {
403 Self::new_ranged_unchecked(
404 seconds,
405 unsafe { Nanoseconds::new_unchecked(nanoseconds) },
407 )
408 }
409
410 #[inline]
412 #[track_caller]
413 pub(crate) const fn new_ranged_unchecked(seconds: i64, nanoseconds: Nanoseconds) -> Self {
414 if seconds < 0 {
415 if true {
if !(nanoseconds.get() <= 0) {
::core::panicking::panic("assertion failed: nanoseconds.get() <= 0")
};
};debug_assert!(nanoseconds.get() <= 0);
416 } else if seconds > 0 {
417 if true {
if !(nanoseconds.get() >= 0) {
::core::panicking::panic("assertion failed: nanoseconds.get() >= 0")
};
};debug_assert!(nanoseconds.get() >= 0);
418 }
419
420 Self {
421 seconds,
422 nanoseconds,
423 _padding: Padding::Optimize,
424 }
425 }
426
427 #[inline]
441 #[track_caller]
442 pub const fn new(mut seconds: i64, mut nanoseconds: i32) -> Self {
443 seconds = seconds
444 .checked_add(nanoseconds as i64 / Nanosecond::per_t::<i64>(Second))
445 .expect("overflow constructing `time::Duration`");
446 nanoseconds %= Nanosecond::per_t::<i32>(Second);
447
448 if seconds > 0 && nanoseconds < 0 {
449 seconds -= 1;
451 nanoseconds += Nanosecond::per_t::<i32>(Second);
452 } else if seconds < 0 && nanoseconds > 0 {
453 seconds += 1;
455 nanoseconds -= Nanosecond::per_t::<i32>(Second);
456 }
457
458 unsafe { Self::new_unchecked(seconds, nanoseconds) }
460 }
461
462 #[inline]
464 pub(crate) const fn new_ranged(mut seconds: i64, mut nanoseconds: Nanoseconds) -> Self {
465 if seconds > 0 && nanoseconds.get() < 0 {
466 seconds -= 1;
468 nanoseconds = unsafe {
471 Nanoseconds::new_unchecked(nanoseconds.get() + Nanosecond::per_t::<i32>(Second))
472 };
473 } else if seconds < 0 && nanoseconds.get() > 0 {
474 seconds += 1;
476 nanoseconds = unsafe {
479 Nanoseconds::new_unchecked(nanoseconds.get() - Nanosecond::per_t::<i32>(Second))
480 };
481 }
482
483 Self::new_ranged_unchecked(seconds, nanoseconds)
484 }
485
486 #[inline]
498 #[track_caller]
499 pub const fn weeks(weeks: i64) -> Self {
500 Self::seconds(
501 weeks
502 .checked_mul(Second::per_t(Week))
503 .expect("overflow constructing `time::Duration`"),
504 )
505 }
506
507 #[inline]
519 #[track_caller]
520 pub const fn days(days: i64) -> Self {
521 Self::seconds(
522 days.checked_mul(Second::per_t(Day))
523 .expect("overflow constructing `time::Duration`"),
524 )
525 }
526
527 #[inline]
539 #[track_caller]
540 pub const fn hours(hours: i64) -> Self {
541 Self::seconds(
542 hours
543 .checked_mul(Second::per_t(Hour))
544 .expect("overflow constructing `time::Duration`"),
545 )
546 }
547
548 #[inline]
560 #[track_caller]
561 pub const fn minutes(minutes: i64) -> Self {
562 Self::seconds(
563 minutes
564 .checked_mul(Second::per_t(Minute))
565 .expect("overflow constructing `time::Duration`"),
566 )
567 }
568
569 #[inline]
576 pub const fn seconds(seconds: i64) -> Self {
577 Self::new_ranged_unchecked(seconds, Nanoseconds::new_static::<0>())
578 }
579
580 #[inline]
585 const fn try_seconds_f64(seconds: f64) -> Result<Self, FloatConstructorError> {
586 {
'value:
{
const MIN_EXP: i16 = 1 - (1i16 << 11) / 2;
const MANT_MASK: u64 = (1 << 52) - 1;
const EXP_MASK: u64 = (1 << 11) - 1;
let bits = seconds.to_bits();
let mant = (bits & MANT_MASK) | (MANT_MASK + 1);
let exp = ((bits >> 52) & EXP_MASK) as i16 + MIN_EXP;
let (secs, nanos) =
if exp < -31 {
(0u64, 0u32)
} else if exp < 0 {
let t = (mant as u128) << (44 + exp);
let nanos_offset = 52 + 44;
#[allow(trivial_numeric_casts)]
let nanos_tmp = Nanosecond::per_t::<u128>(Second) * t as u128;
let nanos = (nanos_tmp >> nanos_offset) as u32;
let rem_mask = (1 << nanos_offset) - 1;
let rem_msb_mask = 1 << (nanos_offset - 1);
let rem = nanos_tmp & rem_mask;
let is_tie = rem == rem_msb_mask;
let is_even = (nanos & 1) == 0;
let rem_msb = nanos_tmp & rem_msb_mask == 0;
let add_ns = !(rem_msb || (is_even && is_tie));
let nanos = nanos + add_ns as u32;
if (52 == 23) || (nanos != Nanosecond::per_t::<u32>(Second)) {
(0, nanos)
} else { (1, 0) }
} else if exp < 52 {
#[allow(trivial_numeric_casts)]
let secs = (mant >> (52 - exp)) as u64;
let t = ((mant << exp) & MANT_MASK) as u128;
let nanos_offset = 52;
let nanos_tmp = Nanosecond::per_t::<u128>(Second) * t;
let nanos = (nanos_tmp >> nanos_offset) as u32;
let rem_mask = (1 << nanos_offset) - 1;
let rem_msb_mask = 1 << (nanos_offset - 1);
let rem = nanos_tmp & rem_mask;
let is_tie = rem == rem_msb_mask;
let is_even = (nanos & 1) == 0;
let rem_msb = nanos_tmp & rem_msb_mask == 0;
let add_ns = !(rem_msb || (is_even && is_tie));
let nanos = nanos + add_ns as u32;
if (52 == 23) || (nanos != Nanosecond::per_t::<u32>(Second)) {
(secs, nanos)
} else { (secs + 1, 0) }
} else if exp < 63 {
#[allow(trivial_numeric_casts)]
let secs = (mant as u64) << (exp - 52);
(secs, 0)
} else if bits == (i64::MIN as f64).to_bits() {
break 'value
Ok(Self::new_ranged_unchecked(i64::MIN,
Nanoseconds::new_static::<0>()));
} else if seconds.is_nan() {
break 'value Err(FloatConstructorError::Nan);
} else if seconds.is_sign_negative() {
break 'value Err(FloatConstructorError::NegOverflow);
} else { break 'value Err(FloatConstructorError::PosOverflow); };
let mask = (bits as i64) >> (52 + 11);
#[allow(trivial_numeric_casts)]
let secs_signed = ((secs as i64) ^ (mask as i64)) - (mask as i64);
#[allow(trivial_numeric_casts)]
let nanos_signed = ((nanos as i32) ^ (mask as i32)) - (mask as i32);
Ok(unsafe { Self::new_unchecked(secs_signed, nanos_signed) })
}
}try_from_secs!(
587 secs = seconds,
588 mantissa_bits = 52,
589 exponent_bits = 11,
590 offset = 44,
591 bits_ty = u64,
592 bits_ty_signed = i64,
593 double_ty = u128,
594 float_ty = f64,
595 )
596 }
597
598 #[inline]
603 const fn try_seconds_f32(seconds: f32) -> Result<Self, FloatConstructorError> {
604 {
'value:
{
const MIN_EXP: i16 = 1 - (1i16 << 8) / 2;
const MANT_MASK: u32 = (1 << 23) - 1;
const EXP_MASK: u32 = (1 << 8) - 1;
let bits = seconds.to_bits();
let mant = (bits & MANT_MASK) | (MANT_MASK + 1);
let exp = ((bits >> 23) & EXP_MASK) as i16 + MIN_EXP;
let (secs, nanos) =
if exp < -31 {
(0u64, 0u32)
} else if exp < 0 {
let t = (mant as u64) << (41 + exp);
let nanos_offset = 23 + 41;
#[allow(trivial_numeric_casts)]
let nanos_tmp = Nanosecond::per_t::<u128>(Second) * t as u128;
let nanos = (nanos_tmp >> nanos_offset) as u32;
let rem_mask = (1 << nanos_offset) - 1;
let rem_msb_mask = 1 << (nanos_offset - 1);
let rem = nanos_tmp & rem_mask;
let is_tie = rem == rem_msb_mask;
let is_even = (nanos & 1) == 0;
let rem_msb = nanos_tmp & rem_msb_mask == 0;
let add_ns = !(rem_msb || (is_even && is_tie));
let nanos = nanos + add_ns as u32;
if (23 == 23) || (nanos != Nanosecond::per_t::<u32>(Second)) {
(0, nanos)
} else { (1, 0) }
} else if exp < 23 {
#[allow(trivial_numeric_casts)]
let secs = (mant >> (23 - exp)) as u64;
let t = ((mant << exp) & MANT_MASK) as u64;
let nanos_offset = 23;
let nanos_tmp = Nanosecond::per_t::<u64>(Second) * t;
let nanos = (nanos_tmp >> nanos_offset) as u32;
let rem_mask = (1 << nanos_offset) - 1;
let rem_msb_mask = 1 << (nanos_offset - 1);
let rem = nanos_tmp & rem_mask;
let is_tie = rem == rem_msb_mask;
let is_even = (nanos & 1) == 0;
let rem_msb = nanos_tmp & rem_msb_mask == 0;
let add_ns = !(rem_msb || (is_even && is_tie));
let nanos = nanos + add_ns as u32;
if (23 == 23) || (nanos != Nanosecond::per_t::<u32>(Second)) {
(secs, nanos)
} else { (secs + 1, 0) }
} else if exp < 63 {
#[allow(trivial_numeric_casts)]
let secs = (mant as u64) << (exp - 23);
(secs, 0)
} else if bits == (i64::MIN as f32).to_bits() {
break 'value
Ok(Self::new_ranged_unchecked(i64::MIN,
Nanoseconds::new_static::<0>()));
} else if seconds.is_nan() {
break 'value Err(FloatConstructorError::Nan);
} else if seconds.is_sign_negative() {
break 'value Err(FloatConstructorError::NegOverflow);
} else { break 'value Err(FloatConstructorError::PosOverflow); };
let mask = (bits as i32) >> (23 + 8);
#[allow(trivial_numeric_casts)]
let secs_signed = ((secs as i64) ^ (mask as i64)) - (mask as i64);
#[allow(trivial_numeric_casts)]
let nanos_signed = ((nanos as i32) ^ (mask as i32)) - (mask as i32);
Ok(unsafe { Self::new_unchecked(secs_signed, nanos_signed) })
}
}try_from_secs!(
605 secs = seconds,
606 mantissa_bits = 23,
607 exponent_bits = 8,
608 offset = 41,
609 bits_ty = u32,
610 bits_ty_signed = i32,
611 double_ty = u64,
612 float_ty = f32,
613 )
614 }
615
616 #[inline]
628 #[track_caller]
629 pub const fn seconds_f64(seconds: f64) -> Self {
630 match Self::try_seconds_f64(seconds) {
631 Ok(duration) => duration,
632 Err(FloatConstructorError::Nan) => {
633 {
::core::panicking::panic_fmt(format_args!("passed NaN to `time::Duration::seconds_f64`"));
};panic!("passed NaN to `time::Duration::seconds_f64`");
634 }
635 Err(FloatConstructorError::NegOverflow | FloatConstructorError::PosOverflow) => {
636 {
::core::panicking::panic_fmt(format_args!("overflow constructing `time::Duration`"));
};panic!("overflow constructing `time::Duration`");
637 }
638 }
639 }
640
641 #[inline]
653 #[track_caller]
654 pub const fn seconds_f32(seconds: f32) -> Self {
655 match Self::try_seconds_f32(seconds) {
656 Ok(duration) => duration,
657 Err(FloatConstructorError::Nan) => {
658 {
::core::panicking::panic_fmt(format_args!("passed NaN to `time::Duration::seconds_f32`"));
};panic!("passed NaN to `time::Duration::seconds_f32`");
659 }
660 Err(FloatConstructorError::NegOverflow | FloatConstructorError::PosOverflow) => {
661 {
::core::panicking::panic_fmt(format_args!("overflow constructing `time::Duration`"));
};panic!("overflow constructing `time::Duration`");
662 }
663 }
664 }
665
666 #[inline]
689 pub const fn saturating_seconds_f64(seconds: f64) -> Self {
690 match Self::try_seconds_f64(seconds) {
691 Ok(duration) => duration,
692 Err(FloatConstructorError::Nan) => Self::ZERO,
693 Err(FloatConstructorError::NegOverflow) => Self::MIN,
694 Err(FloatConstructorError::PosOverflow) => Self::MAX,
695 }
696 }
697
698 #[inline]
721 pub const fn saturating_seconds_f32(seconds: f32) -> Self {
722 match Self::try_seconds_f32(seconds) {
723 Ok(duration) => duration,
724 Err(FloatConstructorError::Nan) => Self::ZERO,
725 Err(FloatConstructorError::NegOverflow) => Self::MIN,
726 Err(FloatConstructorError::PosOverflow) => Self::MAX,
727 }
728 }
729
730 #[inline]
743 pub const fn checked_seconds_f64(seconds: f64) -> Option<Self> {
744 match Self::try_seconds_f64(seconds) {
745 Ok(duration) => Some(duration),
746 Err(_) => None,
747 }
748 }
749
750 #[inline]
763 pub const fn checked_seconds_f32(seconds: f32) -> Option<Self> {
764 match Self::try_seconds_f32(seconds) {
765 Ok(duration) => Some(duration),
766 Err(_) => None,
767 }
768 }
769
770 #[inline]
778 pub const fn milliseconds(milliseconds: i64) -> Self {
779 unsafe {
781 Self::new_unchecked(
782 milliseconds / Millisecond::per_t::<i64>(Second),
783 (milliseconds % Millisecond::per_t::<i64>(Second)
784 * Nanosecond::per_t::<i64>(Millisecond)) as i32,
785 )
786 }
787 }
788
789 #[inline]
797 pub const fn microseconds(microseconds: i64) -> Self {
798 unsafe {
800 Self::new_unchecked(
801 microseconds / Microsecond::per_t::<i64>(Second),
802 (microseconds % Microsecond::per_t::<i64>(Second)
803 * Nanosecond::per_t::<i64>(Microsecond)) as i32,
804 )
805 }
806 }
807
808 #[inline]
816 pub const fn nanoseconds(nanoseconds: i64) -> Self {
817 unsafe {
819 Self::new_unchecked(
820 nanoseconds / Nanosecond::per_t::<i64>(Second),
821 (nanoseconds % Nanosecond::per_t::<i64>(Second)) as i32,
822 )
823 }
824 }
825
826 #[inline]
841 #[track_caller]
842 pub const fn nanoseconds_i128(nanoseconds: i128) -> Self {
843 let seconds = nanoseconds / Nanosecond::per_t::<i128>(Second);
844 let nanoseconds = nanoseconds % Nanosecond::per_t::<i128>(Second);
845
846 if seconds > i64::MAX as i128 || seconds < i64::MIN as i128 {
847 {
::core::panicking::panic_fmt(format_args!("overflow constructing `time::Duration`"));
};panic!("overflow constructing `time::Duration`");
848 }
849
850 unsafe { Self::new_unchecked(seconds as i64, nanoseconds as i32) }
852 }
853
854 #[inline]
864 pub const fn whole_weeks(self) -> i64 {
865 self.whole_seconds() / Second::per_t::<i64>(Week)
866 }
867
868 #[inline]
878 pub const fn whole_days(self) -> i64 {
879 self.whole_seconds() / Second::per_t::<i64>(Day)
880 }
881
882 #[inline]
892 pub const fn whole_hours(self) -> i64 {
893 self.whole_seconds() / Second::per_t::<i64>(Hour)
894 }
895
896 #[inline]
906 pub const fn whole_minutes(self) -> i64 {
907 self.whole_seconds() / Second::per_t::<i64>(Minute)
908 }
909
910 #[inline]
920 pub const fn whole_seconds(self) -> i64 {
921 self.seconds
922 }
923
924 #[inline]
932 pub const fn as_seconds_f64(self) -> f64 {
933 self.seconds as f64 + self.nanoseconds.get() as f64 / Nanosecond::per_t::<f64>(Second)
934 }
935
936 #[inline]
944 pub const fn as_seconds_f32(self) -> f32 {
945 self.seconds as f32 + self.nanoseconds.get() as f32 / Nanosecond::per_t::<f32>(Second)
946 }
947
948 #[inline]
958 pub const fn whole_milliseconds(self) -> i128 {
959 self.seconds as i128 * Millisecond::per_t::<i128>(Second)
960 + self.nanoseconds.get() as i128 / Nanosecond::per_t::<i128>(Millisecond)
961 }
962
963 #[inline]
973 pub const fn subsec_milliseconds(self) -> i16 {
974 (self.nanoseconds.get() / Nanosecond::per_t::<i32>(Millisecond)) as i16
975 }
976
977 #[inline]
987 pub const fn whole_microseconds(self) -> i128 {
988 self.seconds as i128 * Microsecond::per_t::<i128>(Second)
989 + self.nanoseconds.get() as i128 / Nanosecond::per_t::<i128>(Microsecond)
990 }
991
992 #[inline]
1002 pub const fn subsec_microseconds(self) -> i32 {
1003 self.nanoseconds.get() / Nanosecond::per_t::<i32>(Microsecond)
1004 }
1005
1006 #[inline]
1016 pub const fn whole_nanoseconds(self) -> i128 {
1017 self.seconds as i128 * Nanosecond::per_t::<i128>(Second) + self.nanoseconds.get() as i128
1018 }
1019
1020 #[inline]
1030 pub const fn subsec_nanoseconds(self) -> i32 {
1031 self.nanoseconds.get()
1032 }
1033
1034 #[cfg(feature = "quickcheck")]
1036 #[inline]
1037 pub(crate) const fn subsec_nanoseconds_ranged(self) -> Nanoseconds {
1038 self.nanoseconds
1039 }
1040
1041 #[inline]
1050 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
1051 let mut seconds = match self.seconds.checked_add(rhs.seconds) {
Some(value) => value,
None => { crate::hint::cold_path(); return None; }
}const_try_opt!(self.seconds.checked_add(rhs.seconds));
1052 let mut nanoseconds = self.nanoseconds.get() + rhs.nanoseconds.get();
1053
1054 if nanoseconds >= Nanosecond::per_t(Second) || seconds < 0 && nanoseconds > 0 {
1055 nanoseconds -= Nanosecond::per_t::<i32>(Second);
1056 seconds = match seconds.checked_add(1) {
Some(value) => value,
None => { crate::hint::cold_path(); return None; }
}const_try_opt!(seconds.checked_add(1));
1057 } else if nanoseconds <= -Nanosecond::per_t::<i32>(Second) || seconds > 0 && nanoseconds < 0
1058 {
1059 nanoseconds += Nanosecond::per_t::<i32>(Second);
1060 seconds = match seconds.checked_sub(1) {
Some(value) => value,
None => { crate::hint::cold_path(); return None; }
}const_try_opt!(seconds.checked_sub(1));
1061 }
1062
1063 unsafe { Some(Self::new_unchecked(seconds, nanoseconds)) }
1065 }
1066
1067 #[inline]
1076 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
1077 let mut seconds = match self.seconds.checked_sub(rhs.seconds) {
Some(value) => value,
None => { crate::hint::cold_path(); return None; }
}const_try_opt!(self.seconds.checked_sub(rhs.seconds));
1078 let mut nanoseconds = self.nanoseconds.get() - rhs.nanoseconds.get();
1079
1080 if nanoseconds >= Nanosecond::per_t(Second) || seconds < 0 && nanoseconds > 0 {
1081 nanoseconds -= Nanosecond::per_t::<i32>(Second);
1082 seconds = match seconds.checked_add(1) {
Some(value) => value,
None => { crate::hint::cold_path(); return None; }
}const_try_opt!(seconds.checked_add(1));
1083 } else if nanoseconds <= -Nanosecond::per_t::<i32>(Second) || seconds > 0 && nanoseconds < 0
1084 {
1085 nanoseconds += Nanosecond::per_t::<i32>(Second);
1086 seconds = match seconds.checked_sub(1) {
Some(value) => value,
None => { crate::hint::cold_path(); return None; }
}const_try_opt!(seconds.checked_sub(1));
1087 }
1088
1089 unsafe { Some(Self::new_unchecked(seconds, nanoseconds)) }
1091 }
1092
1093 #[inline]
1104 pub const fn checked_mul(self, rhs: i32) -> Option<Self> {
1105 let total_nanos = self.nanoseconds.get() as i64 * rhs as i64;
1107 let extra_secs = total_nanos / Nanosecond::per_t::<i64>(Second);
1108 let nanoseconds = (total_nanos % Nanosecond::per_t::<i64>(Second)) as i32;
1109 let seconds = match match self.seconds.checked_mul(rhs as i64) {
Some(value) => value,
None => { crate::hint::cold_path(); return None; }
}.checked_add(extra_secs) {
Some(value) => value,
None => { crate::hint::cold_path(); return None; }
}const_try_opt!(
1110 const_try_opt!(self.seconds.checked_mul(rhs as i64)).checked_add(extra_secs)
1111 );
1112
1113 unsafe { Some(Self::new_unchecked(seconds, nanoseconds)) }
1115 }
1116
1117 #[inline]
1126 pub const fn checked_div(self, rhs: i32) -> Option<Self> {
1127 let (secs, extra_secs) = (
1128 match self.seconds.checked_div(rhs as i64) {
Some(value) => value,
None => { crate::hint::cold_path(); return None; }
}const_try_opt!(self.seconds.checked_div(rhs as i64)),
1129 self.seconds % (rhs as i64),
1130 );
1131 let (mut nanos, extra_nanos) = (self.nanoseconds.get() / rhs, self.nanoseconds.get() % rhs);
1132 nanos += ((extra_secs * (Nanosecond::per_t::<i64>(Second)) + extra_nanos as i64)
1133 / (rhs as i64)) as i32;
1134
1135 unsafe { Some(Self::new_unchecked(secs, nanos)) }
1137 }
1138
1139 #[inline]
1148 pub const fn checked_neg(self) -> Option<Self> {
1149 if self.seconds == i64::MIN {
1150 None
1151 } else {
1152 Some(Self::new_ranged_unchecked(
1153 -self.seconds,
1154 self.nanoseconds.neg(),
1155 ))
1156 }
1157 }
1158
1159 #[inline]
1172 pub const fn saturating_add(self, rhs: Self) -> Self {
1173 let (mut seconds, overflow) = self.seconds.overflowing_add(rhs.seconds);
1174 if overflow {
1175 if self.seconds > 0 {
1176 return Self::MAX;
1177 }
1178 return Self::MIN;
1179 }
1180 let mut nanoseconds = self.nanoseconds.get() + rhs.nanoseconds.get();
1181
1182 if nanoseconds >= Nanosecond::per_t(Second) || seconds < 0 && nanoseconds > 0 {
1183 nanoseconds -= Nanosecond::per_t::<i32>(Second);
1184 seconds = match seconds.checked_add(1) {
1185 Some(seconds) => seconds,
1186 None => return Self::MAX,
1187 };
1188 } else if nanoseconds <= -Nanosecond::per_t::<i32>(Second) || seconds > 0 && nanoseconds < 0
1189 {
1190 nanoseconds += Nanosecond::per_t::<i32>(Second);
1191 seconds = match seconds.checked_sub(1) {
1192 Some(seconds) => seconds,
1193 None => return Self::MIN,
1194 };
1195 }
1196
1197 unsafe { Self::new_unchecked(seconds, nanoseconds) }
1199 }
1200
1201 #[inline]
1214 pub const fn saturating_sub(self, rhs: Self) -> Self {
1215 let (mut seconds, overflow) = self.seconds.overflowing_sub(rhs.seconds);
1216 if overflow {
1217 if self.seconds > 0 {
1218 return Self::MAX;
1219 }
1220 return Self::MIN;
1221 }
1222 let mut nanoseconds = self.nanoseconds.get() - rhs.nanoseconds.get();
1223
1224 if nanoseconds >= Nanosecond::per_t(Second) || seconds < 0 && nanoseconds > 0 {
1225 nanoseconds -= Nanosecond::per_t::<i32>(Second);
1226 seconds = match seconds.checked_add(1) {
1227 Some(seconds) => seconds,
1228 None => return Self::MAX,
1229 };
1230 } else if nanoseconds <= -Nanosecond::per_t::<i32>(Second) || seconds > 0 && nanoseconds < 0
1231 {
1232 nanoseconds += Nanosecond::per_t::<i32>(Second);
1233 seconds = match seconds.checked_sub(1) {
1234 Some(seconds) => seconds,
1235 None => return Self::MIN,
1236 };
1237 }
1238
1239 unsafe { Self::new_unchecked(seconds, nanoseconds) }
1241 }
1242
1243 #[inline]
1256 pub const fn saturating_mul(self, rhs: i32) -> Self {
1257 let total_nanos = self.nanoseconds.get() as i64 * rhs as i64;
1259 let extra_secs = total_nanos / Nanosecond::per_t::<i64>(Second);
1260 let nanoseconds = (total_nanos % Nanosecond::per_t::<i64>(Second)) as i32;
1261 let (seconds, overflow1) = self.seconds.overflowing_mul(rhs as i64);
1262 if overflow1 {
1263 if self.seconds > 0 && rhs > 0 || self.seconds < 0 && rhs < 0 {
1264 return Self::MAX;
1265 }
1266 return Self::MIN;
1267 }
1268 let (seconds, overflow2) = seconds.overflowing_add(extra_secs);
1269 if overflow2 {
1270 if self.seconds > 0 && rhs > 0 {
1271 return Self::MAX;
1272 }
1273 return Self::MIN;
1274 }
1275
1276 unsafe { Self::new_unchecked(seconds, nanoseconds) }
1278 }
1279
1280 #[cfg(feature = "std")]
1283 #[doc(hidden)]
1284 #[inline]
1285 #[track_caller]
1286 #[deprecated(
1287 since = "0.3.32",
1288 note = "extremely limited use case, not intended for benchmarking"
1289 )]
1290 #[expect(deprecated)]
1291 pub fn time_fn<T>(f: impl FnOnce() -> T) -> (Self, T) {
1292 let start = Instant::now();
1293 let return_value = f();
1294 let end = Instant::now();
1295
1296 (end - start, return_value)
1297 }
1298}
1299
1300impl fmt::Display for Duration {
1315 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1316 if self.is_negative() {
1317 f.write_str("-")?;
1318 }
1319
1320 if let Some(_precision) = f.precision() {
1321 if self.is_zero() {
1324 return (0.).fmt(f).and_then(|_| f.write_str("s"));
1326 }
1327
1328 macro_rules! item {
1330 ($name:literal, $value:expr) => {
1331 let value = $value;
1332 if value >= 1.0 {
1333 return value.fmt(f).and_then(|_| f.write_str($name));
1334 }
1335 };
1336 }
1337
1338 let seconds = self.unsigned_abs().as_secs_f64();
1340
1341 let value = seconds / Second::per_t::<f64>(Day);
if value >= 1.0 { return value.fmt(f).and_then(|_| f.write_str("d")); };item!("d", seconds / Second::per_t::<f64>(Day));
1342 let value = seconds / Second::per_t::<f64>(Hour);
if value >= 1.0 { return value.fmt(f).and_then(|_| f.write_str("h")); };item!("h", seconds / Second::per_t::<f64>(Hour));
1343 let value = seconds / Second::per_t::<f64>(Minute);
if value >= 1.0 { return value.fmt(f).and_then(|_| f.write_str("m")); };item!("m", seconds / Second::per_t::<f64>(Minute));
1344 let value = seconds;
if value >= 1.0 { return value.fmt(f).and_then(|_| f.write_str("s")); };item!("s", seconds);
1345 let value = seconds * Millisecond::per_t::<f64>(Second);
if value >= 1.0 { return value.fmt(f).and_then(|_| f.write_str("ms")); };item!("ms", seconds * Millisecond::per_t::<f64>(Second));
1346 let value = seconds * Microsecond::per_t::<f64>(Second);
if value >= 1.0 { return value.fmt(f).and_then(|_| f.write_str("µs")); };item!("µs", seconds * Microsecond::per_t::<f64>(Second));
1347 let value = seconds * Nanosecond::per_t::<f64>(Second);
if value >= 1.0 { return value.fmt(f).and_then(|_| f.write_str("ns")); };item!("ns", seconds * Nanosecond::per_t::<f64>(Second));
1348 } else {
1349 if self.is_zero() {
1352 return f.write_str("0s");
1353 }
1354
1355 macro_rules! item {
1357 ($name:literal, $value:expr) => {
1358 match $value {
1359 0 => Ok(()),
1360 value => value.fmt(f).and_then(|_| f.write_str($name)),
1361 }
1362 };
1363 }
1364
1365 let seconds = self.seconds.unsigned_abs();
1366 let nanoseconds = self.nanoseconds.get().unsigned_abs();
1367
1368 match seconds / Second::per_t::<u64>(Day) {
0 => Ok(()),
value => value.fmt(f).and_then(|_| f.write_str("d")),
}item!("d", seconds / Second::per_t::<u64>(Day))?;
1369 match seconds / Second::per_t::<u64>(Hour) % Hour::per_t::<u64>(Day) {
0 => Ok(()),
value => value.fmt(f).and_then(|_| f.write_str("h")),
}item!(
1370 "h",
1371 seconds / Second::per_t::<u64>(Hour) % Hour::per_t::<u64>(Day)
1372 )?;
1373 match seconds / Second::per_t::<u64>(Minute) % Minute::per_t::<u64>(Hour) {
0 => Ok(()),
value => value.fmt(f).and_then(|_| f.write_str("m")),
}item!(
1374 "m",
1375 seconds / Second::per_t::<u64>(Minute) % Minute::per_t::<u64>(Hour)
1376 )?;
1377 match seconds % Second::per_t::<u64>(Minute) {
0 => Ok(()),
value => value.fmt(f).and_then(|_| f.write_str("s")),
}item!("s", seconds % Second::per_t::<u64>(Minute))?;
1378 match nanoseconds / Nanosecond::per_t::<u32>(Millisecond) {
0 => Ok(()),
value => value.fmt(f).and_then(|_| f.write_str("ms")),
}item!("ms", nanoseconds / Nanosecond::per_t::<u32>(Millisecond))?;
1379 match nanoseconds / Nanosecond::per_t::<u32>(Microsecond) %
Microsecond::per_t::<u32>(Millisecond) {
0 => Ok(()),
value => value.fmt(f).and_then(|_| f.write_str("µs")),
}item!(
1380 "µs",
1381 nanoseconds / Nanosecond::per_t::<u32>(Microsecond)
1382 % Microsecond::per_t::<u32>(Millisecond)
1383 )?;
1384 match nanoseconds % Nanosecond::per_t::<u32>(Microsecond) {
0 => Ok(()),
value => value.fmt(f).and_then(|_| f.write_str("ns")),
}item!("ns", nanoseconds % Nanosecond::per_t::<u32>(Microsecond))?;
1385 }
1386
1387 Ok(())
1388 }
1389}
1390
1391impl TryFrom<StdDuration> for Duration {
1392 type Error = error::ConversionRange;
1393
1394 #[inline]
1395 fn try_from(original: StdDuration) -> Result<Self, error::ConversionRange> {
1396 Ok(Self::new(
1397 original
1398 .as_secs()
1399 .try_into()
1400 .map_err(|_| error::ConversionRange)?,
1401 original.subsec_nanos().cast_signed(),
1402 ))
1403 }
1404}
1405
1406impl TryFrom<Duration> for StdDuration {
1407 type Error = error::ConversionRange;
1408
1409 #[inline]
1410 fn try_from(duration: Duration) -> Result<Self, error::ConversionRange> {
1411 Ok(Self::new(
1412 duration
1413 .seconds
1414 .try_into()
1415 .map_err(|_| error::ConversionRange)?,
1416 duration
1417 .nanoseconds
1418 .get()
1419 .try_into()
1420 .map_err(|_| error::ConversionRange)?,
1421 ))
1422 }
1423}
1424
1425impl Add for Duration {
1426 type Output = Self;
1427
1428 #[inline]
1432 #[track_caller]
1433 fn add(self, rhs: Self) -> Self::Output {
1434 self.checked_add(rhs)
1435 .expect("overflow when adding durations")
1436 }
1437}
1438
1439impl Add<StdDuration> for Duration {
1440 type Output = Self;
1441
1442 #[inline]
1446 #[track_caller]
1447 fn add(self, std_duration: StdDuration) -> Self::Output {
1448 self + Self::try_from(std_duration)
1449 .expect("overflow converting `std::time::Duration` to `time::Duration`")
1450 }
1451}
1452
1453impl Add<Duration> for StdDuration {
1454 type Output = Duration;
1455
1456 #[inline]
1460 #[track_caller]
1461 fn add(self, rhs: Duration) -> Self::Output {
1462 rhs + self
1463 }
1464}
1465
1466impl AddAssign<Self> for Duration {
1467 #[inline]
1471 #[track_caller]
1472 fn add_assign(&mut self, rhs: Self) {
1473 *self = *self + rhs;
1474 }
1475}
1476
1477impl AddAssign<StdDuration> for Duration {
1478 #[inline]
1482 #[track_caller]
1483 fn add_assign(&mut self, rhs: StdDuration) {
1484 *self = *self + rhs;
1485 }
1486}
1487
1488impl AddAssign<Duration> for StdDuration {
1489 #[inline]
1493 #[track_caller]
1494 fn add_assign(&mut self, rhs: Duration) {
1495 *self = (*self + rhs).try_into().expect(
1496 "Cannot represent a resulting duration in std. Try `let x = x + rhs;`, which will \
1497 change the type.",
1498 );
1499 }
1500}
1501
1502impl Neg for Duration {
1503 type Output = Self;
1504
1505 #[inline]
1509 #[track_caller]
1510 fn neg(self) -> Self::Output {
1511 self.checked_neg().expect("overflow when negating duration")
1512 }
1513}
1514
1515impl Sub for Duration {
1516 type Output = Self;
1517
1518 #[inline]
1522 #[track_caller]
1523 fn sub(self, rhs: Self) -> Self::Output {
1524 self.checked_sub(rhs)
1525 .expect("overflow when subtracting durations")
1526 }
1527}
1528
1529impl Sub<StdDuration> for Duration {
1530 type Output = Self;
1531
1532 #[inline]
1536 #[track_caller]
1537 fn sub(self, rhs: StdDuration) -> Self::Output {
1538 self - Self::try_from(rhs)
1539 .expect("overflow converting `std::time::Duration` to `time::Duration`")
1540 }
1541}
1542
1543impl Sub<Duration> for StdDuration {
1544 type Output = Duration;
1545
1546 #[inline]
1550 #[track_caller]
1551 fn sub(self, rhs: Duration) -> Self::Output {
1552 Duration::try_from(self)
1553 .expect("overflow converting `std::time::Duration` to `time::Duration`")
1554 - rhs
1555 }
1556}
1557
1558impl SubAssign<Self> for Duration {
1559 #[inline]
1563 #[track_caller]
1564 fn sub_assign(&mut self, rhs: Self) {
1565 *self = *self - rhs;
1566 }
1567}
1568
1569impl SubAssign<StdDuration> for Duration {
1570 #[inline]
1574 #[track_caller]
1575 fn sub_assign(&mut self, rhs: StdDuration) {
1576 *self = *self - rhs;
1577 }
1578}
1579
1580impl SubAssign<Duration> for StdDuration {
1581 #[inline]
1585 #[track_caller]
1586 fn sub_assign(&mut self, rhs: Duration) {
1587 *self = (*self - rhs).try_into().expect(
1588 "Cannot represent a resulting duration in std. Try `let x = x - rhs;`, which will \
1589 change the type.",
1590 );
1591 }
1592}
1593
1594macro_rules! cast_signed {
1596 (@signed $val:ident) => {
1597 $val
1598 };
1599 (@unsigned $val:ident) => {
1600 $val.cast_signed()
1601 };
1602}
1603
1604macro_rules! duration_mul_div_int {
1607 ($(@$signedness:ident $type:ty),+ $(,)?) => {$(
1608 impl Mul<$type> for Duration {
1609 type Output = Self;
1610
1611 #[inline]
1615 #[track_caller]
1616 fn mul(self, rhs: $type) -> Self::Output {
1617 Self::nanoseconds_i128(
1618 self.whole_nanoseconds()
1619 .checked_mul(cast_signed!(@$signedness rhs).widen::<i128>())
1620 .expect("overflow when multiplying duration")
1621 )
1622 }
1623 }
1624
1625 impl Mul<Duration> for $type {
1626 type Output = Duration;
1627
1628 #[inline]
1632 #[track_caller]
1633 fn mul(self, rhs: Duration) -> Self::Output {
1634 rhs * self
1635 }
1636 }
1637
1638 impl MulAssign<$type> for Duration {
1639 #[inline]
1643 #[track_caller]
1644 fn mul_assign(&mut self, rhs: $type) {
1645 *self = *self * rhs;
1646 }
1647 }
1648
1649 impl Div<$type> for Duration {
1650 type Output = Self;
1651
1652 #[inline]
1656 #[track_caller]
1657 fn div(self, rhs: $type) -> Self::Output {
1658 Self::nanoseconds_i128(
1659 self.whole_nanoseconds() / cast_signed!(@$signedness rhs).widen::<i128>()
1660 )
1661 }
1662 }
1663
1664 impl DivAssign<$type> for Duration {
1665 #[inline]
1669 #[track_caller]
1670 fn div_assign(&mut self, rhs: $type) {
1671 *self = *self / rhs;
1672 }
1673 }
1674 )+};
1675}
1676
1677impl Mul<u32> for Duration {
type Output = Self;
#[inline]
#[track_caller]
fn mul(self, rhs: u32) -> Self::Output {
Self::nanoseconds_i128(self.whole_nanoseconds().checked_mul(rhs.cast_signed().widen::<i128>()).expect("overflow when multiplying duration"))
}
}
impl Mul<Duration> for u32 {
type Output = Duration;
#[inline]
#[track_caller]
fn mul(self, rhs: Duration) -> Self::Output { rhs * self }
}
impl MulAssign<u32> for Duration {
#[inline]
#[track_caller]
fn mul_assign(&mut self, rhs: u32) { *self = *self * rhs; }
}
impl Div<u32> for Duration {
type Output = Self;
#[inline]
#[track_caller]
fn div(self, rhs: u32) -> Self::Output {
Self::nanoseconds_i128(self.whole_nanoseconds() /
rhs.cast_signed().widen::<i128>())
}
}
impl DivAssign<u32> for Duration {
#[inline]
#[track_caller]
fn div_assign(&mut self, rhs: u32) { *self = *self / rhs; }
}duration_mul_div_int! {
1678 @signed i8,
1679 @signed i16,
1680 @signed i32,
1681 @unsigned u8,
1682 @unsigned u16,
1683 @unsigned u32,
1684}
1685
1686impl Mul<f32> for Duration {
1687 type Output = Self;
1688
1689 #[inline]
1693 #[track_caller]
1694 fn mul(self, rhs: f32) -> Self::Output {
1695 Self::seconds_f32(self.as_seconds_f32() * rhs)
1696 }
1697}
1698
1699impl Mul<Duration> for f32 {
1700 type Output = Duration;
1701
1702 #[inline]
1706 #[track_caller]
1707 fn mul(self, rhs: Duration) -> Self::Output {
1708 rhs * self
1709 }
1710}
1711
1712impl Mul<f64> for Duration {
1713 type Output = Self;
1714
1715 #[inline]
1719 #[track_caller]
1720 fn mul(self, rhs: f64) -> Self::Output {
1721 Self::seconds_f64(self.as_seconds_f64() * rhs)
1722 }
1723}
1724
1725impl Mul<Duration> for f64 {
1726 type Output = Duration;
1727
1728 #[inline]
1732 #[track_caller]
1733 fn mul(self, rhs: Duration) -> Self::Output {
1734 rhs * self
1735 }
1736}
1737
1738impl MulAssign<f32> for Duration {
1739 #[inline]
1743 #[track_caller]
1744 fn mul_assign(&mut self, rhs: f32) {
1745 *self = *self * rhs;
1746 }
1747}
1748
1749impl MulAssign<f64> for Duration {
1750 #[inline]
1754 #[track_caller]
1755 fn mul_assign(&mut self, rhs: f64) {
1756 *self = *self * rhs;
1757 }
1758}
1759
1760impl Div<f32> for Duration {
1761 type Output = Self;
1762
1763 #[inline]
1767 #[track_caller]
1768 fn div(self, rhs: f32) -> Self::Output {
1769 Self::seconds_f32(self.as_seconds_f32() / rhs)
1770 }
1771}
1772
1773impl Div<f64> for Duration {
1774 type Output = Self;
1775
1776 #[inline]
1780 #[track_caller]
1781 fn div(self, rhs: f64) -> Self::Output {
1782 Self::seconds_f64(self.as_seconds_f64() / rhs)
1783 }
1784}
1785
1786impl DivAssign<f32> for Duration {
1787 #[inline]
1791 #[track_caller]
1792 fn div_assign(&mut self, rhs: f32) {
1793 *self = *self / rhs;
1794 }
1795}
1796
1797impl DivAssign<f64> for Duration {
1798 #[inline]
1802 #[track_caller]
1803 fn div_assign(&mut self, rhs: f64) {
1804 *self = *self / rhs;
1805 }
1806}
1807
1808impl Div for Duration {
1809 type Output = f64;
1810
1811 #[inline]
1815 #[track_caller]
1816 fn div(self, rhs: Self) -> Self::Output {
1817 self.as_seconds_f64() / rhs.as_seconds_f64()
1818 }
1819}
1820
1821impl Div<StdDuration> for Duration {
1822 type Output = f64;
1823
1824 #[inline]
1828 #[track_caller]
1829 fn div(self, rhs: StdDuration) -> Self::Output {
1830 self.as_seconds_f64() / rhs.as_secs_f64()
1831 }
1832}
1833
1834impl Div<Duration> for StdDuration {
1835 type Output = f64;
1836
1837 #[inline]
1841 #[track_caller]
1842 fn div(self, rhs: Duration) -> Self::Output {
1843 self.as_secs_f64() / rhs.as_seconds_f64()
1844 }
1845}
1846
1847impl PartialEq<StdDuration> for Duration {
1848 #[inline]
1849 fn eq(&self, rhs: &StdDuration) -> bool {
1850 Ok(*self) == Self::try_from(*rhs)
1851 }
1852}
1853
1854impl PartialEq<Duration> for StdDuration {
1855 #[inline]
1856 fn eq(&self, rhs: &Duration) -> bool {
1857 rhs == self
1858 }
1859}
1860
1861impl PartialOrd<StdDuration> for Duration {
1862 #[inline]
1863 fn partial_cmp(&self, rhs: &StdDuration) -> Option<Ordering> {
1864 if rhs.as_secs() > i64::MAX.cast_unsigned() {
1865 return Some(Ordering::Less);
1866 }
1867
1868 Some(
1869 self.seconds
1870 .cmp(&rhs.as_secs().cast_signed())
1871 .then_with(|| {
1872 self.nanoseconds
1873 .get()
1874 .cmp(&rhs.subsec_nanos().cast_signed())
1875 }),
1876 )
1877 }
1878}
1879
1880impl PartialOrd<Duration> for StdDuration {
1881 #[inline]
1882 fn partial_cmp(&self, rhs: &Duration) -> Option<Ordering> {
1883 rhs.partial_cmp(self).map(Ordering::reverse)
1884 }
1885}
1886
1887impl Sum for Duration {
1888 #[inline]
1889 fn sum<I>(iter: I) -> Self
1890 where
1891 I: Iterator<Item = Self>,
1892 {
1893 iter.reduce(|a, b| a + b).unwrap_or_default()
1894 }
1895}
1896
1897impl<'a> Sum<&'a Self> for Duration {
1898 #[inline]
1899 fn sum<I>(iter: I) -> Self
1900 where
1901 I: Iterator<Item = &'a Self>,
1902 {
1903 iter.copied().sum()
1904 }
1905}
1906
1907#[cfg(feature = "std")]
1908impl Add<Duration> for SystemTime {
1909 type Output = Self;
1910
1911 #[inline]
1915 #[track_caller]
1916 fn add(self, duration: Duration) -> Self::Output {
1917 if duration.is_zero() {
1918 self
1919 } else if duration.is_positive() {
1920 self + duration.unsigned_abs()
1921 } else {
1922 if true {
if !duration.is_negative() {
::core::panicking::panic("assertion failed: duration.is_negative()")
};
};debug_assert!(duration.is_negative());
1923 self - duration.unsigned_abs()
1924 }
1925 }
1926}
1927
1928#[cfg(feature = "std")]
1929impl AddAssign<Duration> for SystemTime {
1930 #[inline]
1934 #[track_caller]
1935 fn add_assign(&mut self, rhs: Duration) {
1936 *self = *self + rhs;
1937 }
1938}
1939
1940#[cfg(feature = "std")]
1941impl Sub<Duration> for SystemTime {
1942 type Output = Self;
1943
1944 #[inline]
1945 #[track_caller]
1946 fn sub(self, duration: Duration) -> Self::Output {
1947 if duration.is_zero() {
1948 self
1949 } else if duration.is_positive() {
1950 self - duration.unsigned_abs()
1951 } else {
1952 if true {
if !duration.is_negative() {
::core::panicking::panic("assertion failed: duration.is_negative()")
};
};debug_assert!(duration.is_negative());
1953 self + duration.unsigned_abs()
1954 }
1955 }
1956}
1957
1958#[cfg(feature = "std")]
1959impl SubAssign<Duration> for SystemTime {
1960 #[inline]
1964 #[track_caller]
1965 fn sub_assign(&mut self, rhs: Duration) {
1966 *self = *self - rhs;
1967 }
1968}