1use core::cmp::Ordering;
4use core::fmt;
5use core::iter::Sum;
6use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
7use core::time::Duration as StdDuration;
8#[cfg(feature = "std")]
9use std::time::SystemTime;
10
11use deranged::RangedI32;
12use num_conv::prelude::*;
13
14#[cfg(feature = "std")]
15#[expect(deprecated)]
16use crate::Instant;
17use crate::convert::*;
18use crate::error;
19use crate::internal_macros::const_try_opt;
20
21#[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)]
22enum FloatConstructorError {
23 Nan,
24 NegOverflow,
25 PosOverflow,
26}
27
28#[repr(u32)]
31#[derive(#[automatically_derived]
impl ::core::clone::Clone for Padding {
#[inline]
fn clone(&self) -> Padding { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Padding { }Copy, #[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::cmp::PartialEq for Padding {
#[inline]
fn eq(&self, other: &Padding) -> bool { true }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Padding {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for Padding {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {}
}Hash, #[automatically_derived]
impl ::core::cmp::PartialOrd for Padding {
#[inline]
fn partial_cmp(&self, other: &Padding)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ordering::Equal)
}
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for Padding {
#[inline]
fn cmp(&self, other: &Padding) -> ::core::cmp::Ordering {
::core::cmp::Ordering::Equal
}
}Ord)]
32pub(crate) enum Padding {
33 #[allow(clippy::missing_docs_in_private_items)]
34 Optimize,
35}
36
37type Nanoseconds =
39 RangedI32<{ -Nanosecond::per_t::<i32>(Second) + 1 }, { Nanosecond::per_t::<i32>(Second) - 1 }>;
40
41#[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, #[automatically_derived]
impl ::core::cmp::PartialEq for Duration {
#[inline]
fn eq(&self, other: &Duration) -> bool {
self.seconds == other.seconds && self.nanoseconds == other.nanoseconds
&& self.padding == other.padding
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Duration {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<i64>;
let _: ::core::cmp::AssertParamIsEq<Nanoseconds>;
let _: ::core::cmp::AssertParamIsEq<Padding>;
}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for Duration {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.seconds, state);
::core::hash::Hash::hash(&self.nanoseconds, state);
::core::hash::Hash::hash(&self.padding, state)
}
}Hash, #[automatically_derived]
impl ::core::cmp::PartialOrd for Duration {
#[inline]
fn partial_cmp(&self, other: &Duration)
-> ::core::option::Option<::core::cmp::Ordering> {
match ::core::cmp::PartialOrd::partial_cmp(&self.seconds,
&other.seconds) {
::core::option::Option::Some(::core::cmp::Ordering::Equal) =>
match ::core::cmp::PartialOrd::partial_cmp(&self.nanoseconds,
&other.nanoseconds) {
::core::option::Option::Some(::core::cmp::Ordering::Equal)
=>
::core::cmp::PartialOrd::partial_cmp(&self.padding,
&other.padding),
cmp => cmp,
},
cmp => cmp,
}
}
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for Duration {
#[inline]
fn cmp(&self, other: &Duration) -> ::core::cmp::Ordering {
match ::core::cmp::Ord::cmp(&self.seconds, &other.seconds) {
::core::cmp::Ordering::Equal =>
match ::core::cmp::Ord::cmp(&self.nanoseconds,
&other.nanoseconds) {
::core::cmp::Ordering::Equal =>
::core::cmp::Ord::cmp(&self.padding, &other.padding),
cmp => cmp,
},
cmp => cmp,
}
}
}Ord)]
48pub struct Duration {
49 seconds: i64,
51 nanoseconds: Nanoseconds,
54 padding: Padding,
55}
56
57impl fmt::Debug for Duration {
58 #[inline]
59 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60 f.debug_struct("Duration")
61 .field("seconds", &self.seconds)
62 .field("nanoseconds", &self.nanoseconds)
63 .finish()
64 }
65}
66
67impl Default for Duration {
68 #[inline]
69 fn default() -> Self {
70 Self {
71 seconds: 0,
72 nanoseconds: Nanoseconds::new_static::<0>(),
73 padding: Padding::Optimize,
74 }
75 }
76}
77
78#[rustfmt::skip] macro_rules! try_from_secs {
86 (
87 secs = $secs: expr,
88 mantissa_bits = $mant_bits: literal,
89 exponent_bits = $exp_bits: literal,
90 offset = $offset: literal,
91 bits_ty = $bits_ty:ty,
92 bits_ty_signed = $bits_ty_signed:ty,
93 double_ty = $double_ty:ty,
94 float_ty = $float_ty:ty,
95 ) => {{
96 'value: {
97 const MIN_EXP: i16 = 1 - (1i16 << $exp_bits) / 2;
98 const MANT_MASK: $bits_ty = (1 << $mant_bits) - 1;
99 const EXP_MASK: $bits_ty = (1 << $exp_bits) - 1;
100
101 let bits = $secs.to_bits();
104 let mant = (bits & MANT_MASK) | (MANT_MASK + 1);
105 let exp = ((bits >> $mant_bits) & EXP_MASK) as i16 + MIN_EXP;
106
107 let (secs, nanos) = if exp < -31 {
108 (0u64, 0u32)
110 } else if exp < 0 {
111 let t = (mant as $double_ty) << ($offset + exp);
113 let nanos_offset = $mant_bits + $offset;
114 #[allow(trivial_numeric_casts)]
115 let nanos_tmp = Nanosecond::per_t::<u128>(Second) * t as u128;
116 let nanos = (nanos_tmp >> nanos_offset) as u32;
117
118 let rem_mask = (1 << nanos_offset) - 1;
119 let rem_msb_mask = 1 << (nanos_offset - 1);
120 let rem = nanos_tmp & rem_mask;
121 let is_tie = rem == rem_msb_mask;
122 let is_even = (nanos & 1) == 0;
123 let rem_msb = nanos_tmp & rem_msb_mask == 0;
124 let add_ns = !(rem_msb || (is_even && is_tie));
125
126 let nanos = nanos + add_ns as u32;
129 if ($mant_bits == 23) || (nanos != Nanosecond::per_t::<u32>(Second)) {
130 (0, nanos)
131 } else {
132 (1, 0)
133 }
134 } else if exp < $mant_bits {
135 #[allow(trivial_numeric_casts)]
136 let secs = (mant >> ($mant_bits - exp)) as u64;
137 let t = ((mant << exp) & MANT_MASK) as $double_ty;
138 let nanos_offset = $mant_bits;
139 let nanos_tmp = Nanosecond::per_t::<$double_ty>(Second) * t;
140 let nanos = (nanos_tmp >> nanos_offset) as u32;
141
142 let rem_mask = (1 << nanos_offset) - 1;
143 let rem_msb_mask = 1 << (nanos_offset - 1);
144 let rem = nanos_tmp & rem_mask;
145 let is_tie = rem == rem_msb_mask;
146 let is_even = (nanos & 1) == 0;
147 let rem_msb = nanos_tmp & rem_msb_mask == 0;
148 let add_ns = !(rem_msb || (is_even && is_tie));
149
150 let nanos = nanos + add_ns as u32;
155 if ($mant_bits == 23) || (nanos != Nanosecond::per_t::<u32>(Second)) {
156 (secs, nanos)
157 } else {
158 (secs + 1, 0)
159 }
160 } else if exp < 63 {
161 #[allow(trivial_numeric_casts)]
166 let secs = (mant as u64) << (exp - $mant_bits);
167 (secs, 0)
168 } else if bits == (i64::MIN as $float_ty).to_bits() {
169 break 'value Ok(Self::new_ranged_unchecked(i64::MIN, Nanoseconds::new_static::<0>()));
175 } else if $secs.is_nan() {
176 break 'value Err(FloatConstructorError::Nan);
179 } else if $secs.is_sign_negative() {
180 break 'value Err(FloatConstructorError::NegOverflow);
181 } else {
182 break 'value Err(FloatConstructorError::PosOverflow);
183 };
184
185 let mask = (bits as $bits_ty_signed) >> ($mant_bits + $exp_bits);
192 #[allow(trivial_numeric_casts)]
193 let secs_signed = ((secs as i64) ^ (mask as i64)) - (mask as i64);
194 #[allow(trivial_numeric_casts)]
195 let nanos_signed = ((nanos as i32) ^ (mask as i32)) - (mask as i32);
196 Ok(unsafe { Self::new_unchecked(secs_signed, nanos_signed) })
198 }
199 }};
200}
201
202impl Duration {
203 pub const ZERO: Self = Self::seconds(0);
210
211 pub const NANOSECOND: Self = Self::nanoseconds(1);
218
219 pub const MICROSECOND: Self = Self::microseconds(1);
226
227 pub const MILLISECOND: Self = Self::milliseconds(1);
234
235 pub const SECOND: Self = Self::seconds(1);
242
243 pub const MINUTE: Self = Self::minutes(1);
250
251 pub const HOUR: Self = Self::hours(1);
258
259 pub const DAY: Self = Self::days(1);
266
267 pub const WEEK: Self = Self::weeks(1);
274
275 pub const MIN: Self = Self::new_ranged(i64::MIN, Nanoseconds::MIN);
277
278 pub const MAX: Self = Self::new_ranged(i64::MAX, Nanoseconds::MAX);
280
281 #[inline]
289 pub const fn is_zero(self) -> bool {
290 self.seconds == 0 && self.nanoseconds.get() == 0
291 }
292
293 #[inline]
302 pub const fn is_negative(self) -> bool {
303 self.seconds < 0 || self.nanoseconds.get() < 0
304 }
305
306 #[inline]
315 pub const fn is_positive(self) -> bool {
316 self.seconds > 0 || self.nanoseconds.get() > 0
317 }
318
319 #[inline]
330 pub const fn abs(self) -> Self {
331 match self.seconds.checked_abs() {
332 Some(seconds) => Self::new_ranged_unchecked(seconds, self.nanoseconds.abs()),
333 None => Self::MAX,
334 }
335 }
336
337 #[inline]
347 pub const fn unsigned_abs(self) -> StdDuration {
348 StdDuration::new(
349 self.seconds.unsigned_abs(),
350 self.nanoseconds.get().unsigned_abs(),
351 )
352 }
353
354 #[inline]
363 #[track_caller]
364 pub(crate) const unsafe fn new_unchecked(seconds: i64, nanoseconds: i32) -> Self {
365 Self::new_ranged_unchecked(
366 seconds,
367 unsafe { Nanoseconds::new_unchecked(nanoseconds) },
369 )
370 }
371
372 #[inline]
374 #[track_caller]
375 pub(crate) const fn new_ranged_unchecked(seconds: i64, nanoseconds: Nanoseconds) -> Self {
376 if seconds < 0 {
377 if true {
if !(nanoseconds.get() <= 0) {
::core::panicking::panic("assertion failed: nanoseconds.get() <= 0")
};
};debug_assert!(nanoseconds.get() <= 0);
378 } else if seconds > 0 {
379 if true {
if !(nanoseconds.get() >= 0) {
::core::panicking::panic("assertion failed: nanoseconds.get() >= 0")
};
};debug_assert!(nanoseconds.get() >= 0);
380 }
381
382 Self {
383 seconds,
384 nanoseconds,
385 padding: Padding::Optimize,
386 }
387 }
388
389 #[inline]
403 #[track_caller]
404 pub const fn new(mut seconds: i64, mut nanoseconds: i32) -> Self {
405 seconds = seconds
406 .checked_add(nanoseconds as i64 / Nanosecond::per_t::<i64>(Second))
407 .expect("overflow constructing `time::Duration`");
408 nanoseconds %= Nanosecond::per_t::<i32>(Second);
409
410 if seconds > 0 && nanoseconds < 0 {
411 seconds -= 1;
413 nanoseconds += Nanosecond::per_t::<i32>(Second);
414 } else if seconds < 0 && nanoseconds > 0 {
415 seconds += 1;
417 nanoseconds -= Nanosecond::per_t::<i32>(Second);
418 }
419
420 unsafe { Self::new_unchecked(seconds, nanoseconds) }
422 }
423
424 #[inline]
426 pub(crate) const fn new_ranged(mut seconds: i64, mut nanoseconds: Nanoseconds) -> Self {
427 if seconds > 0 && nanoseconds.get() < 0 {
428 seconds -= 1;
430 nanoseconds = unsafe {
433 Nanoseconds::new_unchecked(nanoseconds.get() + Nanosecond::per_t::<i32>(Second))
434 };
435 } else if seconds < 0 && nanoseconds.get() > 0 {
436 seconds += 1;
438 nanoseconds = unsafe {
441 Nanoseconds::new_unchecked(nanoseconds.get() - Nanosecond::per_t::<i32>(Second))
442 };
443 }
444
445 Self::new_ranged_unchecked(seconds, nanoseconds)
446 }
447
448 #[inline]
460 #[track_caller]
461 pub const fn weeks(weeks: i64) -> Self {
462 Self::seconds(
463 weeks
464 .checked_mul(Second::per_t(Week))
465 .expect("overflow constructing `time::Duration`"),
466 )
467 }
468
469 #[inline]
481 #[track_caller]
482 pub const fn days(days: i64) -> Self {
483 Self::seconds(
484 days.checked_mul(Second::per_t(Day))
485 .expect("overflow constructing `time::Duration`"),
486 )
487 }
488
489 #[inline]
501 #[track_caller]
502 pub const fn hours(hours: i64) -> Self {
503 Self::seconds(
504 hours
505 .checked_mul(Second::per_t(Hour))
506 .expect("overflow constructing `time::Duration`"),
507 )
508 }
509
510 #[inline]
522 #[track_caller]
523 pub const fn minutes(minutes: i64) -> Self {
524 Self::seconds(
525 minutes
526 .checked_mul(Second::per_t(Minute))
527 .expect("overflow constructing `time::Duration`"),
528 )
529 }
530
531 #[inline]
538 pub const fn seconds(seconds: i64) -> Self {
539 Self::new_ranged_unchecked(seconds, Nanoseconds::new_static::<0>())
540 }
541
542 #[inline]
547 const fn try_seconds_f64(seconds: f64) -> Result<Self, FloatConstructorError> {
548 {
'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!(
549 secs = seconds,
550 mantissa_bits = 52,
551 exponent_bits = 11,
552 offset = 44,
553 bits_ty = u64,
554 bits_ty_signed = i64,
555 double_ty = u128,
556 float_ty = f64,
557 )
558 }
559
560 #[inline]
565 const fn try_seconds_f32(seconds: f32) -> Result<Self, FloatConstructorError> {
566 {
'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!(
567 secs = seconds,
568 mantissa_bits = 23,
569 exponent_bits = 8,
570 offset = 41,
571 bits_ty = u32,
572 bits_ty_signed = i32,
573 double_ty = u64,
574 float_ty = f32,
575 )
576 }
577
578 #[inline(never)]
586 #[track_caller]
587 pub const fn seconds_f64(seconds: f64) -> Self {
588 match Self::try_seconds_f64(seconds) {
589 Ok(duration) => duration,
590 Err(FloatConstructorError::Nan) => {
591 {
::core::panicking::panic_fmt(format_args!("passed NaN to `time::Duration::seconds_f64`"));
};panic!("passed NaN to `time::Duration::seconds_f64`");
592 }
593 Err(FloatConstructorError::NegOverflow | FloatConstructorError::PosOverflow) => {
594 {
::core::panicking::panic_fmt(format_args!("overflow constructing `time::Duration`"));
};panic!("overflow constructing `time::Duration`");
595 }
596 }
597 }
598
599 #[inline]
607 #[track_caller]
608 pub const fn seconds_f32(seconds: f32) -> Self {
609 match Self::try_seconds_f32(seconds) {
610 Ok(duration) => duration,
611 Err(FloatConstructorError::Nan) => {
612 {
::core::panicking::panic_fmt(format_args!("passed NaN to `time::Duration::seconds_f32`"));
};panic!("passed NaN to `time::Duration::seconds_f32`");
613 }
614 Err(FloatConstructorError::NegOverflow | FloatConstructorError::PosOverflow) => {
615 {
::core::panicking::panic_fmt(format_args!("overflow constructing `time::Duration`"));
};panic!("overflow constructing `time::Duration`");
616 }
617 }
618 }
619
620 #[inline(never)]
643 pub const fn saturating_seconds_f64(seconds: f64) -> Self {
644 match Self::try_seconds_f64(seconds) {
645 Ok(duration) => duration,
646 Err(FloatConstructorError::Nan) => Self::ZERO,
647 Err(FloatConstructorError::NegOverflow) => Self::MIN,
648 Err(FloatConstructorError::PosOverflow) => Self::MAX,
649 }
650 }
651
652 #[inline]
675 pub const fn saturating_seconds_f32(seconds: f32) -> Self {
676 match Self::try_seconds_f32(seconds) {
677 Ok(duration) => duration,
678 Err(FloatConstructorError::Nan) => Self::ZERO,
679 Err(FloatConstructorError::NegOverflow) => Self::MIN,
680 Err(FloatConstructorError::PosOverflow) => Self::MAX,
681 }
682 }
683
684 #[inline]
697 pub const fn checked_seconds_f64(seconds: f64) -> Option<Self> {
698 match Self::try_seconds_f64(seconds) {
699 Ok(duration) => Some(duration),
700 Err(_) => None,
701 }
702 }
703
704 #[inline]
717 pub const fn checked_seconds_f32(seconds: f32) -> Option<Self> {
718 match Self::try_seconds_f32(seconds) {
719 Ok(duration) => Some(duration),
720 Err(_) => None,
721 }
722 }
723
724 #[inline]
732 pub const fn milliseconds(milliseconds: i64) -> Self {
733 unsafe {
735 Self::new_unchecked(
736 milliseconds / Millisecond::per_t::<i64>(Second),
737 (milliseconds % Millisecond::per_t::<i64>(Second)
738 * Nanosecond::per_t::<i64>(Millisecond)) as i32,
739 )
740 }
741 }
742
743 #[inline]
751 pub const fn microseconds(microseconds: i64) -> Self {
752 unsafe {
754 Self::new_unchecked(
755 microseconds / Microsecond::per_t::<i64>(Second),
756 (microseconds % Microsecond::per_t::<i64>(Second)
757 * Nanosecond::per_t::<i64>(Microsecond)) as i32,
758 )
759 }
760 }
761
762 #[inline]
770 pub const fn nanoseconds(nanoseconds: i64) -> Self {
771 unsafe {
773 Self::new_unchecked(
774 nanoseconds / Nanosecond::per_t::<i64>(Second),
775 (nanoseconds % Nanosecond::per_t::<i64>(Second)) as i32,
776 )
777 }
778 }
779
780 #[inline]
795 #[track_caller]
796 pub const fn nanoseconds_i128(nanoseconds: i128) -> Self {
797 let seconds = nanoseconds / Nanosecond::per_t::<i128>(Second);
798 let nanoseconds = nanoseconds % Nanosecond::per_t::<i128>(Second);
799
800 if seconds > i64::MAX as i128 || seconds < i64::MIN as i128 {
801 {
::core::panicking::panic_fmt(format_args!("overflow constructing `time::Duration`"));
};panic!("overflow constructing `time::Duration`");
802 }
803
804 unsafe { Self::new_unchecked(seconds as i64, nanoseconds as i32) }
806 }
807
808 #[inline]
818 pub const fn whole_weeks(self) -> i64 {
819 self.whole_seconds() / Second::per_t::<i64>(Week)
820 }
821
822 #[inline]
832 pub const fn whole_days(self) -> i64 {
833 self.whole_seconds() / Second::per_t::<i64>(Day)
834 }
835
836 #[inline]
846 pub const fn whole_hours(self) -> i64 {
847 self.whole_seconds() / Second::per_t::<i64>(Hour)
848 }
849
850 #[inline]
860 pub const fn whole_minutes(self) -> i64 {
861 self.whole_seconds() / Second::per_t::<i64>(Minute)
862 }
863
864 #[inline]
874 pub const fn whole_seconds(self) -> i64 {
875 self.seconds
876 }
877
878 #[inline]
886 pub const fn as_seconds_f64(self) -> f64 {
887 self.seconds as f64 + self.nanoseconds.get() as f64 / Nanosecond::per_t::<f64>(Second)
888 }
889
890 #[inline]
898 pub const fn as_seconds_f32(self) -> f32 {
899 self.seconds as f32 + self.nanoseconds.get() as f32 / Nanosecond::per_t::<f32>(Second)
900 }
901
902 #[inline]
912 pub const fn whole_milliseconds(self) -> i128 {
913 self.seconds as i128 * Millisecond::per_t::<i128>(Second)
914 + self.nanoseconds.get() as i128 / Nanosecond::per_t::<i128>(Millisecond)
915 }
916
917 #[inline]
927 pub const fn subsec_milliseconds(self) -> i16 {
928 (self.nanoseconds.get() / Nanosecond::per_t::<i32>(Millisecond)) as i16
929 }
930
931 #[inline]
941 pub const fn whole_microseconds(self) -> i128 {
942 self.seconds as i128 * Microsecond::per_t::<i128>(Second)
943 + self.nanoseconds.get() as i128 / Nanosecond::per_t::<i128>(Microsecond)
944 }
945
946 #[inline]
956 pub const fn subsec_microseconds(self) -> i32 {
957 self.nanoseconds.get() / Nanosecond::per_t::<i32>(Microsecond)
958 }
959
960 #[inline]
970 pub const fn whole_nanoseconds(self) -> i128 {
971 self.seconds as i128 * Nanosecond::per_t::<i128>(Second) + self.nanoseconds.get() as i128
972 }
973
974 #[inline]
984 pub const fn subsec_nanoseconds(self) -> i32 {
985 self.nanoseconds.get()
986 }
987
988 #[cfg(feature = "quickcheck")]
990 #[inline]
991 pub(crate) const fn subsec_nanoseconds_ranged(self) -> Nanoseconds {
992 self.nanoseconds
993 }
994
995 #[inline]
1004 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
1005 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));
1006 let mut nanoseconds = self.nanoseconds.get() + rhs.nanoseconds.get();
1007
1008 if nanoseconds >= Nanosecond::per_t(Second) || seconds < 0 && nanoseconds > 0 {
1009 nanoseconds -= Nanosecond::per_t::<i32>(Second);
1010 seconds = match seconds.checked_add(1) {
Some(value) => value,
None => { crate::hint::cold_path(); return None; }
}const_try_opt!(seconds.checked_add(1));
1011 } else if nanoseconds <= -Nanosecond::per_t::<i32>(Second) || seconds > 0 && nanoseconds < 0
1012 {
1013 nanoseconds += Nanosecond::per_t::<i32>(Second);
1014 seconds = match seconds.checked_sub(1) {
Some(value) => value,
None => { crate::hint::cold_path(); return None; }
}const_try_opt!(seconds.checked_sub(1));
1015 }
1016
1017 unsafe { Some(Self::new_unchecked(seconds, nanoseconds)) }
1019 }
1020
1021 #[inline]
1030 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
1031 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));
1032 let mut nanoseconds = self.nanoseconds.get() - rhs.nanoseconds.get();
1033
1034 if nanoseconds >= Nanosecond::per_t(Second) || seconds < 0 && nanoseconds > 0 {
1035 nanoseconds -= Nanosecond::per_t::<i32>(Second);
1036 seconds = match seconds.checked_add(1) {
Some(value) => value,
None => { crate::hint::cold_path(); return None; }
}const_try_opt!(seconds.checked_add(1));
1037 } else if nanoseconds <= -Nanosecond::per_t::<i32>(Second) || seconds > 0 && nanoseconds < 0
1038 {
1039 nanoseconds += Nanosecond::per_t::<i32>(Second);
1040 seconds = match seconds.checked_sub(1) {
Some(value) => value,
None => { crate::hint::cold_path(); return None; }
}const_try_opt!(seconds.checked_sub(1));
1041 }
1042
1043 unsafe { Some(Self::new_unchecked(seconds, nanoseconds)) }
1045 }
1046
1047 #[inline]
1058 pub const fn checked_mul(self, rhs: i32) -> Option<Self> {
1059 let total_nanos = self.nanoseconds.get() as i64 * rhs as i64;
1061 let extra_secs = total_nanos / Nanosecond::per_t::<i64>(Second);
1062 let nanoseconds = (total_nanos % Nanosecond::per_t::<i64>(Second)) as i32;
1063 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!(
1064 const_try_opt!(self.seconds.checked_mul(rhs as i64)).checked_add(extra_secs)
1065 );
1066
1067 unsafe { Some(Self::new_unchecked(seconds, nanoseconds)) }
1069 }
1070
1071 #[inline]
1080 pub const fn checked_div(self, rhs: i32) -> Option<Self> {
1081 let (secs, extra_secs) = (
1082 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)),
1083 self.seconds % (rhs as i64),
1084 );
1085 let (mut nanos, extra_nanos) = (self.nanoseconds.get() / rhs, self.nanoseconds.get() % rhs);
1086 nanos += ((extra_secs * (Nanosecond::per_t::<i64>(Second)) + extra_nanos as i64)
1087 / (rhs as i64)) as i32;
1088
1089 unsafe { Some(Self::new_unchecked(secs, nanos)) }
1091 }
1092
1093 #[inline]
1102 pub const fn checked_neg(self) -> Option<Self> {
1103 if self.seconds == i64::MIN {
1104 None
1105 } else {
1106 Some(Self::new_ranged_unchecked(
1107 -self.seconds,
1108 self.nanoseconds.neg(),
1109 ))
1110 }
1111 }
1112
1113 #[inline]
1126 pub const fn saturating_add(self, rhs: Self) -> Self {
1127 let (mut seconds, overflow) = self.seconds.overflowing_add(rhs.seconds);
1128 if overflow {
1129 if self.seconds > 0 {
1130 return Self::MAX;
1131 }
1132 return Self::MIN;
1133 }
1134 let mut nanoseconds = self.nanoseconds.get() + rhs.nanoseconds.get();
1135
1136 if nanoseconds >= Nanosecond::per_t(Second) || seconds < 0 && nanoseconds > 0 {
1137 nanoseconds -= Nanosecond::per_t::<i32>(Second);
1138 seconds = match seconds.checked_add(1) {
1139 Some(seconds) => seconds,
1140 None => return Self::MAX,
1141 };
1142 } else if nanoseconds <= -Nanosecond::per_t::<i32>(Second) || seconds > 0 && nanoseconds < 0
1143 {
1144 nanoseconds += Nanosecond::per_t::<i32>(Second);
1145 seconds = match seconds.checked_sub(1) {
1146 Some(seconds) => seconds,
1147 None => return Self::MIN,
1148 };
1149 }
1150
1151 unsafe { Self::new_unchecked(seconds, nanoseconds) }
1153 }
1154
1155 #[inline]
1168 pub const fn saturating_sub(self, rhs: Self) -> Self {
1169 let (mut seconds, overflow) = self.seconds.overflowing_sub(rhs.seconds);
1170 if overflow {
1171 if self.seconds > 0 {
1172 return Self::MAX;
1173 }
1174 return Self::MIN;
1175 }
1176 let mut nanoseconds = self.nanoseconds.get() - rhs.nanoseconds.get();
1177
1178 if nanoseconds >= Nanosecond::per_t(Second) || seconds < 0 && nanoseconds > 0 {
1179 nanoseconds -= Nanosecond::per_t::<i32>(Second);
1180 seconds = match seconds.checked_add(1) {
1181 Some(seconds) => seconds,
1182 None => return Self::MAX,
1183 };
1184 } else if nanoseconds <= -Nanosecond::per_t::<i32>(Second) || seconds > 0 && nanoseconds < 0
1185 {
1186 nanoseconds += Nanosecond::per_t::<i32>(Second);
1187 seconds = match seconds.checked_sub(1) {
1188 Some(seconds) => seconds,
1189 None => return Self::MIN,
1190 };
1191 }
1192
1193 unsafe { Self::new_unchecked(seconds, nanoseconds) }
1195 }
1196
1197 #[inline]
1210 pub const fn saturating_mul(self, rhs: i32) -> Self {
1211 let total_nanos = self.nanoseconds.get() as i64 * rhs as i64;
1213 let extra_secs = total_nanos / Nanosecond::per_t::<i64>(Second);
1214 let nanoseconds = (total_nanos % Nanosecond::per_t::<i64>(Second)) as i32;
1215 let (seconds, overflow1) = self.seconds.overflowing_mul(rhs as i64);
1216 if overflow1 {
1217 if self.seconds > 0 && rhs > 0 || self.seconds < 0 && rhs < 0 {
1218 return Self::MAX;
1219 }
1220 return Self::MIN;
1221 }
1222 let (seconds, overflow2) = seconds.overflowing_add(extra_secs);
1223 if overflow2 {
1224 if self.seconds > 0 && rhs > 0 {
1225 return Self::MAX;
1226 }
1227 return Self::MIN;
1228 }
1229
1230 unsafe { Self::new_unchecked(seconds, nanoseconds) }
1232 }
1233
1234 #[cfg(feature = "std")]
1237 #[doc(hidden)]
1238 #[inline]
1239 #[track_caller]
1240 #[deprecated(
1241 since = "0.3.32",
1242 note = "extremely limited use case, not intended for benchmarking"
1243 )]
1244 #[expect(deprecated)]
1245 pub fn time_fn<T>(f: impl FnOnce() -> T) -> (Self, T) {
1246 let start = Instant::now();
1247 let return_value = f();
1248 let end = Instant::now();
1249
1250 (end - start, return_value)
1251 }
1252}
1253
1254impl fmt::Display for Duration {
1269 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1270 if self.is_negative() {
1271 f.write_str("-")?;
1272 }
1273
1274 if let Some(_precision) = f.precision() {
1275 if self.is_zero() {
1278 return (0.).fmt(f).and_then(|_| f.write_str("s"));
1280 }
1281
1282 macro_rules! item {
1284 ($name:literal, $value:expr) => {
1285 let value = $value;
1286 if value >= 1.0 {
1287 return value.fmt(f).and_then(|_| f.write_str($name));
1288 }
1289 };
1290 }
1291
1292 let seconds = self.unsigned_abs().as_secs_f64();
1294
1295 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));
1296 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));
1297 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));
1298 let value = seconds;
if value >= 1.0 { return value.fmt(f).and_then(|_| f.write_str("s")); };item!("s", seconds);
1299 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));
1300 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));
1301 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));
1302 } else {
1303 if self.is_zero() {
1306 return f.write_str("0s");
1307 }
1308
1309 macro_rules! item {
1311 ($name:literal, $value:expr) => {
1312 match $value {
1313 0 => Ok(()),
1314 value => value.fmt(f).and_then(|_| f.write_str($name)),
1315 }
1316 };
1317 }
1318
1319 let seconds = self.seconds.unsigned_abs();
1320 let nanoseconds = self.nanoseconds.get().unsigned_abs();
1321
1322 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))?;
1323 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!(
1324 "h",
1325 seconds / Second::per_t::<u64>(Hour) % Hour::per_t::<u64>(Day)
1326 )?;
1327 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!(
1328 "m",
1329 seconds / Second::per_t::<u64>(Minute) % Minute::per_t::<u64>(Hour)
1330 )?;
1331 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))?;
1332 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))?;
1333 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!(
1334 "µs",
1335 nanoseconds / Nanosecond::per_t::<u32>(Microsecond)
1336 % Microsecond::per_t::<u32>(Millisecond)
1337 )?;
1338 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))?;
1339 }
1340
1341 Ok(())
1342 }
1343}
1344
1345impl TryFrom<StdDuration> for Duration {
1346 type Error = error::ConversionRange;
1347
1348 #[inline]
1349 fn try_from(original: StdDuration) -> Result<Self, error::ConversionRange> {
1350 Ok(Self::new(
1351 original
1352 .as_secs()
1353 .try_into()
1354 .map_err(|_| error::ConversionRange)?,
1355 original.subsec_nanos().cast_signed(),
1356 ))
1357 }
1358}
1359
1360impl TryFrom<Duration> for StdDuration {
1361 type Error = error::ConversionRange;
1362
1363 #[inline]
1364 fn try_from(duration: Duration) -> Result<Self, error::ConversionRange> {
1365 Ok(Self::new(
1366 duration
1367 .seconds
1368 .try_into()
1369 .map_err(|_| error::ConversionRange)?,
1370 duration
1371 .nanoseconds
1372 .get()
1373 .try_into()
1374 .map_err(|_| error::ConversionRange)?,
1375 ))
1376 }
1377}
1378
1379impl Add for Duration {
1380 type Output = Self;
1381
1382 #[inline]
1386 #[track_caller]
1387 fn add(self, rhs: Self) -> Self::Output {
1388 self.checked_add(rhs)
1389 .expect("overflow when adding durations")
1390 }
1391}
1392
1393impl Add<StdDuration> for Duration {
1394 type Output = Self;
1395
1396 #[inline]
1400 #[track_caller]
1401 fn add(self, std_duration: StdDuration) -> Self::Output {
1402 self + Self::try_from(std_duration)
1403 .expect("overflow converting `std::time::Duration` to `time::Duration`")
1404 }
1405}
1406
1407impl Add<Duration> for StdDuration {
1408 type Output = Duration;
1409
1410 #[inline]
1414 #[track_caller]
1415 fn add(self, rhs: Duration) -> Self::Output {
1416 rhs + self
1417 }
1418}
1419
1420impl AddAssign<Self> for Duration {
1421 #[inline]
1425 #[track_caller]
1426 fn add_assign(&mut self, rhs: Self) {
1427 *self = *self + rhs;
1428 }
1429}
1430
1431impl AddAssign<StdDuration> for Duration {
1432 #[inline]
1436 #[track_caller]
1437 fn add_assign(&mut self, rhs: StdDuration) {
1438 *self = *self + rhs;
1439 }
1440}
1441
1442impl AddAssign<Duration> for StdDuration {
1443 #[inline]
1447 #[track_caller]
1448 fn add_assign(&mut self, rhs: Duration) {
1449 *self = (*self + rhs).try_into().expect(
1450 "Cannot represent a resulting duration in std. Try `let x = x + rhs;`, which will \
1451 change the type.",
1452 );
1453 }
1454}
1455
1456impl Neg for Duration {
1457 type Output = Self;
1458
1459 #[inline]
1463 #[track_caller]
1464 fn neg(self) -> Self::Output {
1465 self.checked_neg().expect("overflow when negating duration")
1466 }
1467}
1468
1469impl Sub for Duration {
1470 type Output = Self;
1471
1472 #[inline]
1476 #[track_caller]
1477 fn sub(self, rhs: Self) -> Self::Output {
1478 self.checked_sub(rhs)
1479 .expect("overflow when subtracting durations")
1480 }
1481}
1482
1483impl Sub<StdDuration> for Duration {
1484 type Output = Self;
1485
1486 #[inline]
1490 #[track_caller]
1491 fn sub(self, rhs: StdDuration) -> Self::Output {
1492 self - Self::try_from(rhs)
1493 .expect("overflow converting `std::time::Duration` to `time::Duration`")
1494 }
1495}
1496
1497impl Sub<Duration> for StdDuration {
1498 type Output = Duration;
1499
1500 #[inline]
1504 #[track_caller]
1505 fn sub(self, rhs: Duration) -> Self::Output {
1506 Duration::try_from(self)
1507 .expect("overflow converting `std::time::Duration` to `time::Duration`")
1508 - rhs
1509 }
1510}
1511
1512impl SubAssign<Self> for Duration {
1513 #[inline]
1517 #[track_caller]
1518 fn sub_assign(&mut self, rhs: Self) {
1519 *self = *self - rhs;
1520 }
1521}
1522
1523impl SubAssign<StdDuration> for Duration {
1524 #[inline]
1528 #[track_caller]
1529 fn sub_assign(&mut self, rhs: StdDuration) {
1530 *self = *self - rhs;
1531 }
1532}
1533
1534impl SubAssign<Duration> for StdDuration {
1535 #[inline]
1539 #[track_caller]
1540 fn sub_assign(&mut self, rhs: Duration) {
1541 *self = (*self - rhs).try_into().expect(
1542 "Cannot represent a resulting duration in std. Try `let x = x - rhs;`, which will \
1543 change the type.",
1544 );
1545 }
1546}
1547
1548macro_rules! cast_signed {
1550 (@signed $val:ident) => {
1551 $val
1552 };
1553 (@unsigned $val:ident) => {
1554 $val.cast_signed()
1555 };
1556}
1557
1558macro_rules! duration_mul_div_int {
1561 ($(@$signedness:ident $type:ty),+ $(,)?) => {$(
1562 impl Mul<$type> for Duration {
1563 type Output = Self;
1564
1565 #[inline]
1569 #[track_caller]
1570 fn mul(self, rhs: $type) -> Self::Output {
1571 Self::nanoseconds_i128(
1572 self.whole_nanoseconds()
1573 .checked_mul(cast_signed!(@$signedness rhs).extend::<i128>())
1574 .expect("overflow when multiplying duration")
1575 )
1576 }
1577 }
1578
1579 impl Mul<Duration> for $type {
1580 type Output = Duration;
1581
1582 #[inline]
1586 #[track_caller]
1587 fn mul(self, rhs: Duration) -> Self::Output {
1588 rhs * self
1589 }
1590 }
1591
1592 impl MulAssign<$type> for Duration {
1593 #[inline]
1597 #[track_caller]
1598 fn mul_assign(&mut self, rhs: $type) {
1599 *self = *self * rhs;
1600 }
1601 }
1602
1603 impl Div<$type> for Duration {
1604 type Output = Self;
1605
1606 #[inline]
1610 #[track_caller]
1611 fn div(self, rhs: $type) -> Self::Output {
1612 Self::nanoseconds_i128(
1613 self.whole_nanoseconds() / cast_signed!(@$signedness rhs).extend::<i128>()
1614 )
1615 }
1616 }
1617
1618 impl DivAssign<$type> for Duration {
1619 #[inline]
1623 #[track_caller]
1624 fn div_assign(&mut self, rhs: $type) {
1625 *self = *self / rhs;
1626 }
1627 }
1628 )+};
1629}
1630
1631impl 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().extend::<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().extend::<i128>())
}
}
impl DivAssign<u32> for Duration {
#[inline]
#[track_caller]
fn div_assign(&mut self, rhs: u32) { *self = *self / rhs; }
}duration_mul_div_int! {
1632 @signed i8,
1633 @signed i16,
1634 @signed i32,
1635 @unsigned u8,
1636 @unsigned u16,
1637 @unsigned u32,
1638}
1639
1640impl Mul<f32> for Duration {
1641 type Output = Self;
1642
1643 #[inline]
1647 #[track_caller]
1648 fn mul(self, rhs: f32) -> Self::Output {
1649 Self::seconds_f32(self.as_seconds_f32() * rhs)
1650 }
1651}
1652
1653impl Mul<Duration> for f32 {
1654 type Output = Duration;
1655
1656 #[inline]
1660 #[track_caller]
1661 fn mul(self, rhs: Duration) -> Self::Output {
1662 rhs * self
1663 }
1664}
1665
1666impl Mul<f64> for Duration {
1667 type Output = Self;
1668
1669 #[inline]
1673 #[track_caller]
1674 fn mul(self, rhs: f64) -> Self::Output {
1675 Self::seconds_f64(self.as_seconds_f64() * rhs)
1676 }
1677}
1678
1679impl Mul<Duration> for f64 {
1680 type Output = Duration;
1681
1682 #[inline]
1686 #[track_caller]
1687 fn mul(self, rhs: Duration) -> Self::Output {
1688 rhs * self
1689 }
1690}
1691
1692impl MulAssign<f32> for Duration {
1693 #[inline]
1697 #[track_caller]
1698 fn mul_assign(&mut self, rhs: f32) {
1699 *self = *self * rhs;
1700 }
1701}
1702
1703impl MulAssign<f64> for Duration {
1704 #[inline]
1708 #[track_caller]
1709 fn mul_assign(&mut self, rhs: f64) {
1710 *self = *self * rhs;
1711 }
1712}
1713
1714impl Div<f32> for Duration {
1715 type Output = Self;
1716
1717 #[inline]
1721 #[track_caller]
1722 fn div(self, rhs: f32) -> Self::Output {
1723 Self::seconds_f32(self.as_seconds_f32() / rhs)
1724 }
1725}
1726
1727impl Div<f64> for Duration {
1728 type Output = Self;
1729
1730 #[inline]
1734 #[track_caller]
1735 fn div(self, rhs: f64) -> Self::Output {
1736 Self::seconds_f64(self.as_seconds_f64() / rhs)
1737 }
1738}
1739
1740impl DivAssign<f32> for Duration {
1741 #[inline]
1745 #[track_caller]
1746 fn div_assign(&mut self, rhs: f32) {
1747 *self = *self / rhs;
1748 }
1749}
1750
1751impl DivAssign<f64> for Duration {
1752 #[inline]
1756 #[track_caller]
1757 fn div_assign(&mut self, rhs: f64) {
1758 *self = *self / rhs;
1759 }
1760}
1761
1762impl Div for Duration {
1763 type Output = f64;
1764
1765 #[inline]
1766 #[track_caller]
1767 fn div(self, rhs: Self) -> Self::Output {
1768 self.as_seconds_f64() / rhs.as_seconds_f64()
1769 }
1770}
1771
1772impl Div<StdDuration> for Duration {
1773 type Output = f64;
1774
1775 #[inline]
1776 #[track_caller]
1777 fn div(self, rhs: StdDuration) -> Self::Output {
1778 self.as_seconds_f64() / rhs.as_secs_f64()
1779 }
1780}
1781
1782impl Div<Duration> for StdDuration {
1783 type Output = f64;
1784
1785 #[inline]
1786 #[track_caller]
1787 fn div(self, rhs: Duration) -> Self::Output {
1788 self.as_secs_f64() / rhs.as_seconds_f64()
1789 }
1790}
1791
1792impl PartialEq<StdDuration> for Duration {
1793 #[inline]
1794 fn eq(&self, rhs: &StdDuration) -> bool {
1795 Ok(*self) == Self::try_from(*rhs)
1796 }
1797}
1798
1799impl PartialEq<Duration> for StdDuration {
1800 #[inline]
1801 fn eq(&self, rhs: &Duration) -> bool {
1802 rhs == self
1803 }
1804}
1805
1806impl PartialOrd<StdDuration> for Duration {
1807 #[inline]
1808 fn partial_cmp(&self, rhs: &StdDuration) -> Option<Ordering> {
1809 if rhs.as_secs() > i64::MAX.cast_unsigned() {
1810 return Some(Ordering::Less);
1811 }
1812
1813 Some(
1814 self.seconds
1815 .cmp(&rhs.as_secs().cast_signed())
1816 .then_with(|| {
1817 self.nanoseconds
1818 .get()
1819 .cmp(&rhs.subsec_nanos().cast_signed())
1820 }),
1821 )
1822 }
1823}
1824
1825impl PartialOrd<Duration> for StdDuration {
1826 #[inline]
1827 fn partial_cmp(&self, rhs: &Duration) -> Option<Ordering> {
1828 rhs.partial_cmp(self).map(Ordering::reverse)
1829 }
1830}
1831
1832impl Sum for Duration {
1833 #[inline]
1834 fn sum<I>(iter: I) -> Self
1835 where
1836 I: Iterator<Item = Self>,
1837 {
1838 iter.reduce(|a, b| a + b).unwrap_or_default()
1839 }
1840}
1841
1842impl<'a> Sum<&'a Self> for Duration {
1843 #[inline]
1844 fn sum<I>(iter: I) -> Self
1845 where
1846 I: Iterator<Item = &'a Self>,
1847 {
1848 iter.copied().sum()
1849 }
1850}
1851
1852#[cfg(feature = "std")]
1853impl Add<Duration> for SystemTime {
1854 type Output = Self;
1855
1856 #[inline]
1860 #[track_caller]
1861 fn add(self, duration: Duration) -> Self::Output {
1862 if duration.is_zero() {
1863 self
1864 } else if duration.is_positive() {
1865 self + duration.unsigned_abs()
1866 } else {
1867 if true {
if !duration.is_negative() {
::core::panicking::panic("assertion failed: duration.is_negative()")
};
};debug_assert!(duration.is_negative());
1868 self - duration.unsigned_abs()
1869 }
1870 }
1871}
1872
1873#[cfg(feature = "std")]
1874impl AddAssign<Duration> for SystemTime {
1875 #[inline]
1879 #[track_caller]
1880 fn add_assign(&mut self, rhs: Duration) {
1881 *self = *self + rhs;
1882 }
1883}
1884
1885#[cfg(feature = "std")]
1886impl Sub<Duration> for SystemTime {
1887 type Output = Self;
1888
1889 #[inline]
1890 #[track_caller]
1891 fn sub(self, duration: Duration) -> Self::Output {
1892 if duration.is_zero() {
1893 self
1894 } else if duration.is_positive() {
1895 self - duration.unsigned_abs()
1896 } else {
1897 if true {
if !duration.is_negative() {
::core::panicking::panic("assertion failed: duration.is_negative()")
};
};debug_assert!(duration.is_negative());
1898 self + duration.unsigned_abs()
1899 }
1900 }
1901}
1902
1903#[cfg(feature = "std")]
1904impl SubAssign<Duration> for SystemTime {
1905 #[inline]
1909 #[track_caller]
1910 fn sub_assign(&mut self, rhs: Duration) {
1911 *self = *self - rhs;
1912 }
1913}