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 /// [`Add`]: ../../std/ops/trait.Add.html
37 /// [`Sub`]: ../../std/ops/trait.Sub.html
38 /// [`ops`]: ../../std/ops/index.html
43 /// use std::time::Duration;
45 /// let five_seconds = Duration::new(5, 0);
46 /// let five_seconds_and_five_nanos = five_seconds + Duration::new(0, 5);
48 /// assert_eq!(five_seconds_and_five_nanos.as_secs(), 5);
49 /// assert_eq!(five_seconds_and_five_nanos.subsec_nanos(), 5);
51 /// let ten_millis = Duration::from_millis(10);
53 #[stable(feature = "duration", since = "1.3.0")]
54 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
57 nanos: u32, // Always 0 <= nanos < NANOS_PER_SEC
61 /// The duration of one second.
66 /// #![feature(duration_constants)]
67 /// use std::time::Duration;
69 /// assert_eq!(Duration::SECOND, Duration::from_secs(1));
71 #[unstable(feature = "duration_constants", issue = "57391")]
72 pub const SECOND: Duration = Duration::from_secs(1);
74 /// The duration of one millisecond.
79 /// #![feature(duration_constants)]
80 /// use std::time::Duration;
82 /// assert_eq!(Duration::MILLISECOND, Duration::from_millis(1));
84 #[unstable(feature = "duration_constants", issue = "57391")]
85 pub const MILLISECOND: Duration = Duration::from_millis(1);
87 /// The duration of one microsecond.
92 /// #![feature(duration_constants)]
93 /// use std::time::Duration;
95 /// assert_eq!(Duration::MICROSECOND, Duration::from_micros(1));
97 #[unstable(feature = "duration_constants", issue = "57391")]
98 pub const MICROSECOND: Duration = Duration::from_micros(1);
100 /// The duration of one nanosecond.
105 /// #![feature(duration_constants)]
106 /// use std::time::Duration;
108 /// assert_eq!(Duration::NANOSECOND, Duration::from_nanos(1));
110 #[unstable(feature = "duration_constants", issue = "57391")]
111 pub const NANOSECOND: Duration = Duration::from_nanos(1);
113 /// Creates a new `Duration` from the specified number of whole seconds and
114 /// additional nanoseconds.
116 /// If the number of nanoseconds is greater than 1 billion (the number of
117 /// nanoseconds in a second), then it will carry over into the seconds provided.
121 /// This constructor will panic if the carry from the nanoseconds overflows
122 /// the seconds counter.
127 /// use std::time::Duration;
129 /// let five_seconds = Duration::new(5, 0);
131 #[stable(feature = "duration", since = "1.3.0")]
133 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
134 pub fn new(secs: u64, nanos: u32) -> Duration {
136 secs.checked_add((nanos / NANOS_PER_SEC) as u64).expect("overflow in Duration::new");
137 let nanos = nanos % NANOS_PER_SEC;
138 Duration { secs, nanos }
141 /// Creates a new `Duration` that spans no time.
146 /// #![feature(duration_zero)]
147 /// use std::time::Duration;
149 /// let duration = Duration::zero();
150 /// assert!(duration.is_zero());
151 /// assert_eq!(duration.as_nanos(), 0);
153 #[unstable(feature = "duration_zero", issue = "73544")]
155 pub const fn zero() -> Duration {
156 Duration { secs: 0, nanos: 0 }
159 /// Creates a new `Duration` from the specified number of whole seconds.
164 /// use std::time::Duration;
166 /// let duration = Duration::from_secs(5);
168 /// assert_eq!(5, duration.as_secs());
169 /// assert_eq!(0, duration.subsec_nanos());
171 #[stable(feature = "duration", since = "1.3.0")]
173 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
174 pub const fn from_secs(secs: u64) -> Duration {
175 Duration { secs, nanos: 0 }
178 /// Creates a new `Duration` from the specified number of milliseconds.
183 /// use std::time::Duration;
185 /// let duration = Duration::from_millis(2569);
187 /// assert_eq!(2, duration.as_secs());
188 /// assert_eq!(569_000_000, duration.subsec_nanos());
190 #[stable(feature = "duration", since = "1.3.0")]
192 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
193 pub const fn from_millis(millis: u64) -> Duration {
195 secs: millis / MILLIS_PER_SEC,
196 nanos: ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI,
200 /// Creates a new `Duration` from the specified number of microseconds.
205 /// use std::time::Duration;
207 /// let duration = Duration::from_micros(1_000_002);
209 /// assert_eq!(1, duration.as_secs());
210 /// assert_eq!(2000, duration.subsec_nanos());
212 #[stable(feature = "duration_from_micros", since = "1.27.0")]
214 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
215 pub const fn from_micros(micros: u64) -> Duration {
217 secs: micros / MICROS_PER_SEC,
218 nanos: ((micros % MICROS_PER_SEC) as u32) * NANOS_PER_MICRO,
222 /// Creates a new `Duration` from the specified number of nanoseconds.
227 /// use std::time::Duration;
229 /// let duration = Duration::from_nanos(1_000_000_123);
231 /// assert_eq!(1, duration.as_secs());
232 /// assert_eq!(123, duration.subsec_nanos());
234 #[stable(feature = "duration_extras", since = "1.27.0")]
236 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
237 pub const fn from_nanos(nanos: u64) -> Duration {
239 secs: nanos / (NANOS_PER_SEC as u64),
240 nanos: (nanos % (NANOS_PER_SEC as u64)) as u32,
244 /// Returns true if this `Duration` spans no time.
249 /// #![feature(duration_zero)]
250 /// use std::time::Duration;
252 /// assert!(Duration::zero().is_zero());
253 /// assert!(Duration::new(0, 0).is_zero());
254 /// assert!(Duration::from_nanos(0).is_zero());
255 /// assert!(Duration::from_secs(0).is_zero());
257 /// assert!(!Duration::new(1, 1).is_zero());
258 /// assert!(!Duration::from_nanos(1).is_zero());
259 /// assert!(!Duration::from_secs(1).is_zero());
261 #[unstable(feature = "duration_zero", issue = "73544")]
263 pub const fn is_zero(&self) -> bool {
264 self.secs == 0 && self.nanos == 0
267 /// Returns the number of _whole_ seconds contained by this `Duration`.
269 /// The returned value does not include the fractional (nanosecond) part of the
270 /// duration, which can be obtained using [`subsec_nanos`].
275 /// use std::time::Duration;
277 /// let duration = Duration::new(5, 730023852);
278 /// assert_eq!(duration.as_secs(), 5);
281 /// To determine the total number of seconds represented by the `Duration`,
282 /// use `as_secs` in combination with [`subsec_nanos`]:
285 /// use std::time::Duration;
287 /// let duration = Duration::new(5, 730023852);
289 /// assert_eq!(5.730023852,
290 /// duration.as_secs() as f64
291 /// + duration.subsec_nanos() as f64 * 1e-9);
294 /// [`subsec_nanos`]: #method.subsec_nanos
295 #[stable(feature = "duration", since = "1.3.0")]
296 #[rustc_const_stable(feature = "duration", since = "1.32.0")]
298 pub const fn as_secs(&self) -> u64 {
302 /// Returns the fractional part of this `Duration`, in whole milliseconds.
304 /// This method does **not** return the length of the duration when
305 /// represented by milliseconds. The returned number always represents a
306 /// fractional portion of a second (i.e., it is less than one thousand).
311 /// use std::time::Duration;
313 /// let duration = Duration::from_millis(5432);
314 /// assert_eq!(duration.as_secs(), 5);
315 /// assert_eq!(duration.subsec_millis(), 432);
317 #[stable(feature = "duration_extras", since = "1.27.0")]
318 #[rustc_const_stable(feature = "duration_extras", since = "1.32.0")]
320 pub const fn subsec_millis(&self) -> u32 {
321 self.nanos / NANOS_PER_MILLI
324 /// Returns the fractional part of this `Duration`, in whole microseconds.
326 /// This method does **not** return the length of the duration when
327 /// represented by microseconds. The returned number always represents a
328 /// fractional portion of a second (i.e., it is less than one million).
333 /// use std::time::Duration;
335 /// let duration = Duration::from_micros(1_234_567);
336 /// assert_eq!(duration.as_secs(), 1);
337 /// assert_eq!(duration.subsec_micros(), 234_567);
339 #[stable(feature = "duration_extras", since = "1.27.0")]
340 #[rustc_const_stable(feature = "duration_extras", since = "1.32.0")]
342 pub const fn subsec_micros(&self) -> u32 {
343 self.nanos / NANOS_PER_MICRO
346 /// Returns the fractional part of this `Duration`, in nanoseconds.
348 /// This method does **not** return the length of the duration when
349 /// represented by nanoseconds. The returned number always represents a
350 /// fractional portion of a second (i.e., it is less than one billion).
355 /// use std::time::Duration;
357 /// let duration = Duration::from_millis(5010);
358 /// assert_eq!(duration.as_secs(), 5);
359 /// assert_eq!(duration.subsec_nanos(), 10_000_000);
361 #[stable(feature = "duration", since = "1.3.0")]
362 #[rustc_const_stable(feature = "duration", since = "1.32.0")]
364 pub const fn subsec_nanos(&self) -> u32 {
368 /// Returns the total number of whole milliseconds contained by this `Duration`.
373 /// use std::time::Duration;
375 /// let duration = Duration::new(5, 730023852);
376 /// assert_eq!(duration.as_millis(), 5730);
378 #[stable(feature = "duration_as_u128", since = "1.33.0")]
379 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
381 pub const fn as_millis(&self) -> u128 {
382 self.secs as u128 * MILLIS_PER_SEC as u128 + (self.nanos / NANOS_PER_MILLI) as u128
385 /// Returns the total number of whole microseconds contained by this `Duration`.
390 /// use std::time::Duration;
392 /// let duration = Duration::new(5, 730023852);
393 /// assert_eq!(duration.as_micros(), 5730023);
395 #[stable(feature = "duration_as_u128", since = "1.33.0")]
396 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
398 pub const fn as_micros(&self) -> u128 {
399 self.secs as u128 * MICROS_PER_SEC as u128 + (self.nanos / NANOS_PER_MICRO) as u128
402 /// Returns the total number of nanoseconds contained by this `Duration`.
407 /// use std::time::Duration;
409 /// let duration = Duration::new(5, 730023852);
410 /// assert_eq!(duration.as_nanos(), 5730023852);
412 #[stable(feature = "duration_as_u128", since = "1.33.0")]
413 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
415 pub const fn as_nanos(&self) -> u128 {
416 self.secs as u128 * NANOS_PER_SEC as u128 + self.nanos as u128
419 /// Checked `Duration` addition. Computes `self + other`, returning [`None`]
420 /// if overflow occurred.
422 /// [`None`]: ../../std/option/enum.Option.html#variant.None
429 /// use std::time::Duration;
431 /// assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1)));
432 /// assert_eq!(Duration::new(1, 0).checked_add(Duration::new(u64::MAX, 0)), None);
434 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
436 pub fn checked_add(self, rhs: Duration) -> Option<Duration> {
437 if let Some(mut secs) = self.secs.checked_add(rhs.secs) {
438 let mut nanos = self.nanos + rhs.nanos;
439 if nanos >= NANOS_PER_SEC {
440 nanos -= NANOS_PER_SEC;
441 if let Some(new_secs) = secs.checked_add(1) {
447 debug_assert!(nanos < NANOS_PER_SEC);
448 Some(Duration { secs, nanos })
454 /// Checked `Duration` subtraction. Computes `self - other`, returning [`None`]
455 /// if the result would be negative or if overflow occurred.
457 /// [`None`]: ../../std/option/enum.Option.html#variant.None
464 /// use std::time::Duration;
466 /// assert_eq!(Duration::new(0, 1).checked_sub(Duration::new(0, 0)), Some(Duration::new(0, 1)));
467 /// assert_eq!(Duration::new(0, 0).checked_sub(Duration::new(0, 1)), None);
469 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
471 pub fn checked_sub(self, rhs: Duration) -> Option<Duration> {
472 if let Some(mut secs) = self.secs.checked_sub(rhs.secs) {
473 let nanos = if self.nanos >= rhs.nanos {
474 self.nanos - rhs.nanos
476 if let Some(sub_secs) = secs.checked_sub(1) {
478 self.nanos + NANOS_PER_SEC - rhs.nanos
483 debug_assert!(nanos < NANOS_PER_SEC);
484 Some(Duration { secs, nanos })
490 /// Checked `Duration` multiplication. Computes `self * other`, returning
491 /// [`None`] if overflow occurred.
493 /// [`None`]: ../../std/option/enum.Option.html#variant.None
500 /// use std::time::Duration;
502 /// assert_eq!(Duration::new(0, 500_000_001).checked_mul(2), Some(Duration::new(1, 2)));
503 /// assert_eq!(Duration::new(u64::MAX - 1, 0).checked_mul(2), None);
505 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
507 pub fn checked_mul(self, rhs: u32) -> Option<Duration> {
508 // Multiply nanoseconds as u64, because it cannot overflow that way.
509 let total_nanos = self.nanos as u64 * rhs as u64;
510 let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
511 let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
513 self.secs.checked_mul(rhs as u64).and_then(|s| s.checked_add(extra_secs))
515 debug_assert!(nanos < NANOS_PER_SEC);
516 Some(Duration { secs, nanos })
522 /// Checked `Duration` division. Computes `self / other`, returning [`None`]
525 /// [`None`]: ../../std/option/enum.Option.html#variant.None
532 /// use std::time::Duration;
534 /// assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0)));
535 /// assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000)));
536 /// assert_eq!(Duration::new(2, 0).checked_div(0), None);
538 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
540 pub fn checked_div(self, rhs: u32) -> Option<Duration> {
542 let secs = self.secs / (rhs as u64);
543 let carry = self.secs - secs * (rhs as u64);
544 let extra_nanos = carry * (NANOS_PER_SEC as u64) / (rhs as u64);
545 let nanos = self.nanos / rhs + (extra_nanos as u32);
546 debug_assert!(nanos < NANOS_PER_SEC);
547 Some(Duration { secs, nanos })
553 /// Returns the number of seconds contained by this `Duration` as `f64`.
555 /// The returned value does include the fractional (nanosecond) part of the duration.
559 /// use std::time::Duration;
561 /// let dur = Duration::new(2, 700_000_000);
562 /// assert_eq!(dur.as_secs_f64(), 2.7);
564 #[stable(feature = "duration_float", since = "1.38.0")]
566 pub fn as_secs_f64(&self) -> f64 {
567 (self.secs as f64) + (self.nanos as f64) / (NANOS_PER_SEC as f64)
570 /// Returns the number of seconds contained by this `Duration` as `f32`.
572 /// The returned value does include the fractional (nanosecond) part of the duration.
576 /// use std::time::Duration;
578 /// let dur = Duration::new(2, 700_000_000);
579 /// assert_eq!(dur.as_secs_f32(), 2.7);
581 #[stable(feature = "duration_float", since = "1.38.0")]
583 pub fn as_secs_f32(&self) -> f32 {
584 (self.secs as f32) + (self.nanos as f32) / (NANOS_PER_SEC as f32)
587 /// Creates a new `Duration` from the specified number of seconds represented
591 /// This constructor will panic if `secs` is not finite, negative or overflows `Duration`.
595 /// use std::time::Duration;
597 /// let dur = Duration::from_secs_f64(2.7);
598 /// assert_eq!(dur, Duration::new(2, 700_000_000));
600 #[stable(feature = "duration_float", since = "1.38.0")]
602 pub fn from_secs_f64(secs: f64) -> Duration {
603 const MAX_NANOS_F64: f64 = ((u64::MAX as u128 + 1) * (NANOS_PER_SEC as u128)) as f64;
604 let nanos = secs * (NANOS_PER_SEC as f64);
605 if !nanos.is_finite() {
606 panic!("got non-finite value when converting float to duration");
608 if nanos >= MAX_NANOS_F64 {
609 panic!("overflow when converting float to duration");
612 panic!("underflow when converting float to duration");
614 let nanos = nanos as u128;
616 secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
617 nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
621 /// Creates a new `Duration` from the specified number of seconds represented
625 /// This constructor will panic if `secs` is not finite, negative or overflows `Duration`.
629 /// use std::time::Duration;
631 /// let dur = Duration::from_secs_f32(2.7);
632 /// assert_eq!(dur, Duration::new(2, 700_000_000));
634 #[stable(feature = "duration_float", since = "1.38.0")]
636 pub fn from_secs_f32(secs: f32) -> Duration {
637 const MAX_NANOS_F32: f32 = ((u64::MAX as u128 + 1) * (NANOS_PER_SEC as u128)) as f32;
638 let nanos = secs * (NANOS_PER_SEC as f32);
639 if !nanos.is_finite() {
640 panic!("got non-finite value when converting float to duration");
642 if nanos >= MAX_NANOS_F32 {
643 panic!("overflow when converting float to duration");
646 panic!("underflow when converting float to duration");
648 let nanos = nanos as u128;
650 secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
651 nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
655 /// Multiplies `Duration` by `f64`.
658 /// This method will panic if result is not finite, negative or overflows `Duration`.
662 /// use std::time::Duration;
664 /// let dur = Duration::new(2, 700_000_000);
665 /// assert_eq!(dur.mul_f64(3.14), Duration::new(8, 478_000_000));
666 /// assert_eq!(dur.mul_f64(3.14e5), Duration::new(847_800, 0));
668 #[stable(feature = "duration_float", since = "1.38.0")]
670 pub fn mul_f64(self, rhs: f64) -> Duration {
671 Duration::from_secs_f64(rhs * self.as_secs_f64())
674 /// Multiplies `Duration` by `f32`.
677 /// This method will panic if result is not finite, negative or overflows `Duration`.
681 /// use std::time::Duration;
683 /// let dur = Duration::new(2, 700_000_000);
684 /// // note that due to rounding errors result is slightly different
685 /// // from 8.478 and 847800.0
686 /// assert_eq!(dur.mul_f32(3.14), Duration::new(8, 478_000_640));
687 /// assert_eq!(dur.mul_f32(3.14e5), Duration::new(847799, 969_120_256));
689 #[stable(feature = "duration_float", since = "1.38.0")]
691 pub fn mul_f32(self, rhs: f32) -> Duration {
692 Duration::from_secs_f32(rhs * self.as_secs_f32())
695 /// Divide `Duration` by `f64`.
698 /// This method will panic if result is not finite, negative or overflows `Duration`.
702 /// use std::time::Duration;
704 /// let dur = Duration::new(2, 700_000_000);
705 /// assert_eq!(dur.div_f64(3.14), Duration::new(0, 859_872_611));
706 /// // note that truncation is used, not rounding
707 /// assert_eq!(dur.div_f64(3.14e5), Duration::new(0, 8_598));
709 #[stable(feature = "duration_float", since = "1.38.0")]
711 pub fn div_f64(self, rhs: f64) -> Duration {
712 Duration::from_secs_f64(self.as_secs_f64() / rhs)
715 /// Divide `Duration` by `f32`.
718 /// This method will panic if result is not finite, negative or overflows `Duration`.
722 /// use std::time::Duration;
724 /// let dur = Duration::new(2, 700_000_000);
725 /// // note that due to rounding errors result is slightly
726 /// // different from 0.859_872_611
727 /// assert_eq!(dur.div_f32(3.14), Duration::new(0, 859_872_576));
728 /// // note that truncation is used, not rounding
729 /// assert_eq!(dur.div_f32(3.14e5), Duration::new(0, 8_598));
731 #[stable(feature = "duration_float", since = "1.38.0")]
733 pub fn div_f32(self, rhs: f32) -> Duration {
734 Duration::from_secs_f32(self.as_secs_f32() / rhs)
737 /// Divide `Duration` by `Duration` and return `f64`.
741 /// #![feature(div_duration)]
742 /// use std::time::Duration;
744 /// let dur1 = Duration::new(2, 700_000_000);
745 /// let dur2 = Duration::new(5, 400_000_000);
746 /// assert_eq!(dur1.div_duration_f64(dur2), 0.5);
748 #[unstable(feature = "div_duration", issue = "63139")]
750 pub fn div_duration_f64(self, rhs: Duration) -> f64 {
751 self.as_secs_f64() / rhs.as_secs_f64()
754 /// Divide `Duration` by `Duration` and return `f32`.
758 /// #![feature(div_duration)]
759 /// use std::time::Duration;
761 /// let dur1 = Duration::new(2, 700_000_000);
762 /// let dur2 = Duration::new(5, 400_000_000);
763 /// assert_eq!(dur1.div_duration_f32(dur2), 0.5);
765 #[unstable(feature = "div_duration", issue = "63139")]
767 pub fn div_duration_f32(self, rhs: Duration) -> f32 {
768 self.as_secs_f32() / rhs.as_secs_f32()
772 #[stable(feature = "duration", since = "1.3.0")]
773 impl Add for Duration {
774 type Output = Duration;
776 fn add(self, rhs: Duration) -> Duration {
777 self.checked_add(rhs).expect("overflow when adding durations")
781 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
782 impl AddAssign for Duration {
783 fn add_assign(&mut self, rhs: Duration) {
788 #[stable(feature = "duration", since = "1.3.0")]
789 impl Sub for Duration {
790 type Output = Duration;
792 fn sub(self, rhs: Duration) -> Duration {
793 self.checked_sub(rhs).expect("overflow when subtracting durations")
797 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
798 impl SubAssign for Duration {
799 fn sub_assign(&mut self, rhs: Duration) {
804 #[stable(feature = "duration", since = "1.3.0")]
805 impl Mul<u32> for Duration {
806 type Output = Duration;
808 fn mul(self, rhs: u32) -> Duration {
809 self.checked_mul(rhs).expect("overflow when multiplying duration by scalar")
813 #[stable(feature = "symmetric_u32_duration_mul", since = "1.31.0")]
814 impl Mul<Duration> for u32 {
815 type Output = Duration;
817 fn mul(self, rhs: Duration) -> Duration {
822 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
823 impl MulAssign<u32> for Duration {
824 fn mul_assign(&mut self, rhs: u32) {
829 #[stable(feature = "duration", since = "1.3.0")]
830 impl Div<u32> for Duration {
831 type Output = Duration;
833 fn div(self, rhs: u32) -> Duration {
834 self.checked_div(rhs).expect("divide by zero error when dividing duration by scalar")
838 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
839 impl DivAssign<u32> for Duration {
840 fn div_assign(&mut self, rhs: u32) {
845 macro_rules! sum_durations {
847 let mut total_secs: u64 = 0;
848 let mut total_nanos: u64 = 0;
852 total_secs.checked_add(entry.secs).expect("overflow in iter::sum over durations");
853 total_nanos = match total_nanos.checked_add(entry.nanos as u64) {
856 total_secs = total_secs
857 .checked_add(total_nanos / NANOS_PER_SEC as u64)
858 .expect("overflow in iter::sum over durations");
859 (total_nanos % NANOS_PER_SEC as u64) + entry.nanos as u64
863 total_secs = total_secs
864 .checked_add(total_nanos / NANOS_PER_SEC as u64)
865 .expect("overflow in iter::sum over durations");
866 total_nanos = total_nanos % NANOS_PER_SEC as u64;
867 Duration { secs: total_secs, nanos: total_nanos as u32 }
871 #[stable(feature = "duration_sum", since = "1.16.0")]
872 impl Sum for Duration {
873 fn sum<I: Iterator<Item = Duration>>(iter: I) -> Duration {
878 #[stable(feature = "duration_sum", since = "1.16.0")]
879 impl<'a> Sum<&'a Duration> for Duration {
880 fn sum<I: Iterator<Item = &'a Duration>>(iter: I) -> Duration {
885 #[stable(feature = "duration_debug_impl", since = "1.27.0")]
886 impl fmt::Debug for Duration {
887 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
888 /// Formats a floating point number in decimal notation.
890 /// The number is given as the `integer_part` and a fractional part.
891 /// The value of the fractional part is `fractional_part / divisor`. So
892 /// `integer_part` = 3, `fractional_part` = 12 and `divisor` = 100
893 /// represents the number `3.012`. Trailing zeros are omitted.
895 /// `divisor` must not be above 100_000_000. It also should be a power
896 /// of 10, everything else doesn't make sense. `fractional_part` has
897 /// to be less than `10 * divisor`!
899 f: &mut fmt::Formatter<'_>,
900 mut integer_part: u64,
901 mut fractional_part: u32,
904 // Encode the fractional part into a temporary buffer. The buffer
905 // only need to hold 9 elements, because `fractional_part` has to
906 // be smaller than 10^9. The buffer is prefilled with '0' digits
907 // to simplify the code below.
908 let mut buf = [b'0'; 9];
910 // The next digit is written at this position
913 // We keep writing digits into the buffer while there are non-zero
914 // digits left and we haven't written enough digits yet.
915 while fractional_part > 0 && pos < f.precision().unwrap_or(9) {
916 // Write new digit into the buffer
917 buf[pos] = b'0' + (fractional_part / divisor) as u8;
919 fractional_part %= divisor;
924 // If a precision < 9 was specified, there may be some non-zero
925 // digits left that weren't written into the buffer. In that case we
926 // need to perform rounding to match the semantics of printing
927 // normal floating point numbers. However, we only need to do work
928 // when rounding up. This happens if the first digit of the
929 // remaining ones is >= 5.
930 if fractional_part > 0 && fractional_part >= divisor * 5 {
931 // Round up the number contained in the buffer. We go through
932 // the buffer backwards and keep track of the carry.
933 let mut rev_pos = pos;
934 let mut carry = true;
935 while carry && rev_pos > 0 {
938 // If the digit in the buffer is not '9', we just need to
939 // increment it and can stop then (since we don't have a
940 // carry anymore). Otherwise, we set it to '0' (overflow)
942 if buf[rev_pos] < b'9' {
950 // If we still have the carry bit set, that means that we set
951 // the whole buffer to '0's and need to increment the integer
958 // Determine the end of the buffer: if precision is set, we just
959 // use as many digits from the buffer (capped to 9). If it isn't
960 // set, we only use all digits up to the last non-zero one.
961 let end = f.precision().map(|p| crate::cmp::min(p, 9)).unwrap_or(pos);
963 // If we haven't emitted a single fractional digit and the precision
964 // wasn't set to a non-zero value, we don't print the decimal point.
966 write!(f, "{}", integer_part)
968 // SAFETY: We are only writing ASCII digits into the buffer and it was
969 // initialized with '0's, so it contains valid UTF8.
970 let s = unsafe { crate::str::from_utf8_unchecked(&buf[..end]) };
972 // If the user request a precision > 9, we pad '0's at the end.
973 let w = f.precision().unwrap_or(pos);
974 write!(f, "{}.{:0<width$}", integer_part, s, width = w)
978 // Print leading '+' sign if requested
984 fmt_decimal(f, self.secs, self.nanos, 100_000_000)?;
986 } else if self.nanos >= 1_000_000 {
987 fmt_decimal(f, self.nanos as u64 / 1_000_000, self.nanos % 1_000_000, 100_000)?;
989 } else if self.nanos >= 1_000 {
990 fmt_decimal(f, self.nanos as u64 / 1_000, self.nanos % 1_000, 100)?;
993 fmt_decimal(f, self.nanos as u64, 0, 1)?;