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.
12 use ops::{Add, Sub, Mul, Div, AddAssign, SubAssign, MulAssign, DivAssign};
14 const NANOS_PER_SEC: u32 = 1_000_000_000;
15 const NANOS_PER_MILLI: u32 = 1_000_000;
16 const NANOS_PER_MICRO: u32 = 1_000;
17 const MILLIS_PER_SEC: u64 = 1_000;
18 const MICROS_PER_SEC: u64 = 1_000_000;
20 /// A `Duration` type to represent a span of time, typically used for system
23 /// Each `Duration` is composed of a whole number of seconds and a fractional part
24 /// represented in nanoseconds. If the underlying system does not support
25 /// nanosecond-level precision, APIs binding a system timeout will typically round up
26 /// the number of nanoseconds.
28 /// `Duration`s implement many common traits, including [`Add`], [`Sub`], and other
31 /// [`Add`]: ../../std/ops/trait.Add.html
32 /// [`Sub`]: ../../std/ops/trait.Sub.html
33 /// [`ops`]: ../../std/ops/index.html
38 /// use std::time::Duration;
40 /// let five_seconds = Duration::new(5, 0);
41 /// let five_seconds_and_five_nanos = five_seconds + Duration::new(0, 5);
43 /// assert_eq!(five_seconds_and_five_nanos.as_secs(), 5);
44 /// assert_eq!(five_seconds_and_five_nanos.subsec_nanos(), 5);
46 /// let ten_millis = Duration::from_millis(10);
48 #[stable(feature = "duration", since = "1.3.0")]
49 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash, Default)]
52 nanos: u32, // Always 0 <= nanos < NANOS_PER_SEC
56 /// Creates a new `Duration` from the specified number of whole seconds and
57 /// additional nanoseconds.
59 /// If the number of nanoseconds is greater than 1 billion (the number of
60 /// nanoseconds in a second), then it will carry over into the seconds provided.
64 /// This constructor will panic if the carry from the nanoseconds overflows
65 /// the seconds counter.
70 /// use std::time::Duration;
72 /// let five_seconds = Duration::new(5, 0);
74 #[stable(feature = "duration", since = "1.3.0")]
76 pub fn new(secs: u64, nanos: u32) -> Duration {
77 let secs = secs.checked_add((nanos / NANOS_PER_SEC) as u64)
78 .expect("overflow in Duration::new");
79 let nanos = nanos % NANOS_PER_SEC;
80 Duration { secs: secs, nanos: nanos }
83 /// Creates a new `Duration` from the specified number of whole seconds.
88 /// use std::time::Duration;
90 /// let duration = Duration::from_secs(5);
92 /// assert_eq!(5, duration.as_secs());
93 /// assert_eq!(0, duration.subsec_nanos());
95 #[stable(feature = "duration", since = "1.3.0")]
97 pub const fn from_secs(secs: u64) -> Duration {
98 Duration { secs: secs, nanos: 0 }
101 /// Creates a new `Duration` from the specified number of milliseconds.
106 /// use std::time::Duration;
108 /// let duration = Duration::from_millis(2569);
110 /// assert_eq!(2, duration.as_secs());
111 /// assert_eq!(569_000_000, duration.subsec_nanos());
113 #[stable(feature = "duration", since = "1.3.0")]
115 pub const fn from_millis(millis: u64) -> Duration {
117 secs: millis / MILLIS_PER_SEC,
118 nanos: ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI,
122 /// Creates a new `Duration` from the specified number of microseconds.
127 /// #![feature(duration_from_micros)]
128 /// use std::time::Duration;
130 /// let duration = Duration::from_micros(1_000_002);
132 /// assert_eq!(1, duration.as_secs());
133 /// assert_eq!(2000, duration.subsec_nanos());
135 #[unstable(feature = "duration_from_micros", issue = "44400")]
137 pub const fn from_micros(micros: u64) -> Duration {
139 secs: micros / MICROS_PER_SEC,
140 nanos: ((micros % MICROS_PER_SEC) as u32) * NANOS_PER_MICRO,
144 /// Creates a new `Duration` from the specified number of nanoseconds.
149 /// #![feature(duration_extras)]
150 /// use std::time::Duration;
152 /// let duration = Duration::from_nanos(1_000_000_123);
154 /// assert_eq!(1, duration.as_secs());
155 /// assert_eq!(123, duration.subsec_nanos());
157 #[unstable(feature = "duration_extras", issue = "46507")]
159 pub const fn from_nanos(nanos: u64) -> Duration {
161 secs: nanos / (NANOS_PER_SEC as u64),
162 nanos: (nanos % (NANOS_PER_SEC as u64)) as u32,
166 /// Returns the number of _whole_ seconds contained by this `Duration`.
168 /// The returned value does not include the fractional (nanosecond) part of the
169 /// duration, which can be obtained using [`subsec_nanos`].
174 /// use std::time::Duration;
176 /// let duration = Duration::new(5, 730023852);
177 /// assert_eq!(duration.as_secs(), 5);
180 /// To determine the total number of seconds represented by the `Duration`,
181 /// use `as_secs` in combination with [`subsec_nanos`]:
184 /// use std::time::Duration;
186 /// let duration = Duration::new(5, 730023852);
188 /// assert_eq!(5.730023852,
189 /// duration.as_secs() as f64
190 /// + duration.subsec_nanos() as f64 * 1e-9);
193 /// [`subsec_nanos`]: #method.subsec_nanos
194 #[stable(feature = "duration", since = "1.3.0")]
196 pub fn as_secs(&self) -> u64 { self.secs }
198 /// Returns the fractional part of this `Duration`, in milliseconds.
200 /// This method does **not** return the length of the duration when
201 /// represented by milliseconds. The returned number always represents a
202 /// fractional portion of a second (i.e. it is less than one thousand).
207 /// #![feature(duration_extras)]
208 /// use std::time::Duration;
210 /// let duration = Duration::from_millis(5432);
211 /// assert_eq!(duration.as_secs(), 5);
212 /// assert_eq!(duration.subsec_millis(), 432);
214 #[unstable(feature = "duration_extras", issue = "46507")]
216 pub fn subsec_millis(&self) -> u32 { self.nanos / NANOS_PER_MILLI }
218 /// Returns the fractional part of this `Duration`, in microseconds.
220 /// This method does **not** return the length of the duration when
221 /// represented by microseconds. The returned number always represents a
222 /// fractional portion of a second (i.e. it is less than one million).
227 /// #![feature(duration_extras, duration_from_micros)]
228 /// use std::time::Duration;
230 /// let duration = Duration::from_micros(1_234_567);
231 /// assert_eq!(duration.as_secs(), 1);
232 /// assert_eq!(duration.subsec_micros(), 234_567);
234 #[unstable(feature = "duration_extras", issue = "46507")]
236 pub fn subsec_micros(&self) -> u32 { self.nanos / NANOS_PER_MICRO }
238 /// Returns the fractional part of this `Duration`, in nanoseconds.
240 /// This method does **not** return the length of the duration when
241 /// represented by nanoseconds. The returned number always represents a
242 /// fractional portion of a second (i.e. it is less than one billion).
247 /// use std::time::Duration;
249 /// let duration = Duration::from_millis(5010);
250 /// assert_eq!(duration.as_secs(), 5);
251 /// assert_eq!(duration.subsec_nanos(), 10_000_000);
253 #[stable(feature = "duration", since = "1.3.0")]
255 pub fn subsec_nanos(&self) -> u32 { self.nanos }
257 /// Checked `Duration` addition. Computes `self + other`, returning [`None`]
258 /// if overflow occurred.
260 /// [`None`]: ../../std/option/enum.Option.html#variant.None
267 /// use std::time::Duration;
269 /// assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1)));
270 /// assert_eq!(Duration::new(1, 0).checked_add(Duration::new(std::u64::MAX, 0)), None);
272 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
274 pub fn checked_add(self, rhs: Duration) -> Option<Duration> {
275 if let Some(mut secs) = self.secs.checked_add(rhs.secs) {
276 let mut nanos = self.nanos + rhs.nanos;
277 if nanos >= NANOS_PER_SEC {
278 nanos -= NANOS_PER_SEC;
279 if let Some(new_secs) = secs.checked_add(1) {
285 debug_assert!(nanos < NANOS_PER_SEC);
295 /// Checked `Duration` subtraction. Computes `self - other`, returning [`None`]
296 /// if the result would be negative or if overflow occurred.
298 /// [`None`]: ../../std/option/enum.Option.html#variant.None
305 /// use std::time::Duration;
307 /// assert_eq!(Duration::new(0, 1).checked_sub(Duration::new(0, 0)), Some(Duration::new(0, 1)));
308 /// assert_eq!(Duration::new(0, 0).checked_sub(Duration::new(0, 1)), None);
310 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
312 pub fn checked_sub(self, rhs: Duration) -> Option<Duration> {
313 if let Some(mut secs) = self.secs.checked_sub(rhs.secs) {
314 let nanos = if self.nanos >= rhs.nanos {
315 self.nanos - rhs.nanos
317 if let Some(sub_secs) = secs.checked_sub(1) {
319 self.nanos + NANOS_PER_SEC - rhs.nanos
324 debug_assert!(nanos < NANOS_PER_SEC);
325 Some(Duration { secs: secs, nanos: nanos })
331 /// Checked `Duration` multiplication. Computes `self * other`, returning
332 /// [`None`] if overflow occurred.
334 /// [`None`]: ../../std/option/enum.Option.html#variant.None
341 /// use std::time::Duration;
343 /// assert_eq!(Duration::new(0, 500_000_001).checked_mul(2), Some(Duration::new(1, 2)));
344 /// assert_eq!(Duration::new(std::u64::MAX - 1, 0).checked_mul(2), None);
346 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
348 pub fn checked_mul(self, rhs: u32) -> Option<Duration> {
349 // Multiply nanoseconds as u64, because it cannot overflow that way.
350 let total_nanos = self.nanos as u64 * rhs as u64;
351 let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
352 let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
353 if let Some(secs) = self.secs
354 .checked_mul(rhs as u64)
355 .and_then(|s| s.checked_add(extra_secs)) {
356 debug_assert!(nanos < NANOS_PER_SEC);
366 /// Checked `Duration` division. Computes `self / other`, returning [`None`]
369 /// [`None`]: ../../std/option/enum.Option.html#variant.None
376 /// use std::time::Duration;
378 /// assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0)));
379 /// assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000)));
380 /// assert_eq!(Duration::new(2, 0).checked_div(0), None);
382 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
384 pub fn checked_div(self, rhs: u32) -> Option<Duration> {
386 let secs = self.secs / (rhs as u64);
387 let carry = self.secs - secs * (rhs as u64);
388 let extra_nanos = carry * (NANOS_PER_SEC as u64) / (rhs as u64);
389 let nanos = self.nanos / rhs + (extra_nanos as u32);
390 debug_assert!(nanos < NANOS_PER_SEC);
391 Some(Duration { secs: secs, nanos: nanos })
398 #[stable(feature = "duration", since = "1.3.0")]
399 impl Add for Duration {
400 type Output = Duration;
402 fn add(self, rhs: Duration) -> Duration {
403 self.checked_add(rhs).expect("overflow when adding durations")
407 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
408 impl AddAssign for Duration {
409 fn add_assign(&mut self, rhs: Duration) {
414 #[stable(feature = "duration", since = "1.3.0")]
415 impl Sub for Duration {
416 type Output = Duration;
418 fn sub(self, rhs: Duration) -> Duration {
419 self.checked_sub(rhs).expect("overflow when subtracting durations")
423 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
424 impl SubAssign for Duration {
425 fn sub_assign(&mut self, rhs: Duration) {
430 #[stable(feature = "duration", since = "1.3.0")]
431 impl Mul<u32> for Duration {
432 type Output = Duration;
434 fn mul(self, rhs: u32) -> Duration {
435 self.checked_mul(rhs).expect("overflow when multiplying duration by scalar")
439 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
440 impl MulAssign<u32> for Duration {
441 fn mul_assign(&mut self, rhs: u32) {
446 #[stable(feature = "duration", since = "1.3.0")]
447 impl Div<u32> for Duration {
448 type Output = Duration;
450 fn div(self, rhs: u32) -> Duration {
451 self.checked_div(rhs).expect("divide by zero error when dividing duration by scalar")
455 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
456 impl DivAssign<u32> for Duration {
457 fn div_assign(&mut self, rhs: u32) {
462 #[stable(feature = "duration_sum", since = "1.16.0")]
463 impl Sum for Duration {
464 fn sum<I: Iterator<Item=Duration>>(iter: I) -> Duration {
465 iter.fold(Duration::new(0, 0), |a, b| a + b)
469 #[stable(feature = "duration_sum", since = "1.16.0")]
470 impl<'a> Sum<&'a Duration> for Duration {
471 fn sum<I: Iterator<Item=&'a Duration>>(iter: I) -> Duration {
472 iter.fold(Duration::new(0, 0), |a, b| a + *b)
482 assert!(Duration::from_secs(1) != Duration::from_secs(0));
483 assert_eq!(Duration::from_secs(1) + Duration::from_secs(2),
484 Duration::from_secs(3));
485 assert_eq!(Duration::from_millis(10) + Duration::from_secs(4),
486 Duration::new(4, 10 * 1_000_000));
487 assert_eq!(Duration::from_millis(4000), Duration::new(4, 0));
492 assert_eq!(Duration::new(0, 0).as_secs(), 0);
493 assert_eq!(Duration::from_secs(1).as_secs(), 1);
494 assert_eq!(Duration::from_millis(999).as_secs(), 0);
495 assert_eq!(Duration::from_millis(1001).as_secs(), 1);
500 assert_eq!(Duration::new(0, 0).subsec_nanos(), 0);
501 assert_eq!(Duration::new(0, 5).subsec_nanos(), 5);
502 assert_eq!(Duration::new(0, 1_000_000_001).subsec_nanos(), 1);
503 assert_eq!(Duration::from_secs(1).subsec_nanos(), 0);
504 assert_eq!(Duration::from_millis(999).subsec_nanos(), 999 * 1_000_000);
505 assert_eq!(Duration::from_millis(1001).subsec_nanos(), 1 * 1_000_000);
510 assert_eq!(Duration::new(0, 0) + Duration::new(0, 1),
511 Duration::new(0, 1));
512 assert_eq!(Duration::new(0, 500_000_000) + Duration::new(0, 500_000_001),
513 Duration::new(1, 1));
518 assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)),
519 Some(Duration::new(0, 1)));
520 assert_eq!(Duration::new(0, 500_000_000).checked_add(Duration::new(0, 500_000_001)),
521 Some(Duration::new(1, 1)));
522 assert_eq!(Duration::new(1, 0).checked_add(Duration::new(::u64::MAX, 0)), None);
527 assert_eq!(Duration::new(0, 1) - Duration::new(0, 0),
528 Duration::new(0, 1));
529 assert_eq!(Duration::new(0, 500_000_001) - Duration::new(0, 500_000_000),
530 Duration::new(0, 1));
531 assert_eq!(Duration::new(1, 0) - Duration::new(0, 1),
532 Duration::new(0, 999_999_999));
537 let zero = Duration::new(0, 0);
538 let one_nano = Duration::new(0, 1);
539 let one_sec = Duration::new(1, 0);
540 assert_eq!(one_nano.checked_sub(zero), Some(Duration::new(0, 1)));
541 assert_eq!(one_sec.checked_sub(one_nano),
542 Some(Duration::new(0, 999_999_999)));
543 assert_eq!(zero.checked_sub(one_nano), None);
544 assert_eq!(zero.checked_sub(one_sec), None);
547 #[test] #[should_panic]
549 Duration::new(0, 0) - Duration::new(0, 1);
552 #[test] #[should_panic]
554 Duration::new(0, 0) - Duration::new(1, 0);
559 assert_eq!(Duration::new(0, 1) * 2, Duration::new(0, 2));
560 assert_eq!(Duration::new(1, 1) * 3, Duration::new(3, 3));
561 assert_eq!(Duration::new(0, 500_000_001) * 4, Duration::new(2, 4));
562 assert_eq!(Duration::new(0, 500_000_001) * 4000,
563 Duration::new(2000, 4000));
568 assert_eq!(Duration::new(0, 1).checked_mul(2), Some(Duration::new(0, 2)));
569 assert_eq!(Duration::new(1, 1).checked_mul(3), Some(Duration::new(3, 3)));
570 assert_eq!(Duration::new(0, 500_000_001).checked_mul(4), Some(Duration::new(2, 4)));
571 assert_eq!(Duration::new(0, 500_000_001).checked_mul(4000),
572 Some(Duration::new(2000, 4000)));
573 assert_eq!(Duration::new(::u64::MAX - 1, 0).checked_mul(2), None);
578 assert_eq!(Duration::new(0, 1) / 2, Duration::new(0, 0));
579 assert_eq!(Duration::new(1, 1) / 3, Duration::new(0, 333_333_333));
580 assert_eq!(Duration::new(99, 999_999_000) / 100,
581 Duration::new(0, 999_999_990));
586 assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0)));
587 assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000)));
588 assert_eq!(Duration::new(2, 0).checked_div(0), None);