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));
25 use ops::{Add, Sub, Mul, Div, AddAssign, SubAssign, MulAssign, DivAssign};
27 const NANOS_PER_SEC: u32 = 1_000_000_000;
28 const NANOS_PER_MILLI: u32 = 1_000_000;
29 const NANOS_PER_MICRO: u32 = 1_000;
30 const MILLIS_PER_SEC: u64 = 1_000;
31 const MICROS_PER_SEC: u64 = 1_000_000;
33 /// A `Duration` type to represent a span of time, typically used for system
36 /// Each `Duration` is composed of a whole number of seconds and a fractional part
37 /// represented in nanoseconds. If the underlying system does not support
38 /// nanosecond-level precision, APIs binding a system timeout will typically round up
39 /// the number of nanoseconds.
41 /// `Duration`s implement many common traits, including [`Add`], [`Sub`], and other
44 /// [`Add`]: ../../std/ops/trait.Add.html
45 /// [`Sub`]: ../../std/ops/trait.Sub.html
46 /// [`ops`]: ../../std/ops/index.html
51 /// use std::time::Duration;
53 /// let five_seconds = Duration::new(5, 0);
54 /// let five_seconds_and_five_nanos = five_seconds + Duration::new(0, 5);
56 /// assert_eq!(five_seconds_and_five_nanos.as_secs(), 5);
57 /// assert_eq!(five_seconds_and_five_nanos.subsec_nanos(), 5);
59 /// let ten_millis = Duration::from_millis(10);
61 #[stable(feature = "duration", since = "1.3.0")]
62 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash, Default)]
65 nanos: u32, // Always 0 <= nanos < NANOS_PER_SEC
69 /// Creates a new `Duration` from the specified number of whole seconds and
70 /// additional nanoseconds.
72 /// If the number of nanoseconds is greater than 1 billion (the number of
73 /// nanoseconds in a second), then it will carry over into the seconds provided.
77 /// This constructor will panic if the carry from the nanoseconds overflows
78 /// the seconds counter.
83 /// use std::time::Duration;
85 /// let five_seconds = Duration::new(5, 0);
87 #[stable(feature = "duration", since = "1.3.0")]
89 pub fn new(secs: u64, nanos: u32) -> Duration {
90 let secs = secs.checked_add((nanos / NANOS_PER_SEC) as u64)
91 .expect("overflow in Duration::new");
92 let nanos = nanos % NANOS_PER_SEC;
93 Duration { secs: secs, nanos: nanos }
96 /// Creates a new `Duration` from the specified number of whole seconds.
101 /// use std::time::Duration;
103 /// let duration = Duration::from_secs(5);
105 /// assert_eq!(5, duration.as_secs());
106 /// assert_eq!(0, duration.subsec_nanos());
108 #[stable(feature = "duration", since = "1.3.0")]
110 pub const fn from_secs(secs: u64) -> Duration {
111 Duration { secs: secs, nanos: 0 }
114 /// Creates a new `Duration` from the specified number of milliseconds.
119 /// use std::time::Duration;
121 /// let duration = Duration::from_millis(2569);
123 /// assert_eq!(2, duration.as_secs());
124 /// assert_eq!(569_000_000, duration.subsec_nanos());
126 #[stable(feature = "duration", since = "1.3.0")]
128 pub const fn from_millis(millis: u64) -> Duration {
130 secs: millis / MILLIS_PER_SEC,
131 nanos: ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI,
135 /// Creates a new `Duration` from the specified number of microseconds.
140 /// use std::time::Duration;
142 /// let duration = Duration::from_micros(1_000_002);
144 /// assert_eq!(1, duration.as_secs());
145 /// assert_eq!(2000, duration.subsec_nanos());
147 #[stable(feature = "duration_from_micros", since = "1.27.0")]
149 pub const fn from_micros(micros: u64) -> Duration {
151 secs: micros / MICROS_PER_SEC,
152 nanos: ((micros % MICROS_PER_SEC) as u32) * NANOS_PER_MICRO,
156 /// Creates a new `Duration` from the specified number of nanoseconds.
161 /// use std::time::Duration;
163 /// let duration = Duration::from_nanos(1_000_000_123);
165 /// assert_eq!(1, duration.as_secs());
166 /// assert_eq!(123, duration.subsec_nanos());
168 #[stable(feature = "duration_extras", since = "1.27.0")]
170 pub const fn from_nanos(nanos: u64) -> Duration {
172 secs: nanos / (NANOS_PER_SEC as u64),
173 nanos: (nanos % (NANOS_PER_SEC as u64)) as u32,
177 /// Returns the number of _whole_ seconds contained by this `Duration`.
179 /// The returned value does not include the fractional (nanosecond) part of the
180 /// duration, which can be obtained using [`subsec_nanos`].
185 /// use std::time::Duration;
187 /// let duration = Duration::new(5, 730023852);
188 /// assert_eq!(duration.as_secs(), 5);
191 /// To determine the total number of seconds represented by the `Duration`,
192 /// use `as_secs` in combination with [`subsec_nanos`]:
195 /// use std::time::Duration;
197 /// let duration = Duration::new(5, 730023852);
199 /// assert_eq!(5.730023852,
200 /// duration.as_secs() as f64
201 /// + duration.subsec_nanos() as f64 * 1e-9);
204 /// [`subsec_nanos`]: #method.subsec_nanos
205 #[stable(feature = "duration", since = "1.3.0")]
207 pub fn as_secs(&self) -> u64 { self.secs }
209 /// Returns the fractional part of this `Duration`, in milliseconds.
211 /// This method does **not** return the length of the duration when
212 /// represented by milliseconds. The returned number always represents a
213 /// fractional portion of a second (i.e. it is less than one thousand).
218 /// use std::time::Duration;
220 /// let duration = Duration::from_millis(5432);
221 /// assert_eq!(duration.as_secs(), 5);
222 /// assert_eq!(duration.subsec_millis(), 432);
224 #[stable(feature = "duration_extras", since = "1.27.0")]
226 pub fn subsec_millis(&self) -> u32 { self.nanos / NANOS_PER_MILLI }
228 /// Returns the fractional part of this `Duration`, in microseconds.
230 /// This method does **not** return the length of the duration when
231 /// represented by microseconds. The returned number always represents a
232 /// fractional portion of a second (i.e. it is less than one million).
237 /// use std::time::Duration;
239 /// let duration = Duration::from_micros(1_234_567);
240 /// assert_eq!(duration.as_secs(), 1);
241 /// assert_eq!(duration.subsec_micros(), 234_567);
243 #[stable(feature = "duration_extras", since = "1.27.0")]
245 pub fn subsec_micros(&self) -> u32 { self.nanos / NANOS_PER_MICRO }
247 /// Returns the fractional part of this `Duration`, in nanoseconds.
249 /// This method does **not** return the length of the duration when
250 /// represented by nanoseconds. The returned number always represents a
251 /// fractional portion of a second (i.e. it is less than one billion).
256 /// use std::time::Duration;
258 /// let duration = Duration::from_millis(5010);
259 /// assert_eq!(duration.as_secs(), 5);
260 /// assert_eq!(duration.subsec_nanos(), 10_000_000);
262 #[stable(feature = "duration", since = "1.3.0")]
264 pub fn subsec_nanos(&self) -> u32 { self.nanos }
266 /// Returns the total number of nanoseconds contained by this `Duration`.
271 /// # #![feature(duration_nanos)]
272 /// use std::time::Duration;
274 /// let duration = Duration::new(5, 730023852);
275 /// assert_eq!(duration.as_nanos(), 5730023852);
277 #[unstable(feature = "duration_nanos", issue = "50202")]
279 pub fn as_nanos(&self) -> u128 {
280 self.secs as u128 * NANOS_PER_SEC as u128 + self.nanos as u128
283 /// Checked `Duration` addition. Computes `self + other`, returning [`None`]
284 /// if overflow occurred.
286 /// [`None`]: ../../std/option/enum.Option.html#variant.None
293 /// use std::time::Duration;
295 /// assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1)));
296 /// assert_eq!(Duration::new(1, 0).checked_add(Duration::new(std::u64::MAX, 0)), None);
298 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
300 pub fn checked_add(self, rhs: Duration) -> Option<Duration> {
301 if let Some(mut secs) = self.secs.checked_add(rhs.secs) {
302 let mut nanos = self.nanos + rhs.nanos;
303 if nanos >= NANOS_PER_SEC {
304 nanos -= NANOS_PER_SEC;
305 if let Some(new_secs) = secs.checked_add(1) {
311 debug_assert!(nanos < NANOS_PER_SEC);
321 /// Checked `Duration` subtraction. Computes `self - other`, returning [`None`]
322 /// if the result would be negative or if overflow occurred.
324 /// [`None`]: ../../std/option/enum.Option.html#variant.None
331 /// use std::time::Duration;
333 /// assert_eq!(Duration::new(0, 1).checked_sub(Duration::new(0, 0)), Some(Duration::new(0, 1)));
334 /// assert_eq!(Duration::new(0, 0).checked_sub(Duration::new(0, 1)), None);
336 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
338 pub fn checked_sub(self, rhs: Duration) -> Option<Duration> {
339 if let Some(mut secs) = self.secs.checked_sub(rhs.secs) {
340 let nanos = if self.nanos >= rhs.nanos {
341 self.nanos - rhs.nanos
343 if let Some(sub_secs) = secs.checked_sub(1) {
345 self.nanos + NANOS_PER_SEC - rhs.nanos
350 debug_assert!(nanos < NANOS_PER_SEC);
351 Some(Duration { secs: secs, nanos: nanos })
357 /// Checked `Duration` multiplication. Computes `self * other`, returning
358 /// [`None`] if overflow occurred.
360 /// [`None`]: ../../std/option/enum.Option.html#variant.None
367 /// use std::time::Duration;
369 /// assert_eq!(Duration::new(0, 500_000_001).checked_mul(2), Some(Duration::new(1, 2)));
370 /// assert_eq!(Duration::new(std::u64::MAX - 1, 0).checked_mul(2), None);
372 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
374 pub fn checked_mul(self, rhs: u32) -> Option<Duration> {
375 // Multiply nanoseconds as u64, because it cannot overflow that way.
376 let total_nanos = self.nanos as u64 * rhs as u64;
377 let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
378 let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
379 if let Some(secs) = self.secs
380 .checked_mul(rhs as u64)
381 .and_then(|s| s.checked_add(extra_secs)) {
382 debug_assert!(nanos < NANOS_PER_SEC);
392 /// Checked `Duration` division. Computes `self / other`, returning [`None`]
395 /// [`None`]: ../../std/option/enum.Option.html#variant.None
402 /// use std::time::Duration;
404 /// assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0)));
405 /// assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000)));
406 /// assert_eq!(Duration::new(2, 0).checked_div(0), None);
408 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
410 pub fn checked_div(self, rhs: u32) -> Option<Duration> {
412 let secs = self.secs / (rhs as u64);
413 let carry = self.secs - secs * (rhs as u64);
414 let extra_nanos = carry * (NANOS_PER_SEC as u64) / (rhs as u64);
415 let nanos = self.nanos / rhs + (extra_nanos as u32);
416 debug_assert!(nanos < NANOS_PER_SEC);
417 Some(Duration { secs: secs, nanos: nanos })
424 #[stable(feature = "duration", since = "1.3.0")]
425 impl Add for Duration {
426 type Output = Duration;
428 fn add(self, rhs: Duration) -> Duration {
429 self.checked_add(rhs).expect("overflow when adding durations")
433 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
434 impl AddAssign for Duration {
435 fn add_assign(&mut self, rhs: Duration) {
440 #[stable(feature = "duration", since = "1.3.0")]
441 impl Sub for Duration {
442 type Output = Duration;
444 fn sub(self, rhs: Duration) -> Duration {
445 self.checked_sub(rhs).expect("overflow when subtracting durations")
449 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
450 impl SubAssign for Duration {
451 fn sub_assign(&mut self, rhs: Duration) {
456 #[stable(feature = "duration", since = "1.3.0")]
457 impl Mul<u32> for Duration {
458 type Output = Duration;
460 fn mul(self, rhs: u32) -> Duration {
461 self.checked_mul(rhs).expect("overflow when multiplying duration by scalar")
465 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
466 impl MulAssign<u32> for Duration {
467 fn mul_assign(&mut self, rhs: u32) {
472 #[stable(feature = "duration", since = "1.3.0")]
473 impl Div<u32> for Duration {
474 type Output = Duration;
476 fn div(self, rhs: u32) -> Duration {
477 self.checked_div(rhs).expect("divide by zero error when dividing duration by scalar")
481 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
482 impl DivAssign<u32> for Duration {
483 fn div_assign(&mut self, rhs: u32) {
488 #[stable(feature = "duration_sum", since = "1.16.0")]
489 impl Sum for Duration {
490 fn sum<I: Iterator<Item=Duration>>(iter: I) -> Duration {
491 iter.fold(Duration::new(0, 0), |a, b| a + b)
495 #[stable(feature = "duration_sum", since = "1.16.0")]
496 impl<'a> Sum<&'a Duration> for Duration {
497 fn sum<I: Iterator<Item=&'a Duration>>(iter: I) -> Duration {
498 iter.fold(Duration::new(0, 0), |a, b| a + *b)
508 assert!(Duration::from_secs(1) != Duration::from_secs(0));
509 assert_eq!(Duration::from_secs(1) + Duration::from_secs(2),
510 Duration::from_secs(3));
511 assert_eq!(Duration::from_millis(10) + Duration::from_secs(4),
512 Duration::new(4, 10 * 1_000_000));
513 assert_eq!(Duration::from_millis(4000), Duration::new(4, 0));
518 assert_eq!(Duration::new(0, 0).as_secs(), 0);
519 assert_eq!(Duration::from_secs(1).as_secs(), 1);
520 assert_eq!(Duration::from_millis(999).as_secs(), 0);
521 assert_eq!(Duration::from_millis(1001).as_secs(), 1);
526 assert_eq!(Duration::new(0, 0).subsec_nanos(), 0);
527 assert_eq!(Duration::new(0, 5).subsec_nanos(), 5);
528 assert_eq!(Duration::new(0, 1_000_000_001).subsec_nanos(), 1);
529 assert_eq!(Duration::from_secs(1).subsec_nanos(), 0);
530 assert_eq!(Duration::from_millis(999).subsec_nanos(), 999 * 1_000_000);
531 assert_eq!(Duration::from_millis(1001).subsec_nanos(), 1 * 1_000_000);
536 assert_eq!(Duration::new(0, 0) + Duration::new(0, 1),
537 Duration::new(0, 1));
538 assert_eq!(Duration::new(0, 500_000_000) + Duration::new(0, 500_000_001),
539 Duration::new(1, 1));
544 assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)),
545 Some(Duration::new(0, 1)));
546 assert_eq!(Duration::new(0, 500_000_000).checked_add(Duration::new(0, 500_000_001)),
547 Some(Duration::new(1, 1)));
548 assert_eq!(Duration::new(1, 0).checked_add(Duration::new(::u64::MAX, 0)), None);
553 assert_eq!(Duration::new(0, 1) - Duration::new(0, 0),
554 Duration::new(0, 1));
555 assert_eq!(Duration::new(0, 500_000_001) - Duration::new(0, 500_000_000),
556 Duration::new(0, 1));
557 assert_eq!(Duration::new(1, 0) - Duration::new(0, 1),
558 Duration::new(0, 999_999_999));
563 let zero = Duration::new(0, 0);
564 let one_nano = Duration::new(0, 1);
565 let one_sec = Duration::new(1, 0);
566 assert_eq!(one_nano.checked_sub(zero), Some(Duration::new(0, 1)));
567 assert_eq!(one_sec.checked_sub(one_nano),
568 Some(Duration::new(0, 999_999_999)));
569 assert_eq!(zero.checked_sub(one_nano), None);
570 assert_eq!(zero.checked_sub(one_sec), None);
573 #[test] #[should_panic]
575 Duration::new(0, 0) - Duration::new(0, 1);
578 #[test] #[should_panic]
580 Duration::new(0, 0) - Duration::new(1, 0);
585 assert_eq!(Duration::new(0, 1) * 2, Duration::new(0, 2));
586 assert_eq!(Duration::new(1, 1) * 3, Duration::new(3, 3));
587 assert_eq!(Duration::new(0, 500_000_001) * 4, Duration::new(2, 4));
588 assert_eq!(Duration::new(0, 500_000_001) * 4000,
589 Duration::new(2000, 4000));
594 assert_eq!(Duration::new(0, 1).checked_mul(2), Some(Duration::new(0, 2)));
595 assert_eq!(Duration::new(1, 1).checked_mul(3), Some(Duration::new(3, 3)));
596 assert_eq!(Duration::new(0, 500_000_001).checked_mul(4), Some(Duration::new(2, 4)));
597 assert_eq!(Duration::new(0, 500_000_001).checked_mul(4000),
598 Some(Duration::new(2000, 4000)));
599 assert_eq!(Duration::new(::u64::MAX - 1, 0).checked_mul(2), None);
604 assert_eq!(Duration::new(0, 1) / 2, Duration::new(0, 0));
605 assert_eq!(Duration::new(1, 1) / 3, Duration::new(0, 333_333_333));
606 assert_eq!(Duration::new(99, 999_999_000) / 100,
607 Duration::new(0, 999_999_990));
612 assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0)));
613 assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000)));
614 assert_eq!(Duration::new(2, 0).checked_div(0), None);