1 // Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10 #![stable(feature = "duration_core", since = "1.25.0")]
12 //! Temporal quantification.
17 //! use std::time::Duration;
19 //! let five_seconds = Duration::new(5, 0);
20 //! // both declarations are equivalent
21 //! assert_eq!(Duration::new(5, 0), Duration::from_secs(5));
26 use ops::{Add, Sub, Mul, Div, AddAssign, SubAssign, MulAssign, DivAssign};
28 const NANOS_PER_SEC: u32 = 1_000_000_000;
29 const NANOS_PER_MILLI: u32 = 1_000_000;
30 const NANOS_PER_MICRO: u32 = 1_000;
31 const MILLIS_PER_SEC: u64 = 1_000;
32 const MICROS_PER_SEC: u64 = 1_000_000;
33 const MAX_NANOS_F64: f64 = ((u64::MAX as u128)*(NANOS_PER_SEC as u128)) as f64;
35 /// A `Duration` type to represent a span of time, typically used for system
38 /// Each `Duration` is composed of a whole number of seconds and a fractional part
39 /// represented in nanoseconds. If the underlying system does not support
40 /// nanosecond-level precision, APIs binding a system timeout will typically round up
41 /// the number of nanoseconds.
43 /// `Duration`s implement many common traits, including [`Add`], [`Sub`], and other
46 /// [`Add`]: ../../std/ops/trait.Add.html
47 /// [`Sub`]: ../../std/ops/trait.Sub.html
48 /// [`ops`]: ../../std/ops/index.html
53 /// use std::time::Duration;
55 /// let five_seconds = Duration::new(5, 0);
56 /// let five_seconds_and_five_nanos = five_seconds + Duration::new(0, 5);
58 /// assert_eq!(five_seconds_and_five_nanos.as_secs(), 5);
59 /// assert_eq!(five_seconds_and_five_nanos.subsec_nanos(), 5);
61 /// let ten_millis = Duration::from_millis(10);
63 #[stable(feature = "duration", since = "1.3.0")]
64 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
67 nanos: u32, // Always 0 <= nanos < NANOS_PER_SEC
71 /// Creates a new `Duration` from the specified number of whole seconds and
72 /// additional nanoseconds.
74 /// If the number of nanoseconds is greater than 1 billion (the number of
75 /// nanoseconds in a second), then it will carry over into the seconds provided.
79 /// This constructor will panic if the carry from the nanoseconds overflows
80 /// the seconds counter.
85 /// use std::time::Duration;
87 /// let five_seconds = Duration::new(5, 0);
89 #[stable(feature = "duration", since = "1.3.0")]
91 pub fn new(secs: u64, nanos: u32) -> Duration {
92 let secs = secs.checked_add((nanos / NANOS_PER_SEC) as u64)
93 .expect("overflow in Duration::new");
94 let nanos = nanos % NANOS_PER_SEC;
95 Duration { secs: secs, nanos: nanos }
98 /// Creates a new `Duration` from the specified number of whole seconds.
103 /// use std::time::Duration;
105 /// let duration = Duration::from_secs(5);
107 /// assert_eq!(5, duration.as_secs());
108 /// assert_eq!(0, duration.subsec_nanos());
110 #[stable(feature = "duration", since = "1.3.0")]
112 pub const fn from_secs(secs: u64) -> Duration {
113 Duration { secs: secs, nanos: 0 }
116 /// Creates a new `Duration` from the specified number of milliseconds.
121 /// use std::time::Duration;
123 /// let duration = Duration::from_millis(2569);
125 /// assert_eq!(2, duration.as_secs());
126 /// assert_eq!(569_000_000, duration.subsec_nanos());
128 #[stable(feature = "duration", since = "1.3.0")]
130 pub const fn from_millis(millis: u64) -> Duration {
132 secs: millis / MILLIS_PER_SEC,
133 nanos: ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI,
137 /// Creates a new `Duration` from the specified number of microseconds.
142 /// use std::time::Duration;
144 /// let duration = Duration::from_micros(1_000_002);
146 /// assert_eq!(1, duration.as_secs());
147 /// assert_eq!(2000, duration.subsec_nanos());
149 #[stable(feature = "duration_from_micros", since = "1.27.0")]
151 pub const fn from_micros(micros: u64) -> Duration {
153 secs: micros / MICROS_PER_SEC,
154 nanos: ((micros % MICROS_PER_SEC) as u32) * NANOS_PER_MICRO,
158 /// Creates a new `Duration` from the specified number of nanoseconds.
163 /// use std::time::Duration;
165 /// let duration = Duration::from_nanos(1_000_000_123);
167 /// assert_eq!(1, duration.as_secs());
168 /// assert_eq!(123, duration.subsec_nanos());
170 #[stable(feature = "duration_extras", since = "1.27.0")]
172 pub const fn from_nanos(nanos: u64) -> Duration {
174 secs: nanos / (NANOS_PER_SEC as u64),
175 nanos: (nanos % (NANOS_PER_SEC as u64)) as u32,
179 /// Returns the number of _whole_ seconds contained by this `Duration`.
181 /// The returned value does not include the fractional (nanosecond) part of the
182 /// duration, which can be obtained using [`subsec_nanos`].
187 /// use std::time::Duration;
189 /// let duration = Duration::new(5, 730023852);
190 /// assert_eq!(duration.as_secs(), 5);
193 /// To determine the total number of seconds represented by the `Duration`,
194 /// use `as_secs` in combination with [`subsec_nanos`]:
197 /// use std::time::Duration;
199 /// let duration = Duration::new(5, 730023852);
201 /// assert_eq!(5.730023852,
202 /// duration.as_secs() as f64
203 /// + duration.subsec_nanos() as f64 * 1e-9);
206 /// [`subsec_nanos`]: #method.subsec_nanos
207 #[stable(feature = "duration", since = "1.3.0")]
208 #[rustc_const_unstable(feature="duration_getters")]
210 pub const fn as_secs(&self) -> u64 { self.secs }
212 /// Returns the fractional part of this `Duration`, in whole milliseconds.
214 /// This method does **not** return the length of the duration when
215 /// represented by milliseconds. The returned number always represents a
216 /// fractional portion of a second (i.e. it is less than one thousand).
221 /// use std::time::Duration;
223 /// let duration = Duration::from_millis(5432);
224 /// assert_eq!(duration.as_secs(), 5);
225 /// assert_eq!(duration.subsec_millis(), 432);
227 #[stable(feature = "duration_extras", since = "1.27.0")]
228 #[rustc_const_unstable(feature="duration_getters")]
230 pub const fn subsec_millis(&self) -> u32 { self.nanos / NANOS_PER_MILLI }
232 /// Returns the fractional part of this `Duration`, in whole microseconds.
234 /// This method does **not** return the length of the duration when
235 /// represented by microseconds. The returned number always represents a
236 /// fractional portion of a second (i.e. it is less than one million).
241 /// use std::time::Duration;
243 /// let duration = Duration::from_micros(1_234_567);
244 /// assert_eq!(duration.as_secs(), 1);
245 /// assert_eq!(duration.subsec_micros(), 234_567);
247 #[stable(feature = "duration_extras", since = "1.27.0")]
248 #[rustc_const_unstable(feature="duration_getters")]
250 pub const fn subsec_micros(&self) -> u32 { self.nanos / NANOS_PER_MICRO }
252 /// Returns the fractional part of this `Duration`, in nanoseconds.
254 /// This method does **not** return the length of the duration when
255 /// represented by nanoseconds. The returned number always represents a
256 /// fractional portion of a second (i.e. it is less than one billion).
261 /// use std::time::Duration;
263 /// let duration = Duration::from_millis(5010);
264 /// assert_eq!(duration.as_secs(), 5);
265 /// assert_eq!(duration.subsec_nanos(), 10_000_000);
267 #[stable(feature = "duration", since = "1.3.0")]
268 #[rustc_const_unstable(feature="duration_getters")]
270 pub const fn subsec_nanos(&self) -> u32 { self.nanos }
272 /// Returns the total number of whole milliseconds contained by this `Duration`.
277 /// # #![feature(duration_as_u128)]
278 /// use std::time::Duration;
280 /// let duration = Duration::new(5, 730023852);
281 /// assert_eq!(duration.as_millis(), 5730);
283 #[unstable(feature = "duration_as_u128", issue = "50202")]
285 pub fn as_millis(&self) -> u128 {
286 self.secs as u128 * MILLIS_PER_SEC as u128 + (self.nanos / NANOS_PER_MILLI) as u128
289 /// Returns the total number of whole microseconds contained by this `Duration`.
294 /// # #![feature(duration_as_u128)]
295 /// use std::time::Duration;
297 /// let duration = Duration::new(5, 730023852);
298 /// assert_eq!(duration.as_micros(), 5730023);
300 #[unstable(feature = "duration_as_u128", issue = "50202")]
302 pub fn as_micros(&self) -> u128 {
303 self.secs as u128 * MICROS_PER_SEC as u128 + (self.nanos / NANOS_PER_MICRO) as u128
306 /// Returns the total number of nanoseconds contained by this `Duration`.
311 /// # #![feature(duration_as_u128)]
312 /// use std::time::Duration;
314 /// let duration = Duration::new(5, 730023852);
315 /// assert_eq!(duration.as_nanos(), 5730023852);
317 #[unstable(feature = "duration_as_u128", issue = "50202")]
319 pub fn as_nanos(&self) -> u128 {
320 self.secs as u128 * NANOS_PER_SEC as u128 + self.nanos as u128
323 /// Checked `Duration` addition. Computes `self + other`, returning [`None`]
324 /// if overflow occurred.
326 /// [`None`]: ../../std/option/enum.Option.html#variant.None
333 /// use std::time::Duration;
335 /// assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1)));
336 /// assert_eq!(Duration::new(1, 0).checked_add(Duration::new(std::u64::MAX, 0)), None);
338 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
340 pub fn checked_add(self, rhs: Duration) -> Option<Duration> {
341 if let Some(mut secs) = self.secs.checked_add(rhs.secs) {
342 let mut nanos = self.nanos + rhs.nanos;
343 if nanos >= NANOS_PER_SEC {
344 nanos -= NANOS_PER_SEC;
345 if let Some(new_secs) = secs.checked_add(1) {
351 debug_assert!(nanos < NANOS_PER_SEC);
361 /// Checked `Duration` subtraction. Computes `self - other`, returning [`None`]
362 /// if the result would be negative or if overflow occurred.
364 /// [`None`]: ../../std/option/enum.Option.html#variant.None
371 /// use std::time::Duration;
373 /// assert_eq!(Duration::new(0, 1).checked_sub(Duration::new(0, 0)), Some(Duration::new(0, 1)));
374 /// assert_eq!(Duration::new(0, 0).checked_sub(Duration::new(0, 1)), None);
376 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
378 pub fn checked_sub(self, rhs: Duration) -> Option<Duration> {
379 if let Some(mut secs) = self.secs.checked_sub(rhs.secs) {
380 let nanos = if self.nanos >= rhs.nanos {
381 self.nanos - rhs.nanos
383 if let Some(sub_secs) = secs.checked_sub(1) {
385 self.nanos + NANOS_PER_SEC - rhs.nanos
390 debug_assert!(nanos < NANOS_PER_SEC);
391 Some(Duration { secs: secs, nanos: nanos })
397 /// Checked `Duration` multiplication. Computes `self * other`, returning
398 /// [`None`] if overflow occurred.
400 /// [`None`]: ../../std/option/enum.Option.html#variant.None
407 /// use std::time::Duration;
409 /// assert_eq!(Duration::new(0, 500_000_001).checked_mul(2), Some(Duration::new(1, 2)));
410 /// assert_eq!(Duration::new(std::u64::MAX - 1, 0).checked_mul(2), None);
412 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
414 pub fn checked_mul(self, rhs: u32) -> Option<Duration> {
415 // Multiply nanoseconds as u64, because it cannot overflow that way.
416 let total_nanos = self.nanos as u64 * rhs as u64;
417 let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
418 let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
419 if let Some(secs) = self.secs
420 .checked_mul(rhs as u64)
421 .and_then(|s| s.checked_add(extra_secs)) {
422 debug_assert!(nanos < NANOS_PER_SEC);
432 /// Checked `Duration` division. Computes `self / other`, returning [`None`]
435 /// [`None`]: ../../std/option/enum.Option.html#variant.None
442 /// use std::time::Duration;
444 /// assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0)));
445 /// assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000)));
446 /// assert_eq!(Duration::new(2, 0).checked_div(0), None);
448 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
450 pub fn checked_div(self, rhs: u32) -> Option<Duration> {
452 let secs = self.secs / (rhs as u64);
453 let carry = self.secs - secs * (rhs as u64);
454 let extra_nanos = carry * (NANOS_PER_SEC as u64) / (rhs as u64);
455 let nanos = self.nanos / rhs + (extra_nanos as u32);
456 debug_assert!(nanos < NANOS_PER_SEC);
457 Some(Duration { secs: secs, nanos: nanos })
463 /// Returns the number of seconds contained by this `Duration` as `f64`.
465 /// The returned value does include the fractional (nanosecond) part of the duration.
469 /// #![feature(duration_float)]
470 /// use std::time::Duration;
472 /// let dur = Duration::new(2, 700_000_000);
473 /// assert_eq!(dur.as_float_secs(), 2.7);
475 #[unstable(feature = "duration_float", issue = "0")]
477 pub fn as_float_secs(&self) -> f64 {
478 (self.secs as f64) + (self.nanos as f64) / (NANOS_PER_SEC as f64)
481 /// Creates a new `Duration` from the specified number of seconds.
485 /// #![feature(duration_float)]
486 /// use std::time::Duration;
488 /// let dur = Duration::from_float_secs(2.7);
489 /// assert_eq!(dur, Duration::new(2, 700_000_000));
491 #[unstable(feature = "duration_float", issue = "0")]
493 pub fn from_float_secs(secs: f64) -> Duration {
494 let nanos = (secs * (NANOS_PER_SEC as f64)) as u128;
496 secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
497 nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
501 /// Multiply `Duration` by `f64`.
505 /// #![feature(duration_float)]
506 /// use std::time::Duration;
508 /// let dur = Duration::new(2, 700_000_000);
509 /// assert_eq!(dur.mul_f64(3.14), Duration::new(8, 478_000_000));
510 /// assert_eq!(dur.mul_f64(3.14e5), Duration::new(847_800, 0));
512 #[unstable(feature = "duration_float", issue = "0")]
514 pub fn mul_f64(self, rhs: f64) -> Duration {
515 let secs = rhs * self.as_float_secs();
516 if !secs.is_finite() {
517 panic!("got non-finite value when multiplying duration by float");
519 if secs > MAX_NANOS_F64 {
520 panic!("overflow when multiplying duration by float");
523 panic!("underflow when multiplying duration by float");
525 Duration::from_float_secs(secs)
528 /// Divide `Duration` by `f64`.
532 /// #![feature(duration_float)]
533 /// use std::time::Duration;
535 /// let dur = Duration::new(2, 700_000_000);
536 /// assert_eq!(dur.div_f64(3.14), Duration::new(0, 859_872_611));
537 /// // note that truncation is used, not rounding
538 /// assert_eq!(dur.div_f64(3.14e5), Duration::new(0, 8_598));
540 #[unstable(feature = "duration_float", issue = "0")]
542 pub fn div_f64(self, rhs: f64) -> Duration {
543 let secs = self.as_float_secs() / rhs;
544 if !secs.is_finite() {
545 panic!("got non-finite value when dividing duration by float");
547 if secs > MAX_NANOS_F64 {
548 panic!("overflow when dividing duration by float");
551 panic!("underflow when multiplying duration by float");
553 Duration::from_float_secs(secs)
556 /// Divide `Duration` by `Duration` and return `f64`.
560 /// #![feature(duration_float)]
561 /// use std::time::Duration;
563 /// let dur1 = Duration::new(2, 700_000_000);
564 /// let dur2 = Duration::new(5, 400_000_000);
565 /// assert_eq!(dur1.div_duration(dur2), 0.5);
567 #[unstable(feature = "duration_float", issue = "0")]
569 pub fn div_duration(self, rhs: Duration) -> f64 {
570 self.as_float_secs()/rhs.as_float_secs()
574 #[stable(feature = "duration", since = "1.3.0")]
575 impl Add for Duration {
576 type Output = Duration;
578 fn add(self, rhs: Duration) -> Duration {
579 self.checked_add(rhs).expect("overflow when adding durations")
583 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
584 impl AddAssign for Duration {
585 fn add_assign(&mut self, rhs: Duration) {
590 #[stable(feature = "duration", since = "1.3.0")]
591 impl Sub for Duration {
592 type Output = Duration;
594 fn sub(self, rhs: Duration) -> Duration {
595 self.checked_sub(rhs).expect("overflow when subtracting durations")
599 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
600 impl SubAssign for Duration {
601 fn sub_assign(&mut self, rhs: Duration) {
606 #[stable(feature = "duration", since = "1.3.0")]
607 impl Mul<u32> for Duration {
608 type Output = Duration;
610 fn mul(self, rhs: u32) -> Duration {
611 self.checked_mul(rhs).expect("overflow when multiplying duration by scalar")
615 #[stable(feature = "symmetric_u32_duration_mul", since = "1.30.0")]
616 impl Mul<Duration> for u32 {
617 type Output = Duration;
619 fn mul(self, rhs: Duration) -> Duration {
624 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
625 impl MulAssign<u32> for Duration {
626 fn mul_assign(&mut self, rhs: u32) {
631 #[stable(feature = "duration", since = "1.3.0")]
632 impl Div<u32> for Duration {
633 type Output = Duration;
635 fn div(self, rhs: u32) -> Duration {
636 self.checked_div(rhs).expect("divide by zero error when dividing duration by scalar")
640 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
641 impl DivAssign<u32> for Duration {
642 fn div_assign(&mut self, rhs: u32) {
647 macro_rules! sum_durations {
649 let mut total_secs: u64 = 0;
650 let mut total_nanos: u64 = 0;
653 total_secs = total_secs
654 .checked_add(entry.secs)
655 .expect("overflow in iter::sum over durations");
656 total_nanos = match total_nanos.checked_add(entry.nanos as u64) {
659 total_secs = total_secs
660 .checked_add(total_nanos / NANOS_PER_SEC as u64)
661 .expect("overflow in iter::sum over durations");
662 (total_nanos % NANOS_PER_SEC as u64) + entry.nanos as u64
666 total_secs = total_secs
667 .checked_add(total_nanos / NANOS_PER_SEC as u64)
668 .expect("overflow in iter::sum over durations");
669 total_nanos = total_nanos % NANOS_PER_SEC as u64;
672 nanos: total_nanos as u32,
677 #[stable(feature = "duration_sum", since = "1.16.0")]
678 impl Sum for Duration {
679 fn sum<I: Iterator<Item=Duration>>(iter: I) -> Duration {
684 #[stable(feature = "duration_sum", since = "1.16.0")]
685 impl<'a> Sum<&'a Duration> for Duration {
686 fn sum<I: Iterator<Item=&'a Duration>>(iter: I) -> Duration {
691 #[stable(feature = "duration_debug_impl", since = "1.27.0")]
692 impl fmt::Debug for Duration {
693 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
694 /// Formats a floating point number in decimal notation.
696 /// The number is given as the `integer_part` and a fractional part.
697 /// The value of the fractional part is `fractional_part / divisor`. So
698 /// `integer_part` = 3, `fractional_part` = 12 and `divisor` = 100
699 /// represents the number `3.012`. Trailing zeros are omitted.
701 /// `divisor` must not be above 100_000_000. It also should be a power
702 /// of 10, everything else doesn't make sense. `fractional_part` has
703 /// to be less than `10 * divisor`!
705 f: &mut fmt::Formatter,
706 mut integer_part: u64,
707 mut fractional_part: u32,
710 // Encode the fractional part into a temporary buffer. The buffer
711 // only need to hold 9 elements, because `fractional_part` has to
712 // be smaller than 10^9. The buffer is prefilled with '0' digits
713 // to simplify the code below.
714 let mut buf = [b'0'; 9];
716 // The next digit is written at this position
719 // We keep writing digits into the buffer while there are non-zero
720 // digits left and we haven't written enough digits yet.
721 while fractional_part > 0 && pos < f.precision().unwrap_or(9) {
722 // Write new digit into the buffer
723 buf[pos] = b'0' + (fractional_part / divisor) as u8;
725 fractional_part %= divisor;
730 // If a precision < 9 was specified, there may be some non-zero
731 // digits left that weren't written into the buffer. In that case we
732 // need to perform rounding to match the semantics of printing
733 // normal floating point numbers. However, we only need to do work
734 // when rounding up. This happens if the first digit of the
735 // remaining ones is >= 5.
736 if fractional_part > 0 && fractional_part >= divisor * 5 {
737 // Round up the number contained in the buffer. We go through
738 // the buffer backwards and keep track of the carry.
739 let mut rev_pos = pos;
740 let mut carry = true;
741 while carry && rev_pos > 0 {
744 // If the digit in the buffer is not '9', we just need to
745 // increment it and can stop then (since we don't have a
746 // carry anymore). Otherwise, we set it to '0' (overflow)
748 if buf[rev_pos] < b'9' {
756 // If we still have the carry bit set, that means that we set
757 // the whole buffer to '0's and need to increment the integer
764 // Determine the end of the buffer: if precision is set, we just
765 // use as many digits from the buffer (capped to 9). If it isn't
766 // set, we only use all digits up to the last non-zero one.
767 let end = f.precision().map(|p| ::cmp::min(p, 9)).unwrap_or(pos);
769 // If we haven't emitted a single fractional digit and the precision
770 // wasn't set to a non-zero value, we don't print the decimal point.
772 write!(f, "{}", integer_part)
774 // We are only writing ASCII digits into the buffer and it was
775 // initialized with '0's, so it contains valid UTF8.
777 ::str::from_utf8_unchecked(&buf[..end])
780 // If the user request a precision > 9, we pad '0's at the end.
781 let w = f.precision().unwrap_or(pos);
782 write!(f, "{}.{:0<width$}", integer_part, s, width = w)
786 // Print leading '+' sign if requested
792 fmt_decimal(f, self.secs, self.nanos, 100_000_000)?;
794 } else if self.nanos >= 1_000_000 {
795 fmt_decimal(f, self.nanos as u64 / 1_000_000, self.nanos % 1_000_000, 100_000)?;
797 } else if self.nanos >= 1_000 {
798 fmt_decimal(f, self.nanos as u64 / 1_000, self.nanos % 1_000, 100)?;
801 fmt_decimal(f, self.nanos as u64, 0, 1)?;