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` from the specified number of whole seconds.
146 /// use std::time::Duration;
148 /// let duration = Duration::from_secs(5);
150 /// assert_eq!(5, duration.as_secs());
151 /// assert_eq!(0, duration.subsec_nanos());
153 #[stable(feature = "duration", since = "1.3.0")]
155 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
156 pub const fn from_secs(secs: u64) -> Duration {
157 Duration { secs, nanos: 0 }
160 /// Creates a new `Duration` from the specified number of milliseconds.
165 /// use std::time::Duration;
167 /// let duration = Duration::from_millis(2569);
169 /// assert_eq!(2, duration.as_secs());
170 /// assert_eq!(569_000_000, duration.subsec_nanos());
172 #[stable(feature = "duration", since = "1.3.0")]
174 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
175 pub const fn from_millis(millis: u64) -> Duration {
177 secs: millis / MILLIS_PER_SEC,
178 nanos: ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI,
182 /// Creates a new `Duration` from the specified number of microseconds.
187 /// use std::time::Duration;
189 /// let duration = Duration::from_micros(1_000_002);
191 /// assert_eq!(1, duration.as_secs());
192 /// assert_eq!(2000, duration.subsec_nanos());
194 #[stable(feature = "duration_from_micros", since = "1.27.0")]
196 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
197 pub const fn from_micros(micros: u64) -> Duration {
199 secs: micros / MICROS_PER_SEC,
200 nanos: ((micros % MICROS_PER_SEC) as u32) * NANOS_PER_MICRO,
204 /// Creates a new `Duration` from the specified number of nanoseconds.
209 /// use std::time::Duration;
211 /// let duration = Duration::from_nanos(1_000_000_123);
213 /// assert_eq!(1, duration.as_secs());
214 /// assert_eq!(123, duration.subsec_nanos());
216 #[stable(feature = "duration_extras", since = "1.27.0")]
218 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
219 pub const fn from_nanos(nanos: u64) -> Duration {
221 secs: nanos / (NANOS_PER_SEC as u64),
222 nanos: (nanos % (NANOS_PER_SEC as u64)) as u32,
226 /// Creates a new `Duration` that spans no time.
231 /// #![feature(duration_zero)]
232 /// use std::time::Duration;
234 /// let duration = Duration::zero();
235 /// assert!(duration.is_zero());
237 /// const IMMEDIATELY: Duration = Duration::zero();
238 /// assert!(IMMEDIATELY.is_zero());
240 #[unstable(feature = "duration_zero", issue = "none")]
242 pub const fn zero() -> Duration {
243 Duration { secs: 0, nanos: 0 }
246 /// Returns true if this `Duration` spans no time.
251 /// #![feature(duration_zero)]
252 /// use std::time::Duration;
254 /// assert!(Duration::zero().is_zero());
255 /// assert!(Duration::new(0, 0).is_zero());
256 /// assert!(Duration::from_nanos(0).is_zero());
257 /// assert!(Duration::from_secs(0).is_zero());
259 /// assert!(!Duration::new(1, 1).is_zero());
260 /// assert!(!Duration::from_nanos(1).is_zero());
261 /// assert!(!Duration::from_secs(1).is_zero());
263 #[unstable(feature = "duration_zero", issue = "none")]
265 pub const fn is_zero(&self) -> bool {
266 self.secs == 0 && self.nanos == 0
269 /// Returns the number of _whole_ seconds contained by this `Duration`.
271 /// The returned value does not include the fractional (nanosecond) part of the
272 /// duration, which can be obtained using [`subsec_nanos`].
277 /// use std::time::Duration;
279 /// let duration = Duration::new(5, 730023852);
280 /// assert_eq!(duration.as_secs(), 5);
283 /// To determine the total number of seconds represented by the `Duration`,
284 /// use `as_secs` in combination with [`subsec_nanos`]:
287 /// use std::time::Duration;
289 /// let duration = Duration::new(5, 730023852);
291 /// assert_eq!(5.730023852,
292 /// duration.as_secs() as f64
293 /// + duration.subsec_nanos() as f64 * 1e-9);
296 /// [`subsec_nanos`]: #method.subsec_nanos
297 #[stable(feature = "duration", since = "1.3.0")]
298 #[rustc_const_stable(feature = "duration", since = "1.32.0")]
300 pub const fn as_secs(&self) -> u64 {
304 /// Returns the fractional part of this `Duration`, in whole milliseconds.
306 /// This method does **not** return the length of the duration when
307 /// represented by milliseconds. The returned number always represents a
308 /// fractional portion of a second (i.e., it is less than one thousand).
313 /// use std::time::Duration;
315 /// let duration = Duration::from_millis(5432);
316 /// assert_eq!(duration.as_secs(), 5);
317 /// assert_eq!(duration.subsec_millis(), 432);
319 #[stable(feature = "duration_extras", since = "1.27.0")]
320 #[rustc_const_stable(feature = "duration_extras", since = "1.32.0")]
322 pub const fn subsec_millis(&self) -> u32 {
323 self.nanos / NANOS_PER_MILLI
326 /// Returns the fractional part of this `Duration`, in whole microseconds.
328 /// This method does **not** return the length of the duration when
329 /// represented by microseconds. The returned number always represents a
330 /// fractional portion of a second (i.e., it is less than one million).
335 /// use std::time::Duration;
337 /// let duration = Duration::from_micros(1_234_567);
338 /// assert_eq!(duration.as_secs(), 1);
339 /// assert_eq!(duration.subsec_micros(), 234_567);
341 #[stable(feature = "duration_extras", since = "1.27.0")]
342 #[rustc_const_stable(feature = "duration_extras", since = "1.32.0")]
344 pub const fn subsec_micros(&self) -> u32 {
345 self.nanos / NANOS_PER_MICRO
348 /// Returns the fractional part of this `Duration`, in nanoseconds.
350 /// This method does **not** return the length of the duration when
351 /// represented by nanoseconds. The returned number always represents a
352 /// fractional portion of a second (i.e., it is less than one billion).
357 /// use std::time::Duration;
359 /// let duration = Duration::from_millis(5010);
360 /// assert_eq!(duration.as_secs(), 5);
361 /// assert_eq!(duration.subsec_nanos(), 10_000_000);
363 #[stable(feature = "duration", since = "1.3.0")]
364 #[rustc_const_stable(feature = "duration", since = "1.32.0")]
366 pub const fn subsec_nanos(&self) -> u32 {
370 /// Returns the total number of whole milliseconds contained by this `Duration`.
375 /// use std::time::Duration;
377 /// let duration = Duration::new(5, 730023852);
378 /// assert_eq!(duration.as_millis(), 5730);
380 #[stable(feature = "duration_as_u128", since = "1.33.0")]
381 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
383 pub const fn as_millis(&self) -> u128 {
384 self.secs as u128 * MILLIS_PER_SEC as u128 + (self.nanos / NANOS_PER_MILLI) as u128
387 /// Returns the total number of whole microseconds contained by this `Duration`.
392 /// use std::time::Duration;
394 /// let duration = Duration::new(5, 730023852);
395 /// assert_eq!(duration.as_micros(), 5730023);
397 #[stable(feature = "duration_as_u128", since = "1.33.0")]
398 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
400 pub const fn as_micros(&self) -> u128 {
401 self.secs as u128 * MICROS_PER_SEC as u128 + (self.nanos / NANOS_PER_MICRO) as u128
404 /// Returns the total number of nanoseconds contained by this `Duration`.
409 /// use std::time::Duration;
411 /// let duration = Duration::new(5, 730023852);
412 /// assert_eq!(duration.as_nanos(), 5730023852);
414 #[stable(feature = "duration_as_u128", since = "1.33.0")]
415 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
417 pub const fn as_nanos(&self) -> u128 {
418 self.secs as u128 * NANOS_PER_SEC as u128 + self.nanos as u128
421 /// Checked `Duration` addition. Computes `self + other`, returning [`None`]
422 /// if overflow occurred.
424 /// [`None`]: ../../std/option/enum.Option.html#variant.None
431 /// use std::time::Duration;
433 /// assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1)));
434 /// assert_eq!(Duration::new(1, 0).checked_add(Duration::new(u64::MAX, 0)), None);
436 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
438 pub fn checked_add(self, rhs: Duration) -> Option<Duration> {
439 if let Some(mut secs) = self.secs.checked_add(rhs.secs) {
440 let mut nanos = self.nanos + rhs.nanos;
441 if nanos >= NANOS_PER_SEC {
442 nanos -= NANOS_PER_SEC;
443 if let Some(new_secs) = secs.checked_add(1) {
449 debug_assert!(nanos < NANOS_PER_SEC);
450 Some(Duration { secs, nanos })
456 /// Checked `Duration` subtraction. Computes `self - other`, returning [`None`]
457 /// if the result would be negative or if overflow occurred.
459 /// [`None`]: ../../std/option/enum.Option.html#variant.None
466 /// use std::time::Duration;
468 /// assert_eq!(Duration::new(0, 1).checked_sub(Duration::new(0, 0)), Some(Duration::new(0, 1)));
469 /// assert_eq!(Duration::new(0, 0).checked_sub(Duration::new(0, 1)), None);
471 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
473 pub fn checked_sub(self, rhs: Duration) -> Option<Duration> {
474 if let Some(mut secs) = self.secs.checked_sub(rhs.secs) {
475 let nanos = if self.nanos >= rhs.nanos {
476 self.nanos - rhs.nanos
478 if let Some(sub_secs) = secs.checked_sub(1) {
480 self.nanos + NANOS_PER_SEC - rhs.nanos
485 debug_assert!(nanos < NANOS_PER_SEC);
486 Some(Duration { secs, nanos })
492 /// Checked `Duration` multiplication. Computes `self * other`, returning
493 /// [`None`] if overflow occurred.
495 /// [`None`]: ../../std/option/enum.Option.html#variant.None
502 /// use std::time::Duration;
504 /// assert_eq!(Duration::new(0, 500_000_001).checked_mul(2), Some(Duration::new(1, 2)));
505 /// assert_eq!(Duration::new(u64::MAX - 1, 0).checked_mul(2), None);
507 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
509 pub fn checked_mul(self, rhs: u32) -> Option<Duration> {
510 // Multiply nanoseconds as u64, because it cannot overflow that way.
511 let total_nanos = self.nanos as u64 * rhs as u64;
512 let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
513 let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
515 self.secs.checked_mul(rhs as u64).and_then(|s| s.checked_add(extra_secs))
517 debug_assert!(nanos < NANOS_PER_SEC);
518 Some(Duration { secs, nanos })
524 /// Checked `Duration` division. Computes `self / other`, returning [`None`]
527 /// [`None`]: ../../std/option/enum.Option.html#variant.None
534 /// use std::time::Duration;
536 /// assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0)));
537 /// assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000)));
538 /// assert_eq!(Duration::new(2, 0).checked_div(0), None);
540 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
542 pub fn checked_div(self, rhs: u32) -> Option<Duration> {
544 let secs = self.secs / (rhs as u64);
545 let carry = self.secs - secs * (rhs as u64);
546 let extra_nanos = carry * (NANOS_PER_SEC as u64) / (rhs as u64);
547 let nanos = self.nanos / rhs + (extra_nanos as u32);
548 debug_assert!(nanos < NANOS_PER_SEC);
549 Some(Duration { secs, nanos })
555 /// Returns the number of seconds contained by this `Duration` as `f64`.
557 /// The returned value does include the fractional (nanosecond) part of the duration.
561 /// use std::time::Duration;
563 /// let dur = Duration::new(2, 700_000_000);
564 /// assert_eq!(dur.as_secs_f64(), 2.7);
566 #[stable(feature = "duration_float", since = "1.38.0")]
568 pub fn as_secs_f64(&self) -> f64 {
569 (self.secs as f64) + (self.nanos as f64) / (NANOS_PER_SEC as f64)
572 /// Returns the number of seconds contained by this `Duration` as `f32`.
574 /// The returned value does include the fractional (nanosecond) part of the duration.
578 /// use std::time::Duration;
580 /// let dur = Duration::new(2, 700_000_000);
581 /// assert_eq!(dur.as_secs_f32(), 2.7);
583 #[stable(feature = "duration_float", since = "1.38.0")]
585 pub fn as_secs_f32(&self) -> f32 {
586 (self.secs as f32) + (self.nanos as f32) / (NANOS_PER_SEC as f32)
589 /// Creates a new `Duration` from the specified number of seconds represented
593 /// This constructor will panic if `secs` is not finite, negative or overflows `Duration`.
597 /// use std::time::Duration;
599 /// let dur = Duration::from_secs_f64(2.7);
600 /// assert_eq!(dur, Duration::new(2, 700_000_000));
602 #[stable(feature = "duration_float", since = "1.38.0")]
604 pub fn from_secs_f64(secs: f64) -> Duration {
605 const MAX_NANOS_F64: f64 = ((u64::MAX as u128 + 1) * (NANOS_PER_SEC as u128)) as f64;
606 let nanos = secs * (NANOS_PER_SEC as f64);
607 if !nanos.is_finite() {
608 panic!("got non-finite value when converting float to duration");
610 if nanos >= MAX_NANOS_F64 {
611 panic!("overflow when converting float to duration");
614 panic!("underflow when converting float to duration");
616 let nanos = nanos as u128;
618 secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
619 nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
623 /// Creates a new `Duration` from the specified number of seconds represented
627 /// This constructor will panic if `secs` is not finite, negative or overflows `Duration`.
631 /// use std::time::Duration;
633 /// let dur = Duration::from_secs_f32(2.7);
634 /// assert_eq!(dur, Duration::new(2, 700_000_000));
636 #[stable(feature = "duration_float", since = "1.38.0")]
638 pub fn from_secs_f32(secs: f32) -> Duration {
639 const MAX_NANOS_F32: f32 = ((u64::MAX as u128 + 1) * (NANOS_PER_SEC as u128)) as f32;
640 let nanos = secs * (NANOS_PER_SEC as f32);
641 if !nanos.is_finite() {
642 panic!("got non-finite value when converting float to duration");
644 if nanos >= MAX_NANOS_F32 {
645 panic!("overflow when converting float to duration");
648 panic!("underflow when converting float to duration");
650 let nanos = nanos as u128;
652 secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
653 nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
657 /// Multiplies `Duration` by `f64`.
660 /// This method will panic if result is not finite, negative or overflows `Duration`.
664 /// use std::time::Duration;
666 /// let dur = Duration::new(2, 700_000_000);
667 /// assert_eq!(dur.mul_f64(3.14), Duration::new(8, 478_000_000));
668 /// assert_eq!(dur.mul_f64(3.14e5), Duration::new(847_800, 0));
670 #[stable(feature = "duration_float", since = "1.38.0")]
672 pub fn mul_f64(self, rhs: f64) -> Duration {
673 Duration::from_secs_f64(rhs * self.as_secs_f64())
676 /// Multiplies `Duration` by `f32`.
679 /// This method will panic if result is not finite, negative or overflows `Duration`.
683 /// use std::time::Duration;
685 /// let dur = Duration::new(2, 700_000_000);
686 /// // note that due to rounding errors result is slightly different
687 /// // from 8.478 and 847800.0
688 /// assert_eq!(dur.mul_f32(3.14), Duration::new(8, 478_000_640));
689 /// assert_eq!(dur.mul_f32(3.14e5), Duration::new(847799, 969_120_256));
691 #[stable(feature = "duration_float", since = "1.38.0")]
693 pub fn mul_f32(self, rhs: f32) -> Duration {
694 Duration::from_secs_f32(rhs * self.as_secs_f32())
697 /// Divide `Duration` by `f64`.
700 /// This method will panic if result is not finite, negative or overflows `Duration`.
704 /// use std::time::Duration;
706 /// let dur = Duration::new(2, 700_000_000);
707 /// assert_eq!(dur.div_f64(3.14), Duration::new(0, 859_872_611));
708 /// // note that truncation is used, not rounding
709 /// assert_eq!(dur.div_f64(3.14e5), Duration::new(0, 8_598));
711 #[stable(feature = "duration_float", since = "1.38.0")]
713 pub fn div_f64(self, rhs: f64) -> Duration {
714 Duration::from_secs_f64(self.as_secs_f64() / rhs)
717 /// Divide `Duration` by `f32`.
720 /// This method will panic if result is not finite, negative or overflows `Duration`.
724 /// use std::time::Duration;
726 /// let dur = Duration::new(2, 700_000_000);
727 /// // note that due to rounding errors result is slightly
728 /// // different from 0.859_872_611
729 /// assert_eq!(dur.div_f32(3.14), Duration::new(0, 859_872_576));
730 /// // note that truncation is used, not rounding
731 /// assert_eq!(dur.div_f32(3.14e5), Duration::new(0, 8_598));
733 #[stable(feature = "duration_float", since = "1.38.0")]
735 pub fn div_f32(self, rhs: f32) -> Duration {
736 Duration::from_secs_f32(self.as_secs_f32() / rhs)
739 /// Divide `Duration` by `Duration` and return `f64`.
743 /// #![feature(div_duration)]
744 /// use std::time::Duration;
746 /// let dur1 = Duration::new(2, 700_000_000);
747 /// let dur2 = Duration::new(5, 400_000_000);
748 /// assert_eq!(dur1.div_duration_f64(dur2), 0.5);
750 #[unstable(feature = "div_duration", issue = "63139")]
752 pub fn div_duration_f64(self, rhs: Duration) -> f64 {
753 self.as_secs_f64() / rhs.as_secs_f64()
756 /// Divide `Duration` by `Duration` and return `f32`.
760 /// #![feature(div_duration)]
761 /// use std::time::Duration;
763 /// let dur1 = Duration::new(2, 700_000_000);
764 /// let dur2 = Duration::new(5, 400_000_000);
765 /// assert_eq!(dur1.div_duration_f32(dur2), 0.5);
767 #[unstable(feature = "div_duration", issue = "63139")]
769 pub fn div_duration_f32(self, rhs: Duration) -> f32 {
770 self.as_secs_f32() / rhs.as_secs_f32()
774 #[stable(feature = "duration", since = "1.3.0")]
775 impl Add for Duration {
776 type Output = Duration;
778 fn add(self, rhs: Duration) -> Duration {
779 self.checked_add(rhs).expect("overflow when adding durations")
783 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
784 impl AddAssign for Duration {
785 fn add_assign(&mut self, rhs: Duration) {
790 #[stable(feature = "duration", since = "1.3.0")]
791 impl Sub for Duration {
792 type Output = Duration;
794 fn sub(self, rhs: Duration) -> Duration {
795 self.checked_sub(rhs).expect("overflow when subtracting durations")
799 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
800 impl SubAssign for Duration {
801 fn sub_assign(&mut self, rhs: Duration) {
806 #[stable(feature = "duration", since = "1.3.0")]
807 impl Mul<u32> for Duration {
808 type Output = Duration;
810 fn mul(self, rhs: u32) -> Duration {
811 self.checked_mul(rhs).expect("overflow when multiplying duration by scalar")
815 #[stable(feature = "symmetric_u32_duration_mul", since = "1.31.0")]
816 impl Mul<Duration> for u32 {
817 type Output = Duration;
819 fn mul(self, rhs: Duration) -> Duration {
824 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
825 impl MulAssign<u32> for Duration {
826 fn mul_assign(&mut self, rhs: u32) {
831 #[stable(feature = "duration", since = "1.3.0")]
832 impl Div<u32> for Duration {
833 type Output = Duration;
835 fn div(self, rhs: u32) -> Duration {
836 self.checked_div(rhs).expect("divide by zero error when dividing duration by scalar")
840 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
841 impl DivAssign<u32> for Duration {
842 fn div_assign(&mut self, rhs: u32) {
847 macro_rules! sum_durations {
849 let mut total_secs: u64 = 0;
850 let mut total_nanos: u64 = 0;
854 total_secs.checked_add(entry.secs).expect("overflow in iter::sum over durations");
855 total_nanos = match total_nanos.checked_add(entry.nanos as u64) {
858 total_secs = total_secs
859 .checked_add(total_nanos / NANOS_PER_SEC as u64)
860 .expect("overflow in iter::sum over durations");
861 (total_nanos % NANOS_PER_SEC as u64) + entry.nanos as u64
865 total_secs = total_secs
866 .checked_add(total_nanos / NANOS_PER_SEC as u64)
867 .expect("overflow in iter::sum over durations");
868 total_nanos = total_nanos % NANOS_PER_SEC as u64;
869 Duration { secs: total_secs, nanos: total_nanos as u32 }
873 #[stable(feature = "duration_sum", since = "1.16.0")]
874 impl Sum for Duration {
875 fn sum<I: Iterator<Item = Duration>>(iter: I) -> Duration {
880 #[stable(feature = "duration_sum", since = "1.16.0")]
881 impl<'a> Sum<&'a Duration> for Duration {
882 fn sum<I: Iterator<Item = &'a Duration>>(iter: I) -> Duration {
887 #[stable(feature = "duration_debug_impl", since = "1.27.0")]
888 impl fmt::Debug for Duration {
889 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
890 /// Formats a floating point number in decimal notation.
892 /// The number is given as the `integer_part` and a fractional part.
893 /// The value of the fractional part is `fractional_part / divisor`. So
894 /// `integer_part` = 3, `fractional_part` = 12 and `divisor` = 100
895 /// represents the number `3.012`. Trailing zeros are omitted.
897 /// `divisor` must not be above 100_000_000. It also should be a power
898 /// of 10, everything else doesn't make sense. `fractional_part` has
899 /// to be less than `10 * divisor`!
901 f: &mut fmt::Formatter<'_>,
902 mut integer_part: u64,
903 mut fractional_part: u32,
906 // Encode the fractional part into a temporary buffer. The buffer
907 // only need to hold 9 elements, because `fractional_part` has to
908 // be smaller than 10^9. The buffer is prefilled with '0' digits
909 // to simplify the code below.
910 let mut buf = [b'0'; 9];
912 // The next digit is written at this position
915 // We keep writing digits into the buffer while there are non-zero
916 // digits left and we haven't written enough digits yet.
917 while fractional_part > 0 && pos < f.precision().unwrap_or(9) {
918 // Write new digit into the buffer
919 buf[pos] = b'0' + (fractional_part / divisor) as u8;
921 fractional_part %= divisor;
926 // If a precision < 9 was specified, there may be some non-zero
927 // digits left that weren't written into the buffer. In that case we
928 // need to perform rounding to match the semantics of printing
929 // normal floating point numbers. However, we only need to do work
930 // when rounding up. This happens if the first digit of the
931 // remaining ones is >= 5.
932 if fractional_part > 0 && fractional_part >= divisor * 5 {
933 // Round up the number contained in the buffer. We go through
934 // the buffer backwards and keep track of the carry.
935 let mut rev_pos = pos;
936 let mut carry = true;
937 while carry && rev_pos > 0 {
940 // If the digit in the buffer is not '9', we just need to
941 // increment it and can stop then (since we don't have a
942 // carry anymore). Otherwise, we set it to '0' (overflow)
944 if buf[rev_pos] < b'9' {
952 // If we still have the carry bit set, that means that we set
953 // the whole buffer to '0's and need to increment the integer
960 // Determine the end of the buffer: if precision is set, we just
961 // use as many digits from the buffer (capped to 9). If it isn't
962 // set, we only use all digits up to the last non-zero one.
963 let end = f.precision().map(|p| crate::cmp::min(p, 9)).unwrap_or(pos);
965 // If we haven't emitted a single fractional digit and the precision
966 // wasn't set to a non-zero value, we don't print the decimal point.
968 write!(f, "{}", integer_part)
970 // SAFETY: We are only writing ASCII digits into the buffer and it was
971 // initialized with '0's, so it contains valid UTF8.
972 let s = unsafe { crate::str::from_utf8_unchecked(&buf[..end]) };
974 // If the user request a precision > 9, we pad '0's at the end.
975 let w = f.precision().unwrap_or(pos);
976 write!(f, "{}.{:0<width$}", integer_part, s, width = w)
980 // Print leading '+' sign if requested
986 fmt_decimal(f, self.secs, self.nanos, 100_000_000)?;
988 } else if self.nanos >= 1_000_000 {
989 fmt_decimal(f, self.nanos as u64 / 1_000_000, self.nanos % 1_000_000, 100_000)?;
991 } else if self.nanos >= 1_000 {
992 fmt_decimal(f, self.nanos as u64 / 1_000, self.nanos % 1_000, 100)?;
995 fmt_decimal(f, self.nanos as u64, 0, 1)?;