1 #![stable(feature = "duration_core", since = "1.25.0")]
3 //! Temporal quantification.
8 //! use std::time::Duration;
10 //! let five_seconds = Duration::new(5, 0);
11 //! // both declarations are equivalent
12 //! assert_eq!(Duration::new(5, 0), Duration::from_secs(5));
17 use crate::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
19 const NANOS_PER_SEC: u32 = 1_000_000_000;
20 const NANOS_PER_MILLI: u32 = 1_000_000;
21 const NANOS_PER_MICRO: u32 = 1_000;
22 const MILLIS_PER_SEC: u64 = 1_000;
23 const MICROS_PER_SEC: u64 = 1_000_000;
25 /// A `Duration` type to represent a span of time, typically used for system
28 /// Each `Duration` is composed of a whole number of seconds and a fractional part
29 /// represented in nanoseconds. If the underlying system does not support
30 /// nanosecond-level precision, APIs binding a system timeout will typically round up
31 /// the number of nanoseconds.
33 /// [`Duration`]s implement many common traits, including [`Add`], [`Sub`], and other
34 /// [`ops`] traits. It implements [`Default`] by returning a zero-length `Duration`.
36 /// [`ops`]: crate::ops
41 /// use std::time::Duration;
43 /// let five_seconds = Duration::new(5, 0);
44 /// let five_seconds_and_five_nanos = five_seconds + Duration::new(0, 5);
46 /// assert_eq!(five_seconds_and_five_nanos.as_secs(), 5);
47 /// assert_eq!(five_seconds_and_five_nanos.subsec_nanos(), 5);
49 /// let ten_millis = Duration::from_millis(10);
52 /// # Formatting `Duration` values
54 /// `Duration` intentionally does not have a `Display` impl, as there are a
55 /// variety of ways to format spans of time for human readability. `Duration`
56 /// provides a `Debug` impl that shows the full precision of the value.
58 /// The `Debug` output uses the non-ASCII "µs" suffix for microseconds. If your
59 /// program output may appear in contexts that cannot rely on full Unicode
60 /// compatibility, you may wish to format `Duration` objects yourself or use a
62 #[stable(feature = "duration", since = "1.3.0")]
63 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
64 #[cfg_attr(not(test), rustc_diagnostic_item = "Duration")]
67 nanos: u32, // Always 0 <= nanos < NANOS_PER_SEC
71 /// The duration of one second.
76 /// #![feature(duration_constants)]
77 /// use std::time::Duration;
79 /// assert_eq!(Duration::SECOND, Duration::from_secs(1));
81 #[unstable(feature = "duration_constants", issue = "57391")]
82 pub const SECOND: Duration = Duration::from_secs(1);
84 /// The duration of one millisecond.
89 /// #![feature(duration_constants)]
90 /// use std::time::Duration;
92 /// assert_eq!(Duration::MILLISECOND, Duration::from_millis(1));
94 #[unstable(feature = "duration_constants", issue = "57391")]
95 pub const MILLISECOND: Duration = Duration::from_millis(1);
97 /// The duration of one microsecond.
102 /// #![feature(duration_constants)]
103 /// use std::time::Duration;
105 /// assert_eq!(Duration::MICROSECOND, Duration::from_micros(1));
107 #[unstable(feature = "duration_constants", issue = "57391")]
108 pub const MICROSECOND: Duration = Duration::from_micros(1);
110 /// The duration of one nanosecond.
115 /// #![feature(duration_constants)]
116 /// use std::time::Duration;
118 /// assert_eq!(Duration::NANOSECOND, Duration::from_nanos(1));
120 #[unstable(feature = "duration_constants", issue = "57391")]
121 pub const NANOSECOND: Duration = Duration::from_nanos(1);
123 /// A duration of zero time.
128 /// use std::time::Duration;
130 /// let duration = Duration::ZERO;
131 /// assert!(duration.is_zero());
132 /// assert_eq!(duration.as_nanos(), 0);
134 #[stable(feature = "duration_zero", since = "1.53.0")]
135 pub const ZERO: Duration = Duration::from_nanos(0);
137 /// The maximum duration.
139 /// May vary by platform as necessary. Must be able to contain the difference between
140 /// two instances of [`Instant`] or two instances of [`SystemTime`].
141 /// This constraint gives it a value of about 584,942,417,355 years in practice,
142 /// which is currently used on all platforms.
147 /// use std::time::Duration;
149 /// assert_eq!(Duration::MAX, Duration::new(u64::MAX, 1_000_000_000 - 1));
151 /// [`Instant`]: ../../std/time/struct.Instant.html
152 /// [`SystemTime`]: ../../std/time/struct.SystemTime.html
153 #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
154 pub const MAX: Duration = Duration::new(u64::MAX, NANOS_PER_SEC - 1);
156 /// Creates a new `Duration` from the specified number of whole seconds and
157 /// additional nanoseconds.
159 /// If the number of nanoseconds is greater than 1 billion (the number of
160 /// nanoseconds in a second), then it will carry over into the seconds provided.
164 /// This constructor will panic if the carry from the nanoseconds overflows
165 /// the seconds counter.
170 /// use std::time::Duration;
172 /// let five_seconds = Duration::new(5, 0);
174 #[stable(feature = "duration", since = "1.3.0")]
176 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
177 pub const fn new(secs: u64, nanos: u32) -> Duration {
178 let secs = match secs.checked_add((nanos / NANOS_PER_SEC) as u64) {
180 None => panic!("overflow in Duration::new"),
182 let nanos = nanos % NANOS_PER_SEC;
183 Duration { secs, nanos }
186 /// Creates a new `Duration` from the specified number of whole seconds.
191 /// use std::time::Duration;
193 /// let duration = Duration::from_secs(5);
195 /// assert_eq!(5, duration.as_secs());
196 /// assert_eq!(0, duration.subsec_nanos());
198 #[stable(feature = "duration", since = "1.3.0")]
200 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
201 pub const fn from_secs(secs: u64) -> Duration {
202 Duration { secs, nanos: 0 }
205 /// Creates a new `Duration` from the specified number of milliseconds.
210 /// use std::time::Duration;
212 /// let duration = Duration::from_millis(2569);
214 /// assert_eq!(2, duration.as_secs());
215 /// assert_eq!(569_000_000, duration.subsec_nanos());
217 #[stable(feature = "duration", since = "1.3.0")]
219 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
220 pub const fn from_millis(millis: u64) -> Duration {
222 secs: millis / MILLIS_PER_SEC,
223 nanos: ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI,
227 /// Creates a new `Duration` from the specified number of microseconds.
232 /// use std::time::Duration;
234 /// let duration = Duration::from_micros(1_000_002);
236 /// assert_eq!(1, duration.as_secs());
237 /// assert_eq!(2000, duration.subsec_nanos());
239 #[stable(feature = "duration_from_micros", since = "1.27.0")]
241 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
242 pub const fn from_micros(micros: u64) -> Duration {
244 secs: micros / MICROS_PER_SEC,
245 nanos: ((micros % MICROS_PER_SEC) as u32) * NANOS_PER_MICRO,
249 /// Creates a new `Duration` from the specified number of nanoseconds.
254 /// use std::time::Duration;
256 /// let duration = Duration::from_nanos(1_000_000_123);
258 /// assert_eq!(1, duration.as_secs());
259 /// assert_eq!(123, duration.subsec_nanos());
261 #[stable(feature = "duration_extras", since = "1.27.0")]
263 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
264 pub const fn from_nanos(nanos: u64) -> Duration {
266 secs: nanos / (NANOS_PER_SEC as u64),
267 nanos: (nanos % (NANOS_PER_SEC as u64)) as u32,
271 /// Returns true if this `Duration` spans no time.
276 /// use std::time::Duration;
278 /// assert!(Duration::ZERO.is_zero());
279 /// assert!(Duration::new(0, 0).is_zero());
280 /// assert!(Duration::from_nanos(0).is_zero());
281 /// assert!(Duration::from_secs(0).is_zero());
283 /// assert!(!Duration::new(1, 1).is_zero());
284 /// assert!(!Duration::from_nanos(1).is_zero());
285 /// assert!(!Duration::from_secs(1).is_zero());
287 #[stable(feature = "duration_zero", since = "1.53.0")]
288 #[rustc_const_stable(feature = "duration_zero", since = "1.53.0")]
290 pub const fn is_zero(&self) -> bool {
291 self.secs == 0 && self.nanos == 0
294 /// Returns the number of _whole_ seconds contained by this `Duration`.
296 /// The returned value does not include the fractional (nanosecond) part of the
297 /// duration, which can be obtained using [`subsec_nanos`].
302 /// use std::time::Duration;
304 /// let duration = Duration::new(5, 730023852);
305 /// assert_eq!(duration.as_secs(), 5);
308 /// To determine the total number of seconds represented by the `Duration`,
309 /// use `as_secs` in combination with [`subsec_nanos`]:
312 /// use std::time::Duration;
314 /// let duration = Duration::new(5, 730023852);
316 /// assert_eq!(5.730023852,
317 /// duration.as_secs() as f64
318 /// + duration.subsec_nanos() as f64 * 1e-9);
321 /// [`subsec_nanos`]: Duration::subsec_nanos
322 #[stable(feature = "duration", since = "1.3.0")]
323 #[rustc_const_stable(feature = "duration", since = "1.32.0")]
325 pub const fn as_secs(&self) -> u64 {
329 /// Returns the fractional part of this `Duration`, in whole milliseconds.
331 /// This method does **not** return the length of the duration when
332 /// represented by milliseconds. The returned number always represents a
333 /// fractional portion of a second (i.e., it is less than one thousand).
338 /// use std::time::Duration;
340 /// let duration = Duration::from_millis(5432);
341 /// assert_eq!(duration.as_secs(), 5);
342 /// assert_eq!(duration.subsec_millis(), 432);
344 #[stable(feature = "duration_extras", since = "1.27.0")]
345 #[rustc_const_stable(feature = "duration_extras", since = "1.32.0")]
347 pub const fn subsec_millis(&self) -> u32 {
348 self.nanos / NANOS_PER_MILLI
351 /// Returns the fractional part of this `Duration`, in whole microseconds.
353 /// This method does **not** return the length of the duration when
354 /// represented by microseconds. The returned number always represents a
355 /// fractional portion of a second (i.e., it is less than one million).
360 /// use std::time::Duration;
362 /// let duration = Duration::from_micros(1_234_567);
363 /// assert_eq!(duration.as_secs(), 1);
364 /// assert_eq!(duration.subsec_micros(), 234_567);
366 #[stable(feature = "duration_extras", since = "1.27.0")]
367 #[rustc_const_stable(feature = "duration_extras", since = "1.32.0")]
369 pub const fn subsec_micros(&self) -> u32 {
370 self.nanos / NANOS_PER_MICRO
373 /// Returns the fractional part of this `Duration`, in nanoseconds.
375 /// This method does **not** return the length of the duration when
376 /// represented by nanoseconds. The returned number always represents a
377 /// fractional portion of a second (i.e., it is less than one billion).
382 /// use std::time::Duration;
384 /// let duration = Duration::from_millis(5010);
385 /// assert_eq!(duration.as_secs(), 5);
386 /// assert_eq!(duration.subsec_nanos(), 10_000_000);
388 #[stable(feature = "duration", since = "1.3.0")]
389 #[rustc_const_stable(feature = "duration", since = "1.32.0")]
391 pub const fn subsec_nanos(&self) -> u32 {
395 /// Returns the total number of whole milliseconds contained by this `Duration`.
400 /// use std::time::Duration;
402 /// let duration = Duration::new(5, 730023852);
403 /// assert_eq!(duration.as_millis(), 5730);
405 #[stable(feature = "duration_as_u128", since = "1.33.0")]
406 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
408 pub const fn as_millis(&self) -> u128 {
409 self.secs as u128 * MILLIS_PER_SEC as u128 + (self.nanos / NANOS_PER_MILLI) as u128
412 /// Returns the total number of whole microseconds contained by this `Duration`.
417 /// use std::time::Duration;
419 /// let duration = Duration::new(5, 730023852);
420 /// assert_eq!(duration.as_micros(), 5730023);
422 #[stable(feature = "duration_as_u128", since = "1.33.0")]
423 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
425 pub const fn as_micros(&self) -> u128 {
426 self.secs as u128 * MICROS_PER_SEC as u128 + (self.nanos / NANOS_PER_MICRO) as u128
429 /// Returns the total number of nanoseconds contained by this `Duration`.
434 /// use std::time::Duration;
436 /// let duration = Duration::new(5, 730023852);
437 /// assert_eq!(duration.as_nanos(), 5730023852);
439 #[stable(feature = "duration_as_u128", since = "1.33.0")]
440 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
442 pub const fn as_nanos(&self) -> u128 {
443 self.secs as u128 * NANOS_PER_SEC as u128 + self.nanos as u128
446 /// Checked `Duration` addition. Computes `self + other`, returning [`None`]
447 /// if overflow occurred.
454 /// use std::time::Duration;
456 /// assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1)));
457 /// assert_eq!(Duration::new(1, 0).checked_add(Duration::new(u64::MAX, 0)), None);
459 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
461 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
462 pub const fn checked_add(self, rhs: Duration) -> Option<Duration> {
463 if let Some(mut secs) = self.secs.checked_add(rhs.secs) {
464 let mut nanos = self.nanos + rhs.nanos;
465 if nanos >= NANOS_PER_SEC {
466 nanos -= NANOS_PER_SEC;
467 if let Some(new_secs) = secs.checked_add(1) {
473 debug_assert!(nanos < NANOS_PER_SEC);
474 Some(Duration { secs, nanos })
480 /// Saturating `Duration` addition. Computes `self + other`, returning [`Duration::MAX`]
481 /// if overflow occurred.
486 /// #![feature(duration_constants)]
487 /// use std::time::Duration;
489 /// assert_eq!(Duration::new(0, 0).saturating_add(Duration::new(0, 1)), Duration::new(0, 1));
490 /// assert_eq!(Duration::new(1, 0).saturating_add(Duration::new(u64::MAX, 0)), Duration::MAX);
492 #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
494 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
495 pub const fn saturating_add(self, rhs: Duration) -> Duration {
496 match self.checked_add(rhs) {
498 None => Duration::MAX,
502 /// Checked `Duration` subtraction. Computes `self - other`, returning [`None`]
503 /// if the result would be negative or if overflow occurred.
510 /// use std::time::Duration;
512 /// assert_eq!(Duration::new(0, 1).checked_sub(Duration::new(0, 0)), Some(Duration::new(0, 1)));
513 /// assert_eq!(Duration::new(0, 0).checked_sub(Duration::new(0, 1)), None);
515 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
517 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
518 pub const fn checked_sub(self, rhs: Duration) -> Option<Duration> {
519 if let Some(mut secs) = self.secs.checked_sub(rhs.secs) {
520 let nanos = if self.nanos >= rhs.nanos {
521 self.nanos - rhs.nanos
522 } else if let Some(sub_secs) = secs.checked_sub(1) {
524 self.nanos + NANOS_PER_SEC - rhs.nanos
528 debug_assert!(nanos < NANOS_PER_SEC);
529 Some(Duration { secs, nanos })
535 /// Saturating `Duration` subtraction. Computes `self - other`, returning [`Duration::ZERO`]
536 /// if the result would be negative or if overflow occurred.
541 /// use std::time::Duration;
543 /// assert_eq!(Duration::new(0, 1).saturating_sub(Duration::new(0, 0)), Duration::new(0, 1));
544 /// assert_eq!(Duration::new(0, 0).saturating_sub(Duration::new(0, 1)), Duration::ZERO);
546 #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
548 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
549 pub const fn saturating_sub(self, rhs: Duration) -> Duration {
550 match self.checked_sub(rhs) {
552 None => Duration::ZERO,
556 /// Checked `Duration` multiplication. Computes `self * other`, returning
557 /// [`None`] if overflow occurred.
564 /// use std::time::Duration;
566 /// assert_eq!(Duration::new(0, 500_000_001).checked_mul(2), Some(Duration::new(1, 2)));
567 /// assert_eq!(Duration::new(u64::MAX - 1, 0).checked_mul(2), None);
569 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
571 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
572 pub const fn checked_mul(self, rhs: u32) -> Option<Duration> {
573 // Multiply nanoseconds as u64, because it cannot overflow that way.
574 let total_nanos = self.nanos as u64 * rhs as u64;
575 let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
576 let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
577 if let Some(s) = self.secs.checked_mul(rhs as u64) {
578 if let Some(secs) = s.checked_add(extra_secs) {
579 debug_assert!(nanos < NANOS_PER_SEC);
580 return Some(Duration { secs, nanos });
586 /// Saturating `Duration` multiplication. Computes `self * other`, returning
587 /// [`Duration::MAX`] if overflow occurred.
592 /// #![feature(duration_constants)]
593 /// use std::time::Duration;
595 /// assert_eq!(Duration::new(0, 500_000_001).saturating_mul(2), Duration::new(1, 2));
596 /// assert_eq!(Duration::new(u64::MAX - 1, 0).saturating_mul(2), Duration::MAX);
598 #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
600 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
601 pub const fn saturating_mul(self, rhs: u32) -> Duration {
602 match self.checked_mul(rhs) {
604 None => Duration::MAX,
608 /// Checked `Duration` division. Computes `self / other`, returning [`None`]
616 /// use std::time::Duration;
618 /// assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0)));
619 /// assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000)));
620 /// assert_eq!(Duration::new(2, 0).checked_div(0), None);
622 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
624 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
625 pub const fn checked_div(self, rhs: u32) -> Option<Duration> {
627 let secs = self.secs / (rhs as u64);
628 let carry = self.secs - secs * (rhs as u64);
629 let extra_nanos = carry * (NANOS_PER_SEC as u64) / (rhs as u64);
630 let nanos = self.nanos / rhs + (extra_nanos as u32);
631 debug_assert!(nanos < NANOS_PER_SEC);
632 Some(Duration { secs, nanos })
638 /// Returns the number of seconds contained by this `Duration` as `f64`.
640 /// The returned value does include the fractional (nanosecond) part of the duration.
644 /// use std::time::Duration;
646 /// let dur = Duration::new(2, 700_000_000);
647 /// assert_eq!(dur.as_secs_f64(), 2.7);
649 #[stable(feature = "duration_float", since = "1.38.0")]
651 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
652 pub const fn as_secs_f64(&self) -> f64 {
653 (self.secs as f64) + (self.nanos as f64) / (NANOS_PER_SEC as f64)
656 /// Returns the number of seconds contained by this `Duration` as `f32`.
658 /// The returned value does include the fractional (nanosecond) part of the duration.
662 /// use std::time::Duration;
664 /// let dur = Duration::new(2, 700_000_000);
665 /// assert_eq!(dur.as_secs_f32(), 2.7);
667 #[stable(feature = "duration_float", since = "1.38.0")]
669 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
670 pub const fn as_secs_f32(&self) -> f32 {
671 (self.secs as f32) + (self.nanos as f32) / (NANOS_PER_SEC as f32)
674 /// Creates a new `Duration` from the specified number of seconds represented
678 /// This constructor will panic if `secs` is not finite, negative or overflows `Duration`.
682 /// use std::time::Duration;
684 /// let dur = Duration::from_secs_f64(2.7);
685 /// assert_eq!(dur, Duration::new(2, 700_000_000));
687 #[stable(feature = "duration_float", since = "1.38.0")]
689 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
690 pub const fn from_secs_f64(secs: f64) -> Duration {
691 match Duration::try_from_secs_f64(secs) {
693 Err(e) => crate::panicking::panic(e.description()),
697 /// The checked version of [`from_secs_f64`].
699 /// [`from_secs_f64`]: Duration::from_secs_f64
701 /// This constructor will return an `Err` if `secs` is not finite, negative or overflows `Duration`.
705 /// #![feature(duration_checked_float)]
707 /// use std::time::Duration;
709 /// let dur = Duration::try_from_secs_f64(2.7);
710 /// assert_eq!(dur, Ok(Duration::new(2, 700_000_000)));
712 /// let negative = Duration::try_from_secs_f64(-5.0);
713 /// assert!(negative.is_err());
715 #[unstable(feature = "duration_checked_float", issue = "83400")]
717 pub const fn try_from_secs_f64(secs: f64) -> Result<Duration, FromSecsError> {
718 const MAX_NANOS_F64: f64 = ((u64::MAX as u128 + 1) * (NANOS_PER_SEC as u128)) as f64;
719 let nanos = secs * (NANOS_PER_SEC as f64);
720 if !nanos.is_finite() {
721 Err(FromSecsError { kind: FromSecsErrorKind::NonFinite })
722 } else if nanos >= MAX_NANOS_F64 {
723 Err(FromSecsError { kind: FromSecsErrorKind::Overflow })
724 } else if nanos < 0.0 {
725 Err(FromSecsError { kind: FromSecsErrorKind::Underflow })
727 let nanos = nanos as u128;
729 secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
730 nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
735 /// Creates a new `Duration` from the specified number of seconds represented
739 /// This constructor will panic if `secs` is not finite, negative or overflows `Duration`.
743 /// use std::time::Duration;
745 /// let dur = Duration::from_secs_f32(2.7);
746 /// assert_eq!(dur, Duration::new(2, 700_000_000));
748 #[stable(feature = "duration_float", since = "1.38.0")]
750 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
751 pub const fn from_secs_f32(secs: f32) -> Duration {
752 match Duration::try_from_secs_f32(secs) {
754 Err(e) => crate::panicking::panic(e.description()),
758 /// The checked version of [`from_secs_f32`].
760 /// [`from_secs_f32`]: Duration::from_secs_f32
762 /// This constructor will return an `Err` if `secs` is not finite, negative or overflows `Duration`.
766 /// #![feature(duration_checked_float)]
768 /// use std::time::Duration;
770 /// let dur = Duration::try_from_secs_f32(2.7);
771 /// assert_eq!(dur, Ok(Duration::new(2, 700_000_000)));
773 /// let negative = Duration::try_from_secs_f32(-5.0);
774 /// assert!(negative.is_err());
776 #[unstable(feature = "duration_checked_float", issue = "83400")]
778 pub const fn try_from_secs_f32(secs: f32) -> Result<Duration, FromSecsError> {
779 const MAX_NANOS_F32: f32 = ((u64::MAX as u128 + 1) * (NANOS_PER_SEC as u128)) as f32;
780 let nanos = secs * (NANOS_PER_SEC as f32);
781 if !nanos.is_finite() {
782 Err(FromSecsError { kind: FromSecsErrorKind::NonFinite })
783 } else if nanos >= MAX_NANOS_F32 {
784 Err(FromSecsError { kind: FromSecsErrorKind::Overflow })
785 } else if nanos < 0.0 {
786 Err(FromSecsError { kind: FromSecsErrorKind::Underflow })
788 let nanos = nanos as u128;
790 secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
791 nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
796 /// Multiplies `Duration` by `f64`.
799 /// This method will panic if result is not finite, negative or overflows `Duration`.
803 /// use std::time::Duration;
805 /// let dur = Duration::new(2, 700_000_000);
806 /// assert_eq!(dur.mul_f64(3.14), Duration::new(8, 478_000_000));
807 /// assert_eq!(dur.mul_f64(3.14e5), Duration::new(847_800, 0));
809 #[stable(feature = "duration_float", since = "1.38.0")]
811 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
812 pub const fn mul_f64(self, rhs: f64) -> Duration {
813 Duration::from_secs_f64(rhs * self.as_secs_f64())
816 /// Multiplies `Duration` by `f32`.
819 /// This method will panic if result is not finite, negative or overflows `Duration`.
823 /// use std::time::Duration;
825 /// let dur = Duration::new(2, 700_000_000);
826 /// // note that due to rounding errors result is slightly different
827 /// // from 8.478 and 847800.0
828 /// assert_eq!(dur.mul_f32(3.14), Duration::new(8, 478_000_640));
829 /// assert_eq!(dur.mul_f32(3.14e5), Duration::new(847799, 969_120_256));
831 #[stable(feature = "duration_float", since = "1.38.0")]
833 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
834 pub const fn mul_f32(self, rhs: f32) -> Duration {
835 Duration::from_secs_f32(rhs * self.as_secs_f32())
838 /// Divide `Duration` by `f64`.
841 /// This method will panic if result is not finite, negative or overflows `Duration`.
845 /// use std::time::Duration;
847 /// let dur = Duration::new(2, 700_000_000);
848 /// assert_eq!(dur.div_f64(3.14), Duration::new(0, 859_872_611));
849 /// // note that truncation is used, not rounding
850 /// assert_eq!(dur.div_f64(3.14e5), Duration::new(0, 8_598));
852 #[stable(feature = "duration_float", since = "1.38.0")]
854 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
855 pub const fn div_f64(self, rhs: f64) -> Duration {
856 Duration::from_secs_f64(self.as_secs_f64() / rhs)
859 /// Divide `Duration` by `f32`.
862 /// This method will panic if result is not finite, negative or overflows `Duration`.
866 /// use std::time::Duration;
868 /// let dur = Duration::new(2, 700_000_000);
869 /// // note that due to rounding errors result is slightly
870 /// // different from 0.859_872_611
871 /// assert_eq!(dur.div_f32(3.14), Duration::new(0, 859_872_576));
872 /// // note that truncation is used, not rounding
873 /// assert_eq!(dur.div_f32(3.14e5), Duration::new(0, 8_598));
875 #[stable(feature = "duration_float", since = "1.38.0")]
877 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
878 pub const fn div_f32(self, rhs: f32) -> Duration {
879 Duration::from_secs_f32(self.as_secs_f32() / rhs)
882 /// Divide `Duration` by `Duration` and return `f64`.
886 /// #![feature(div_duration)]
887 /// use std::time::Duration;
889 /// let dur1 = Duration::new(2, 700_000_000);
890 /// let dur2 = Duration::new(5, 400_000_000);
891 /// assert_eq!(dur1.div_duration_f64(dur2), 0.5);
893 #[unstable(feature = "div_duration", issue = "63139")]
895 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
896 pub const fn div_duration_f64(self, rhs: Duration) -> f64 {
897 self.as_secs_f64() / rhs.as_secs_f64()
900 /// Divide `Duration` by `Duration` and return `f32`.
904 /// #![feature(div_duration)]
905 /// use std::time::Duration;
907 /// let dur1 = Duration::new(2, 700_000_000);
908 /// let dur2 = Duration::new(5, 400_000_000);
909 /// assert_eq!(dur1.div_duration_f32(dur2), 0.5);
911 #[unstable(feature = "div_duration", issue = "63139")]
913 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
914 pub const fn div_duration_f32(self, rhs: Duration) -> f32 {
915 self.as_secs_f32() / rhs.as_secs_f32()
919 #[stable(feature = "duration", since = "1.3.0")]
920 impl Add for Duration {
921 type Output = Duration;
923 fn add(self, rhs: Duration) -> Duration {
924 self.checked_add(rhs).expect("overflow when adding durations")
928 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
929 impl AddAssign for Duration {
930 fn add_assign(&mut self, rhs: Duration) {
935 #[stable(feature = "duration", since = "1.3.0")]
936 impl Sub for Duration {
937 type Output = Duration;
939 fn sub(self, rhs: Duration) -> Duration {
940 self.checked_sub(rhs).expect("overflow when subtracting durations")
944 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
945 impl SubAssign for Duration {
946 fn sub_assign(&mut self, rhs: Duration) {
951 #[stable(feature = "duration", since = "1.3.0")]
952 impl Mul<u32> for Duration {
953 type Output = Duration;
955 fn mul(self, rhs: u32) -> Duration {
956 self.checked_mul(rhs).expect("overflow when multiplying duration by scalar")
960 #[stable(feature = "symmetric_u32_duration_mul", since = "1.31.0")]
961 impl Mul<Duration> for u32 {
962 type Output = Duration;
964 fn mul(self, rhs: Duration) -> Duration {
969 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
970 impl MulAssign<u32> for Duration {
971 fn mul_assign(&mut self, rhs: u32) {
976 #[stable(feature = "duration", since = "1.3.0")]
977 impl Div<u32> for Duration {
978 type Output = Duration;
980 fn div(self, rhs: u32) -> Duration {
981 self.checked_div(rhs).expect("divide by zero error when dividing duration by scalar")
985 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
986 impl DivAssign<u32> for Duration {
987 fn div_assign(&mut self, rhs: u32) {
992 macro_rules! sum_durations {
994 let mut total_secs: u64 = 0;
995 let mut total_nanos: u64 = 0;
999 total_secs.checked_add(entry.secs).expect("overflow in iter::sum over durations");
1000 total_nanos = match total_nanos.checked_add(entry.nanos as u64) {
1003 total_secs = total_secs
1004 .checked_add(total_nanos / NANOS_PER_SEC as u64)
1005 .expect("overflow in iter::sum over durations");
1006 (total_nanos % NANOS_PER_SEC as u64) + entry.nanos as u64
1010 total_secs = total_secs
1011 .checked_add(total_nanos / NANOS_PER_SEC as u64)
1012 .expect("overflow in iter::sum over durations");
1013 total_nanos = total_nanos % NANOS_PER_SEC as u64;
1014 Duration { secs: total_secs, nanos: total_nanos as u32 }
1018 #[stable(feature = "duration_sum", since = "1.16.0")]
1019 impl Sum for Duration {
1020 fn sum<I: Iterator<Item = Duration>>(iter: I) -> Duration {
1021 sum_durations!(iter)
1025 #[stable(feature = "duration_sum", since = "1.16.0")]
1026 impl<'a> Sum<&'a Duration> for Duration {
1027 fn sum<I: Iterator<Item = &'a Duration>>(iter: I) -> Duration {
1028 sum_durations!(iter)
1032 #[stable(feature = "duration_debug_impl", since = "1.27.0")]
1033 impl fmt::Debug for Duration {
1034 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1035 /// Formats a floating point number in decimal notation.
1037 /// The number is given as the `integer_part` and a fractional part.
1038 /// The value of the fractional part is `fractional_part / divisor`. So
1039 /// `integer_part` = 3, `fractional_part` = 12 and `divisor` = 100
1040 /// represents the number `3.012`. Trailing zeros are omitted.
1042 /// `divisor` must not be above 100_000_000. It also should be a power
1043 /// of 10, everything else doesn't make sense. `fractional_part` has
1044 /// to be less than `10 * divisor`!
1046 f: &mut fmt::Formatter<'_>,
1047 mut integer_part: u64,
1048 mut fractional_part: u32,
1051 // Encode the fractional part into a temporary buffer. The buffer
1052 // only need to hold 9 elements, because `fractional_part` has to
1053 // be smaller than 10^9. The buffer is prefilled with '0' digits
1054 // to simplify the code below.
1055 let mut buf = [b'0'; 9];
1057 // The next digit is written at this position
1060 // We keep writing digits into the buffer while there are non-zero
1061 // digits left and we haven't written enough digits yet.
1062 while fractional_part > 0 && pos < f.precision().unwrap_or(9) {
1063 // Write new digit into the buffer
1064 buf[pos] = b'0' + (fractional_part / divisor) as u8;
1066 fractional_part %= divisor;
1071 // If a precision < 9 was specified, there may be some non-zero
1072 // digits left that weren't written into the buffer. In that case we
1073 // need to perform rounding to match the semantics of printing
1074 // normal floating point numbers. However, we only need to do work
1075 // when rounding up. This happens if the first digit of the
1076 // remaining ones is >= 5.
1077 if fractional_part > 0 && fractional_part >= divisor * 5 {
1078 // Round up the number contained in the buffer. We go through
1079 // the buffer backwards and keep track of the carry.
1080 let mut rev_pos = pos;
1081 let mut carry = true;
1082 while carry && rev_pos > 0 {
1085 // If the digit in the buffer is not '9', we just need to
1086 // increment it and can stop then (since we don't have a
1087 // carry anymore). Otherwise, we set it to '0' (overflow)
1089 if buf[rev_pos] < b'9' {
1093 buf[rev_pos] = b'0';
1097 // If we still have the carry bit set, that means that we set
1098 // the whole buffer to '0's and need to increment the integer
1105 // Determine the end of the buffer: if precision is set, we just
1106 // use as many digits from the buffer (capped to 9). If it isn't
1107 // set, we only use all digits up to the last non-zero one.
1108 let end = f.precision().map(|p| crate::cmp::min(p, 9)).unwrap_or(pos);
1110 // If we haven't emitted a single fractional digit and the precision
1111 // wasn't set to a non-zero value, we don't print the decimal point.
1113 write!(f, "{}", integer_part)
1115 // SAFETY: We are only writing ASCII digits into the buffer and it was
1116 // initialized with '0's, so it contains valid UTF8.
1117 let s = unsafe { crate::str::from_utf8_unchecked(&buf[..end]) };
1119 // If the user request a precision > 9, we pad '0's at the end.
1120 let w = f.precision().unwrap_or(pos);
1121 write!(f, "{}.{:0<width$}", integer_part, s, width = w)
1125 // Print leading '+' sign if requested
1131 fmt_decimal(f, self.secs, self.nanos, NANOS_PER_SEC / 10)?;
1133 } else if self.nanos >= NANOS_PER_MILLI {
1136 (self.nanos / NANOS_PER_MILLI) as u64,
1137 self.nanos % NANOS_PER_MILLI,
1138 NANOS_PER_MILLI / 10,
1141 } else if self.nanos >= NANOS_PER_MICRO {
1144 (self.nanos / NANOS_PER_MICRO) as u64,
1145 self.nanos % NANOS_PER_MICRO,
1146 NANOS_PER_MICRO / 10,
1150 fmt_decimal(f, self.nanos as u64, 0, 1)?;
1156 /// An error which can be returned when converting a floating-point value of seconds
1157 /// into a [`Duration`].
1159 /// This error is used as the error type for [`Duration::try_from_secs_f32`] and
1160 /// [`Duration::try_from_secs_f64`].
1165 /// #![feature(duration_checked_float)]
1167 /// use std::time::Duration;
1169 /// if let Err(e) = Duration::try_from_secs_f32(-1.0) {
1170 /// println!("Failed conversion to Duration: {}", e);
1173 #[derive(Debug, Clone, PartialEq, Eq)]
1174 #[unstable(feature = "duration_checked_float", issue = "83400")]
1175 pub struct FromSecsError {
1176 kind: FromSecsErrorKind,
1179 impl FromSecsError {
1180 const fn description(&self) -> &'static str {
1182 FromSecsErrorKind::NonFinite => {
1183 "got non-finite value when converting float to duration"
1185 FromSecsErrorKind::Overflow => "overflow when converting float to duration",
1186 FromSecsErrorKind::Underflow => "underflow when converting float to duration",
1191 #[unstable(feature = "duration_checked_float", issue = "83400")]
1192 impl fmt::Display for FromSecsError {
1193 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1194 fmt::Display::fmt(self.description(), f)
1198 #[derive(Debug, Clone, PartialEq, Eq)]
1199 enum FromSecsErrorKind {
1200 // Value is not a finite value (either infinity or NaN).
1202 // Value is too large to store in a `Duration`.
1204 // Value is less than `0.0`.