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)]
66 nanos: u32, // Always 0 <= nanos < NANOS_PER_SEC
70 /// The duration of one second.
75 /// #![feature(duration_constants)]
76 /// use std::time::Duration;
78 /// assert_eq!(Duration::SECOND, Duration::from_secs(1));
80 #[unstable(feature = "duration_constants", issue = "57391")]
81 pub const SECOND: Duration = Duration::from_secs(1);
83 /// The duration of one millisecond.
88 /// #![feature(duration_constants)]
89 /// use std::time::Duration;
91 /// assert_eq!(Duration::MILLISECOND, Duration::from_millis(1));
93 #[unstable(feature = "duration_constants", issue = "57391")]
94 pub const MILLISECOND: Duration = Duration::from_millis(1);
96 /// The duration of one microsecond.
101 /// #![feature(duration_constants)]
102 /// use std::time::Duration;
104 /// assert_eq!(Duration::MICROSECOND, Duration::from_micros(1));
106 #[unstable(feature = "duration_constants", issue = "57391")]
107 pub const MICROSECOND: Duration = Duration::from_micros(1);
109 /// The duration of one nanosecond.
114 /// #![feature(duration_constants)]
115 /// use std::time::Duration;
117 /// assert_eq!(Duration::NANOSECOND, Duration::from_nanos(1));
119 #[unstable(feature = "duration_constants", issue = "57391")]
120 pub const NANOSECOND: Duration = Duration::from_nanos(1);
122 /// A duration of zero time.
127 /// use std::time::Duration;
129 /// let duration = Duration::ZERO;
130 /// assert!(duration.is_zero());
131 /// assert_eq!(duration.as_nanos(), 0);
133 #[stable(feature = "duration_zero", since = "1.53.0")]
134 pub const ZERO: Duration = Duration::from_nanos(0);
136 /// The maximum duration.
138 /// May vary by platform as necessary. Must be able to contain the difference between
139 /// two instances of [`Instant`] or two instances of [`SystemTime`].
140 /// This constraint gives it a value of about 584,942,417,355 years in practice,
141 /// which is currently used on all platforms.
146 /// use std::time::Duration;
148 /// assert_eq!(Duration::MAX, Duration::new(u64::MAX, 1_000_000_000 - 1));
150 /// [`Instant`]: ../../std/time/struct.Instant.html
151 /// [`SystemTime`]: ../../std/time/struct.SystemTime.html
152 #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
153 pub const MAX: Duration = Duration::new(u64::MAX, NANOS_PER_SEC - 1);
155 /// Creates a new `Duration` from the specified number of whole seconds and
156 /// additional nanoseconds.
158 /// If the number of nanoseconds is greater than 1 billion (the number of
159 /// nanoseconds in a second), then it will carry over into the seconds provided.
163 /// This constructor will panic if the carry from the nanoseconds overflows
164 /// the seconds counter.
169 /// use std::time::Duration;
171 /// let five_seconds = Duration::new(5, 0);
173 #[stable(feature = "duration", since = "1.3.0")]
175 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
176 pub const fn new(secs: u64, nanos: u32) -> Duration {
177 let secs = match secs.checked_add((nanos / NANOS_PER_SEC) as u64) {
179 None => panic!("overflow in Duration::new"),
181 let nanos = nanos % NANOS_PER_SEC;
182 Duration { secs, nanos }
185 /// Creates a new `Duration` from the specified number of whole seconds.
190 /// use std::time::Duration;
192 /// let duration = Duration::from_secs(5);
194 /// assert_eq!(5, duration.as_secs());
195 /// assert_eq!(0, duration.subsec_nanos());
197 #[stable(feature = "duration", since = "1.3.0")]
199 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
200 pub const fn from_secs(secs: u64) -> Duration {
201 Duration { secs, nanos: 0 }
204 /// Creates a new `Duration` from the specified number of milliseconds.
209 /// use std::time::Duration;
211 /// let duration = Duration::from_millis(2569);
213 /// assert_eq!(2, duration.as_secs());
214 /// assert_eq!(569_000_000, duration.subsec_nanos());
216 #[stable(feature = "duration", since = "1.3.0")]
218 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
219 pub const fn from_millis(millis: u64) -> Duration {
221 secs: millis / MILLIS_PER_SEC,
222 nanos: ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI,
226 /// Creates a new `Duration` from the specified number of microseconds.
231 /// use std::time::Duration;
233 /// let duration = Duration::from_micros(1_000_002);
235 /// assert_eq!(1, duration.as_secs());
236 /// assert_eq!(2000, duration.subsec_nanos());
238 #[stable(feature = "duration_from_micros", since = "1.27.0")]
240 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
241 pub const fn from_micros(micros: u64) -> Duration {
243 secs: micros / MICROS_PER_SEC,
244 nanos: ((micros % MICROS_PER_SEC) as u32) * NANOS_PER_MICRO,
248 /// Creates a new `Duration` from the specified number of nanoseconds.
253 /// use std::time::Duration;
255 /// let duration = Duration::from_nanos(1_000_000_123);
257 /// assert_eq!(1, duration.as_secs());
258 /// assert_eq!(123, duration.subsec_nanos());
260 #[stable(feature = "duration_extras", since = "1.27.0")]
262 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
263 pub const fn from_nanos(nanos: u64) -> Duration {
265 secs: nanos / (NANOS_PER_SEC as u64),
266 nanos: (nanos % (NANOS_PER_SEC as u64)) as u32,
270 /// Returns true if this `Duration` spans no time.
275 /// use std::time::Duration;
277 /// assert!(Duration::ZERO.is_zero());
278 /// assert!(Duration::new(0, 0).is_zero());
279 /// assert!(Duration::from_nanos(0).is_zero());
280 /// assert!(Duration::from_secs(0).is_zero());
282 /// assert!(!Duration::new(1, 1).is_zero());
283 /// assert!(!Duration::from_nanos(1).is_zero());
284 /// assert!(!Duration::from_secs(1).is_zero());
286 #[stable(feature = "duration_zero", since = "1.53.0")]
287 #[rustc_const_stable(feature = "duration_zero", since = "1.53.0")]
289 pub const fn is_zero(&self) -> bool {
290 self.secs == 0 && self.nanos == 0
293 /// Returns the number of _whole_ seconds contained by this `Duration`.
295 /// The returned value does not include the fractional (nanosecond) part of the
296 /// duration, which can be obtained using [`subsec_nanos`].
301 /// use std::time::Duration;
303 /// let duration = Duration::new(5, 730023852);
304 /// assert_eq!(duration.as_secs(), 5);
307 /// To determine the total number of seconds represented by the `Duration`,
308 /// use `as_secs` in combination with [`subsec_nanos`]:
311 /// use std::time::Duration;
313 /// let duration = Duration::new(5, 730023852);
315 /// assert_eq!(5.730023852,
316 /// duration.as_secs() as f64
317 /// + duration.subsec_nanos() as f64 * 1e-9);
320 /// [`subsec_nanos`]: Duration::subsec_nanos
321 #[stable(feature = "duration", since = "1.3.0")]
322 #[rustc_const_stable(feature = "duration", since = "1.32.0")]
324 pub const fn as_secs(&self) -> u64 {
328 /// Returns the fractional part of this `Duration`, in whole milliseconds.
330 /// This method does **not** return the length of the duration when
331 /// represented by milliseconds. The returned number always represents a
332 /// fractional portion of a second (i.e., it is less than one thousand).
337 /// use std::time::Duration;
339 /// let duration = Duration::from_millis(5432);
340 /// assert_eq!(duration.as_secs(), 5);
341 /// assert_eq!(duration.subsec_millis(), 432);
343 #[stable(feature = "duration_extras", since = "1.27.0")]
344 #[rustc_const_stable(feature = "duration_extras", since = "1.32.0")]
346 pub const fn subsec_millis(&self) -> u32 {
347 self.nanos / NANOS_PER_MILLI
350 /// Returns the fractional part of this `Duration`, in whole microseconds.
352 /// This method does **not** return the length of the duration when
353 /// represented by microseconds. The returned number always represents a
354 /// fractional portion of a second (i.e., it is less than one million).
359 /// use std::time::Duration;
361 /// let duration = Duration::from_micros(1_234_567);
362 /// assert_eq!(duration.as_secs(), 1);
363 /// assert_eq!(duration.subsec_micros(), 234_567);
365 #[stable(feature = "duration_extras", since = "1.27.0")]
366 #[rustc_const_stable(feature = "duration_extras", since = "1.32.0")]
368 pub const fn subsec_micros(&self) -> u32 {
369 self.nanos / NANOS_PER_MICRO
372 /// Returns the fractional part of this `Duration`, in nanoseconds.
374 /// This method does **not** return the length of the duration when
375 /// represented by nanoseconds. The returned number always represents a
376 /// fractional portion of a second (i.e., it is less than one billion).
381 /// use std::time::Duration;
383 /// let duration = Duration::from_millis(5010);
384 /// assert_eq!(duration.as_secs(), 5);
385 /// assert_eq!(duration.subsec_nanos(), 10_000_000);
387 #[stable(feature = "duration", since = "1.3.0")]
388 #[rustc_const_stable(feature = "duration", since = "1.32.0")]
390 pub const fn subsec_nanos(&self) -> u32 {
394 /// Returns the total number of whole milliseconds contained by this `Duration`.
399 /// use std::time::Duration;
401 /// let duration = Duration::new(5, 730023852);
402 /// assert_eq!(duration.as_millis(), 5730);
404 #[stable(feature = "duration_as_u128", since = "1.33.0")]
405 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
407 pub const fn as_millis(&self) -> u128 {
408 self.secs as u128 * MILLIS_PER_SEC as u128 + (self.nanos / NANOS_PER_MILLI) as u128
411 /// Returns the total number of whole microseconds contained by this `Duration`.
416 /// use std::time::Duration;
418 /// let duration = Duration::new(5, 730023852);
419 /// assert_eq!(duration.as_micros(), 5730023);
421 #[stable(feature = "duration_as_u128", since = "1.33.0")]
422 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
424 pub const fn as_micros(&self) -> u128 {
425 self.secs as u128 * MICROS_PER_SEC as u128 + (self.nanos / NANOS_PER_MICRO) as u128
428 /// Returns the total number of nanoseconds contained by this `Duration`.
433 /// use std::time::Duration;
435 /// let duration = Duration::new(5, 730023852);
436 /// assert_eq!(duration.as_nanos(), 5730023852);
438 #[stable(feature = "duration_as_u128", since = "1.33.0")]
439 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
441 pub const fn as_nanos(&self) -> u128 {
442 self.secs as u128 * NANOS_PER_SEC as u128 + self.nanos as u128
445 /// Checked `Duration` addition. Computes `self + other`, returning [`None`]
446 /// if overflow occurred.
453 /// use std::time::Duration;
455 /// assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1)));
456 /// assert_eq!(Duration::new(1, 0).checked_add(Duration::new(u64::MAX, 0)), None);
458 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
460 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
461 pub const fn checked_add(self, rhs: Duration) -> Option<Duration> {
462 if let Some(mut secs) = self.secs.checked_add(rhs.secs) {
463 let mut nanos = self.nanos + rhs.nanos;
464 if nanos >= NANOS_PER_SEC {
465 nanos -= NANOS_PER_SEC;
466 if let Some(new_secs) = secs.checked_add(1) {
472 debug_assert!(nanos < NANOS_PER_SEC);
473 Some(Duration { secs, nanos })
479 /// Saturating `Duration` addition. Computes `self + other`, returning [`Duration::MAX`]
480 /// if overflow occurred.
485 /// #![feature(duration_constants)]
486 /// use std::time::Duration;
488 /// assert_eq!(Duration::new(0, 0).saturating_add(Duration::new(0, 1)), Duration::new(0, 1));
489 /// assert_eq!(Duration::new(1, 0).saturating_add(Duration::new(u64::MAX, 0)), Duration::MAX);
491 #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
493 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
494 pub const fn saturating_add(self, rhs: Duration) -> Duration {
495 match self.checked_add(rhs) {
497 None => Duration::MAX,
501 /// Checked `Duration` subtraction. Computes `self - other`, returning [`None`]
502 /// if the result would be negative or if overflow occurred.
509 /// use std::time::Duration;
511 /// assert_eq!(Duration::new(0, 1).checked_sub(Duration::new(0, 0)), Some(Duration::new(0, 1)));
512 /// assert_eq!(Duration::new(0, 0).checked_sub(Duration::new(0, 1)), None);
514 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
516 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
517 pub const fn checked_sub(self, rhs: Duration) -> Option<Duration> {
518 if let Some(mut secs) = self.secs.checked_sub(rhs.secs) {
519 let nanos = if self.nanos >= rhs.nanos {
520 self.nanos - rhs.nanos
522 if let Some(sub_secs) = secs.checked_sub(1) {
524 self.nanos + NANOS_PER_SEC - rhs.nanos
529 debug_assert!(nanos < NANOS_PER_SEC);
530 Some(Duration { secs, nanos })
536 /// Saturating `Duration` subtraction. Computes `self - other`, returning [`Duration::ZERO`]
537 /// if the result would be negative or if overflow occurred.
542 /// use std::time::Duration;
544 /// assert_eq!(Duration::new(0, 1).saturating_sub(Duration::new(0, 0)), Duration::new(0, 1));
545 /// assert_eq!(Duration::new(0, 0).saturating_sub(Duration::new(0, 1)), Duration::ZERO);
547 #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
549 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
550 pub const fn saturating_sub(self, rhs: Duration) -> Duration {
551 match self.checked_sub(rhs) {
553 None => Duration::ZERO,
557 /// Checked `Duration` multiplication. Computes `self * other`, returning
558 /// [`None`] if overflow occurred.
565 /// use std::time::Duration;
567 /// assert_eq!(Duration::new(0, 500_000_001).checked_mul(2), Some(Duration::new(1, 2)));
568 /// assert_eq!(Duration::new(u64::MAX - 1, 0).checked_mul(2), None);
570 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
572 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
573 pub const fn checked_mul(self, rhs: u32) -> Option<Duration> {
574 // Multiply nanoseconds as u64, because it cannot overflow that way.
575 let total_nanos = self.nanos as u64 * rhs as u64;
576 let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
577 let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
578 if let Some(s) = self.secs.checked_mul(rhs as u64) {
579 if let Some(secs) = s.checked_add(extra_secs) {
580 debug_assert!(nanos < NANOS_PER_SEC);
581 return Some(Duration { secs, nanos });
587 /// Saturating `Duration` multiplication. Computes `self * other`, returning
588 /// [`Duration::MAX`] if overflow occurred.
593 /// #![feature(duration_constants)]
594 /// use std::time::Duration;
596 /// assert_eq!(Duration::new(0, 500_000_001).saturating_mul(2), Duration::new(1, 2));
597 /// assert_eq!(Duration::new(u64::MAX - 1, 0).saturating_mul(2), Duration::MAX);
599 #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
601 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
602 pub const fn saturating_mul(self, rhs: u32) -> Duration {
603 match self.checked_mul(rhs) {
605 None => Duration::MAX,
609 /// Checked `Duration` division. Computes `self / other`, returning [`None`]
617 /// use std::time::Duration;
619 /// assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0)));
620 /// assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000)));
621 /// assert_eq!(Duration::new(2, 0).checked_div(0), None);
623 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
625 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
626 pub const fn checked_div(self, rhs: u32) -> Option<Duration> {
628 let secs = self.secs / (rhs as u64);
629 let carry = self.secs - secs * (rhs as u64);
630 let extra_nanos = carry * (NANOS_PER_SEC as u64) / (rhs as u64);
631 let nanos = self.nanos / rhs + (extra_nanos as u32);
632 debug_assert!(nanos < NANOS_PER_SEC);
633 Some(Duration { secs, nanos })
639 /// Returns the number of seconds contained by this `Duration` as `f64`.
641 /// The returned value does include the fractional (nanosecond) part of the duration.
645 /// use std::time::Duration;
647 /// let dur = Duration::new(2, 700_000_000);
648 /// assert_eq!(dur.as_secs_f64(), 2.7);
650 #[stable(feature = "duration_float", since = "1.38.0")]
652 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
653 pub const fn as_secs_f64(&self) -> f64 {
654 (self.secs as f64) + (self.nanos as f64) / (NANOS_PER_SEC as f64)
657 /// Returns the number of seconds contained by this `Duration` as `f32`.
659 /// The returned value does include the fractional (nanosecond) part of the duration.
663 /// use std::time::Duration;
665 /// let dur = Duration::new(2, 700_000_000);
666 /// assert_eq!(dur.as_secs_f32(), 2.7);
668 #[stable(feature = "duration_float", since = "1.38.0")]
670 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
671 pub const fn as_secs_f32(&self) -> f32 {
672 (self.secs as f32) + (self.nanos as f32) / (NANOS_PER_SEC as f32)
675 /// Creates a new `Duration` from the specified number of seconds represented
679 /// This constructor will panic if `secs` is not finite, negative or overflows `Duration`.
683 /// use std::time::Duration;
685 /// let dur = Duration::from_secs_f64(2.7);
686 /// assert_eq!(dur, Duration::new(2, 700_000_000));
688 #[stable(feature = "duration_float", since = "1.38.0")]
690 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
691 pub const fn from_secs_f64(secs: f64) -> Duration {
692 const MAX_NANOS_F64: f64 = ((u64::MAX as u128 + 1) * (NANOS_PER_SEC as u128)) as f64;
693 let nanos = secs * (NANOS_PER_SEC as f64);
694 if !nanos.is_finite() {
695 panic!("got non-finite value when converting float to duration");
697 if nanos >= MAX_NANOS_F64 {
698 panic!("overflow when converting float to duration");
701 panic!("underflow when converting float to duration");
703 let nanos = nanos as u128;
705 secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
706 nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
710 /// Creates a new `Duration` from the specified number of seconds represented
714 /// This constructor will panic if `secs` is not finite, negative or overflows `Duration`.
718 /// use std::time::Duration;
720 /// let dur = Duration::from_secs_f32(2.7);
721 /// assert_eq!(dur, Duration::new(2, 700_000_000));
723 #[stable(feature = "duration_float", since = "1.38.0")]
725 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
726 pub const fn from_secs_f32(secs: f32) -> Duration {
727 const MAX_NANOS_F32: f32 = ((u64::MAX as u128 + 1) * (NANOS_PER_SEC as u128)) as f32;
728 let nanos = secs * (NANOS_PER_SEC as f32);
729 if !nanos.is_finite() {
730 panic!("got non-finite value when converting float to duration");
732 if nanos >= MAX_NANOS_F32 {
733 panic!("overflow when converting float to duration");
736 panic!("underflow when converting float to duration");
738 let nanos = nanos as u128;
740 secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
741 nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
745 /// Multiplies `Duration` by `f64`.
748 /// This method will panic if result is not finite, negative or overflows `Duration`.
752 /// use std::time::Duration;
754 /// let dur = Duration::new(2, 700_000_000);
755 /// assert_eq!(dur.mul_f64(3.14), Duration::new(8, 478_000_000));
756 /// assert_eq!(dur.mul_f64(3.14e5), Duration::new(847_800, 0));
758 #[stable(feature = "duration_float", since = "1.38.0")]
760 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
761 pub const fn mul_f64(self, rhs: f64) -> Duration {
762 Duration::from_secs_f64(rhs * self.as_secs_f64())
765 /// Multiplies `Duration` by `f32`.
768 /// This method will panic if result is not finite, negative or overflows `Duration`.
772 /// use std::time::Duration;
774 /// let dur = Duration::new(2, 700_000_000);
775 /// // note that due to rounding errors result is slightly different
776 /// // from 8.478 and 847800.0
777 /// assert_eq!(dur.mul_f32(3.14), Duration::new(8, 478_000_640));
778 /// assert_eq!(dur.mul_f32(3.14e5), Duration::new(847799, 969_120_256));
780 #[stable(feature = "duration_float", since = "1.38.0")]
782 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
783 pub const fn mul_f32(self, rhs: f32) -> Duration {
784 Duration::from_secs_f32(rhs * self.as_secs_f32())
787 /// Divide `Duration` by `f64`.
790 /// This method will panic if result is not finite, negative or overflows `Duration`.
794 /// use std::time::Duration;
796 /// let dur = Duration::new(2, 700_000_000);
797 /// assert_eq!(dur.div_f64(3.14), Duration::new(0, 859_872_611));
798 /// // note that truncation is used, not rounding
799 /// assert_eq!(dur.div_f64(3.14e5), Duration::new(0, 8_598));
801 #[stable(feature = "duration_float", since = "1.38.0")]
803 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
804 pub const fn div_f64(self, rhs: f64) -> Duration {
805 Duration::from_secs_f64(self.as_secs_f64() / rhs)
808 /// Divide `Duration` by `f32`.
811 /// This method will panic if result is not finite, negative or overflows `Duration`.
815 /// use std::time::Duration;
817 /// let dur = Duration::new(2, 700_000_000);
818 /// // note that due to rounding errors result is slightly
819 /// // different from 0.859_872_611
820 /// assert_eq!(dur.div_f32(3.14), Duration::new(0, 859_872_576));
821 /// // note that truncation is used, not rounding
822 /// assert_eq!(dur.div_f32(3.14e5), Duration::new(0, 8_598));
824 #[stable(feature = "duration_float", since = "1.38.0")]
826 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
827 pub const fn div_f32(self, rhs: f32) -> Duration {
828 Duration::from_secs_f32(self.as_secs_f32() / rhs)
831 /// Divide `Duration` by `Duration` and return `f64`.
835 /// #![feature(div_duration)]
836 /// use std::time::Duration;
838 /// let dur1 = Duration::new(2, 700_000_000);
839 /// let dur2 = Duration::new(5, 400_000_000);
840 /// assert_eq!(dur1.div_duration_f64(dur2), 0.5);
842 #[unstable(feature = "div_duration", issue = "63139")]
844 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
845 pub const fn div_duration_f64(self, rhs: Duration) -> f64 {
846 self.as_secs_f64() / rhs.as_secs_f64()
849 /// Divide `Duration` by `Duration` and return `f32`.
853 /// #![feature(div_duration)]
854 /// use std::time::Duration;
856 /// let dur1 = Duration::new(2, 700_000_000);
857 /// let dur2 = Duration::new(5, 400_000_000);
858 /// assert_eq!(dur1.div_duration_f32(dur2), 0.5);
860 #[unstable(feature = "div_duration", issue = "63139")]
862 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
863 pub const fn div_duration_f32(self, rhs: Duration) -> f32 {
864 self.as_secs_f32() / rhs.as_secs_f32()
868 #[stable(feature = "duration", since = "1.3.0")]
869 impl Add for Duration {
870 type Output = Duration;
872 fn add(self, rhs: Duration) -> Duration {
873 self.checked_add(rhs).expect("overflow when adding durations")
877 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
878 impl AddAssign for Duration {
879 fn add_assign(&mut self, rhs: Duration) {
884 #[stable(feature = "duration", since = "1.3.0")]
885 impl Sub for Duration {
886 type Output = Duration;
888 fn sub(self, rhs: Duration) -> Duration {
889 self.checked_sub(rhs).expect("overflow when subtracting durations")
893 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
894 impl SubAssign for Duration {
895 fn sub_assign(&mut self, rhs: Duration) {
900 #[stable(feature = "duration", since = "1.3.0")]
901 impl Mul<u32> for Duration {
902 type Output = Duration;
904 fn mul(self, rhs: u32) -> Duration {
905 self.checked_mul(rhs).expect("overflow when multiplying duration by scalar")
909 #[stable(feature = "symmetric_u32_duration_mul", since = "1.31.0")]
910 impl Mul<Duration> for u32 {
911 type Output = Duration;
913 fn mul(self, rhs: Duration) -> Duration {
918 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
919 impl MulAssign<u32> for Duration {
920 fn mul_assign(&mut self, rhs: u32) {
925 #[stable(feature = "duration", since = "1.3.0")]
926 impl Div<u32> for Duration {
927 type Output = Duration;
929 fn div(self, rhs: u32) -> Duration {
930 self.checked_div(rhs).expect("divide by zero error when dividing duration by scalar")
934 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
935 impl DivAssign<u32> for Duration {
936 fn div_assign(&mut self, rhs: u32) {
941 macro_rules! sum_durations {
943 let mut total_secs: u64 = 0;
944 let mut total_nanos: u64 = 0;
948 total_secs.checked_add(entry.secs).expect("overflow in iter::sum over durations");
949 total_nanos = match total_nanos.checked_add(entry.nanos as u64) {
952 total_secs = total_secs
953 .checked_add(total_nanos / NANOS_PER_SEC as u64)
954 .expect("overflow in iter::sum over durations");
955 (total_nanos % NANOS_PER_SEC as u64) + entry.nanos as u64
959 total_secs = total_secs
960 .checked_add(total_nanos / NANOS_PER_SEC as u64)
961 .expect("overflow in iter::sum over durations");
962 total_nanos = total_nanos % NANOS_PER_SEC as u64;
963 Duration { secs: total_secs, nanos: total_nanos as u32 }
967 #[stable(feature = "duration_sum", since = "1.16.0")]
968 impl Sum for Duration {
969 fn sum<I: Iterator<Item = Duration>>(iter: I) -> Duration {
974 #[stable(feature = "duration_sum", since = "1.16.0")]
975 impl<'a> Sum<&'a Duration> for Duration {
976 fn sum<I: Iterator<Item = &'a Duration>>(iter: I) -> Duration {
981 #[stable(feature = "duration_debug_impl", since = "1.27.0")]
982 impl fmt::Debug for Duration {
983 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
984 /// Formats a floating point number in decimal notation.
986 /// The number is given as the `integer_part` and a fractional part.
987 /// The value of the fractional part is `fractional_part / divisor`. So
988 /// `integer_part` = 3, `fractional_part` = 12 and `divisor` = 100
989 /// represents the number `3.012`. Trailing zeros are omitted.
991 /// `divisor` must not be above 100_000_000. It also should be a power
992 /// of 10, everything else doesn't make sense. `fractional_part` has
993 /// to be less than `10 * divisor`!
995 f: &mut fmt::Formatter<'_>,
996 mut integer_part: u64,
997 mut fractional_part: u32,
1000 // Encode the fractional part into a temporary buffer. The buffer
1001 // only need to hold 9 elements, because `fractional_part` has to
1002 // be smaller than 10^9. The buffer is prefilled with '0' digits
1003 // to simplify the code below.
1004 let mut buf = [b'0'; 9];
1006 // The next digit is written at this position
1009 // We keep writing digits into the buffer while there are non-zero
1010 // digits left and we haven't written enough digits yet.
1011 while fractional_part > 0 && pos < f.precision().unwrap_or(9) {
1012 // Write new digit into the buffer
1013 buf[pos] = b'0' + (fractional_part / divisor) as u8;
1015 fractional_part %= divisor;
1020 // If a precision < 9 was specified, there may be some non-zero
1021 // digits left that weren't written into the buffer. In that case we
1022 // need to perform rounding to match the semantics of printing
1023 // normal floating point numbers. However, we only need to do work
1024 // when rounding up. This happens if the first digit of the
1025 // remaining ones is >= 5.
1026 if fractional_part > 0 && fractional_part >= divisor * 5 {
1027 // Round up the number contained in the buffer. We go through
1028 // the buffer backwards and keep track of the carry.
1029 let mut rev_pos = pos;
1030 let mut carry = true;
1031 while carry && rev_pos > 0 {
1034 // If the digit in the buffer is not '9', we just need to
1035 // increment it and can stop then (since we don't have a
1036 // carry anymore). Otherwise, we set it to '0' (overflow)
1038 if buf[rev_pos] < b'9' {
1042 buf[rev_pos] = b'0';
1046 // If we still have the carry bit set, that means that we set
1047 // the whole buffer to '0's and need to increment the integer
1054 // Determine the end of the buffer: if precision is set, we just
1055 // use as many digits from the buffer (capped to 9). If it isn't
1056 // set, we only use all digits up to the last non-zero one.
1057 let end = f.precision().map(|p| crate::cmp::min(p, 9)).unwrap_or(pos);
1059 // If we haven't emitted a single fractional digit and the precision
1060 // wasn't set to a non-zero value, we don't print the decimal point.
1062 write!(f, "{}", integer_part)
1064 // SAFETY: We are only writing ASCII digits into the buffer and it was
1065 // initialized with '0's, so it contains valid UTF8.
1066 let s = unsafe { crate::str::from_utf8_unchecked(&buf[..end]) };
1068 // If the user request a precision > 9, we pad '0's at the end.
1069 let w = f.precision().unwrap_or(pos);
1070 write!(f, "{}.{:0<width$}", integer_part, s, width = w)
1074 // Print leading '+' sign if requested
1080 fmt_decimal(f, self.secs, self.nanos, NANOS_PER_SEC / 10)?;
1082 } else if self.nanos >= NANOS_PER_MILLI {
1085 (self.nanos / NANOS_PER_MILLI) as u64,
1086 self.nanos % NANOS_PER_MILLI,
1087 NANOS_PER_MILLI / 10,
1090 } else if self.nanos >= NANOS_PER_MICRO {
1093 (self.nanos / NANOS_PER_MICRO) as u64,
1094 self.nanos % NANOS_PER_MICRO,
1095 NANOS_PER_MICRO / 10,
1099 fmt_decimal(f, self.nanos as u64, 0, 1)?;