]> git.lizzy.rs Git - rust.git/blob - src/libstd/time/duration.rs
Optimized error reporting for recursive requirements #47720
[rust.git] / src / libstd / time / duration.rs
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.
4 //
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
11 use iter::Sum;
12 use ops::{Add, Sub, Mul, Div, AddAssign, SubAssign, MulAssign, DivAssign};
13
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;
19
20 /// A `Duration` type to represent a span of time, typically used for system
21 /// timeouts.
22 ///
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.
27 ///
28 /// `Duration`s implement many common traits, including [`Add`], [`Sub`], and other
29 /// [`ops`] traits.
30 ///
31 /// [`Add`]: ../../std/ops/trait.Add.html
32 /// [`Sub`]: ../../std/ops/trait.Sub.html
33 /// [`ops`]: ../../std/ops/index.html
34 ///
35 /// # Examples
36 ///
37 /// ```
38 /// use std::time::Duration;
39 ///
40 /// let five_seconds = Duration::new(5, 0);
41 /// let five_seconds_and_five_nanos = five_seconds + Duration::new(0, 5);
42 ///
43 /// assert_eq!(five_seconds_and_five_nanos.as_secs(), 5);
44 /// assert_eq!(five_seconds_and_five_nanos.subsec_nanos(), 5);
45 ///
46 /// let ten_millis = Duration::from_millis(10);
47 /// ```
48 #[stable(feature = "duration", since = "1.3.0")]
49 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash, Default)]
50 pub struct Duration {
51     secs: u64,
52     nanos: u32, // Always 0 <= nanos < NANOS_PER_SEC
53 }
54
55 impl Duration {
56     /// Creates a new `Duration` from the specified number of whole seconds and
57     /// additional nanoseconds.
58     ///
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.
61     ///
62     /// # Panics
63     ///
64     /// This constructor will panic if the carry from the nanoseconds overflows
65     /// the seconds counter.
66     ///
67     /// # Examples
68     ///
69     /// ```
70     /// use std::time::Duration;
71     ///
72     /// let five_seconds = Duration::new(5, 0);
73     /// ```
74     #[stable(feature = "duration", since = "1.3.0")]
75     #[inline]
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 }
81     }
82
83     /// Creates a new `Duration` from the specified number of whole seconds.
84     ///
85     /// # Examples
86     ///
87     /// ```
88     /// use std::time::Duration;
89     ///
90     /// let duration = Duration::from_secs(5);
91     ///
92     /// assert_eq!(5, duration.as_secs());
93     /// assert_eq!(0, duration.subsec_nanos());
94     /// ```
95     #[stable(feature = "duration", since = "1.3.0")]
96     #[inline]
97     pub const fn from_secs(secs: u64) -> Duration {
98         Duration { secs: secs, nanos: 0 }
99     }
100
101     /// Creates a new `Duration` from the specified number of milliseconds.
102     ///
103     /// # Examples
104     ///
105     /// ```
106     /// use std::time::Duration;
107     ///
108     /// let duration = Duration::from_millis(2569);
109     ///
110     /// assert_eq!(2, duration.as_secs());
111     /// assert_eq!(569_000_000, duration.subsec_nanos());
112     /// ```
113     #[stable(feature = "duration", since = "1.3.0")]
114     #[inline]
115     pub const fn from_millis(millis: u64) -> Duration {
116         Duration {
117             secs: millis / MILLIS_PER_SEC,
118             nanos: ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI,
119         }
120     }
121
122     /// Creates a new `Duration` from the specified number of microseconds.
123     ///
124     /// # Examples
125     ///
126     /// ```
127     /// #![feature(duration_from_micros)]
128     /// use std::time::Duration;
129     ///
130     /// let duration = Duration::from_micros(1_000_002);
131     ///
132     /// assert_eq!(1, duration.as_secs());
133     /// assert_eq!(2000, duration.subsec_nanos());
134     /// ```
135     #[unstable(feature = "duration_from_micros", issue = "44400")]
136     #[inline]
137     pub const fn from_micros(micros: u64) -> Duration {
138         Duration {
139             secs: micros / MICROS_PER_SEC,
140             nanos: ((micros % MICROS_PER_SEC) as u32) * NANOS_PER_MICRO,
141         }
142     }
143
144     /// Creates a new `Duration` from the specified number of nanoseconds.
145     ///
146     /// # Examples
147     ///
148     /// ```
149     /// #![feature(duration_extras)]
150     /// use std::time::Duration;
151     ///
152     /// let duration = Duration::from_nanos(1_000_000_123);
153     ///
154     /// assert_eq!(1, duration.as_secs());
155     /// assert_eq!(123, duration.subsec_nanos());
156     /// ```
157     #[unstable(feature = "duration_extras", issue = "46507")]
158     #[inline]
159     pub const fn from_nanos(nanos: u64) -> Duration {
160         Duration {
161             secs: nanos / (NANOS_PER_SEC as u64),
162             nanos: (nanos % (NANOS_PER_SEC as u64)) as u32,
163         }
164     }
165
166     /// Returns the number of _whole_ seconds contained by this `Duration`.
167     ///
168     /// The returned value does not include the fractional (nanosecond) part of the
169     /// duration, which can be obtained using [`subsec_nanos`].
170     ///
171     /// # Examples
172     ///
173     /// ```
174     /// use std::time::Duration;
175     ///
176     /// let duration = Duration::new(5, 730023852);
177     /// assert_eq!(duration.as_secs(), 5);
178     /// ```
179     ///
180     /// To determine the total number of seconds represented by the `Duration`,
181     /// use `as_secs` in combination with [`subsec_nanos`]:
182     ///
183     /// ```
184     /// use std::time::Duration;
185     ///
186     /// let duration = Duration::new(5, 730023852);
187     ///
188     /// assert_eq!(5.730023852,
189     ///            duration.as_secs() as f64
190     ///            + duration.subsec_nanos() as f64 * 1e-9);
191     /// ```
192     ///
193     /// [`subsec_nanos`]: #method.subsec_nanos
194     #[stable(feature = "duration", since = "1.3.0")]
195     #[inline]
196     pub fn as_secs(&self) -> u64 { self.secs }
197
198     /// Returns the fractional part of this `Duration`, in milliseconds.
199     ///
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).
203     ///
204     /// # Examples
205     ///
206     /// ```
207     /// #![feature(duration_extras)]
208     /// use std::time::Duration;
209     ///
210     /// let duration = Duration::from_millis(5432);
211     /// assert_eq!(duration.as_secs(), 5);
212     /// assert_eq!(duration.subsec_millis(), 432);
213     /// ```
214     #[unstable(feature = "duration_extras", issue = "46507")]
215     #[inline]
216     pub fn subsec_millis(&self) -> u32 { self.nanos / NANOS_PER_MILLI }
217
218     /// Returns the fractional part of this `Duration`, in microseconds.
219     ///
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).
223     ///
224     /// # Examples
225     ///
226     /// ```
227     /// #![feature(duration_extras, duration_from_micros)]
228     /// use std::time::Duration;
229     ///
230     /// let duration = Duration::from_micros(1_234_567);
231     /// assert_eq!(duration.as_secs(), 1);
232     /// assert_eq!(duration.subsec_micros(), 234_567);
233     /// ```
234     #[unstable(feature = "duration_extras", issue = "46507")]
235     #[inline]
236     pub fn subsec_micros(&self) -> u32 { self.nanos / NANOS_PER_MICRO }
237
238     /// Returns the fractional part of this `Duration`, in nanoseconds.
239     ///
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).
243     ///
244     /// # Examples
245     ///
246     /// ```
247     /// use std::time::Duration;
248     ///
249     /// let duration = Duration::from_millis(5010);
250     /// assert_eq!(duration.as_secs(), 5);
251     /// assert_eq!(duration.subsec_nanos(), 10_000_000);
252     /// ```
253     #[stable(feature = "duration", since = "1.3.0")]
254     #[inline]
255     pub fn subsec_nanos(&self) -> u32 { self.nanos }
256
257     /// Checked `Duration` addition. Computes `self + other`, returning [`None`]
258     /// if overflow occurred.
259     ///
260     /// [`None`]: ../../std/option/enum.Option.html#variant.None
261     ///
262     /// # Examples
263     ///
264     /// Basic usage:
265     ///
266     /// ```
267     /// use std::time::Duration;
268     ///
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);
271     /// ```
272     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
273     #[inline]
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) {
280                     secs = new_secs;
281                 } else {
282                     return None;
283                 }
284             }
285             debug_assert!(nanos < NANOS_PER_SEC);
286             Some(Duration {
287                 secs,
288                 nanos,
289             })
290         } else {
291             None
292         }
293     }
294
295     /// Checked `Duration` subtraction. Computes `self - other`, returning [`None`]
296     /// if the result would be negative or if overflow occurred.
297     ///
298     /// [`None`]: ../../std/option/enum.Option.html#variant.None
299     ///
300     /// # Examples
301     ///
302     /// Basic usage:
303     ///
304     /// ```
305     /// use std::time::Duration;
306     ///
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);
309     /// ```
310     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
311     #[inline]
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
316             } else {
317                 if let Some(sub_secs) = secs.checked_sub(1) {
318                     secs = sub_secs;
319                     self.nanos + NANOS_PER_SEC - rhs.nanos
320                 } else {
321                     return None;
322                 }
323             };
324             debug_assert!(nanos < NANOS_PER_SEC);
325             Some(Duration { secs: secs, nanos: nanos })
326         } else {
327             None
328         }
329     }
330
331     /// Checked `Duration` multiplication. Computes `self * other`, returning
332     /// [`None`] if overflow occurred.
333     ///
334     /// [`None`]: ../../std/option/enum.Option.html#variant.None
335     ///
336     /// # Examples
337     ///
338     /// Basic usage:
339     ///
340     /// ```
341     /// use std::time::Duration;
342     ///
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);
345     /// ```
346     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
347     #[inline]
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);
357             Some(Duration {
358                 secs,
359                 nanos,
360             })
361         } else {
362             None
363         }
364     }
365
366     /// Checked `Duration` division. Computes `self / other`, returning [`None`]
367     /// if `other == 0`.
368     ///
369     /// [`None`]: ../../std/option/enum.Option.html#variant.None
370     ///
371     /// # Examples
372     ///
373     /// Basic usage:
374     ///
375     /// ```
376     /// use std::time::Duration;
377     ///
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);
381     /// ```
382     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
383     #[inline]
384     pub fn checked_div(self, rhs: u32) -> Option<Duration> {
385         if rhs != 0 {
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 })
392         } else {
393             None
394         }
395     }
396 }
397
398 #[stable(feature = "duration", since = "1.3.0")]
399 impl Add for Duration {
400     type Output = Duration;
401
402     fn add(self, rhs: Duration) -> Duration {
403         self.checked_add(rhs).expect("overflow when adding durations")
404     }
405 }
406
407 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
408 impl AddAssign for Duration {
409     fn add_assign(&mut self, rhs: Duration) {
410         *self = *self + rhs;
411     }
412 }
413
414 #[stable(feature = "duration", since = "1.3.0")]
415 impl Sub for Duration {
416     type Output = Duration;
417
418     fn sub(self, rhs: Duration) -> Duration {
419         self.checked_sub(rhs).expect("overflow when subtracting durations")
420     }
421 }
422
423 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
424 impl SubAssign for Duration {
425     fn sub_assign(&mut self, rhs: Duration) {
426         *self = *self - rhs;
427     }
428 }
429
430 #[stable(feature = "duration", since = "1.3.0")]
431 impl Mul<u32> for Duration {
432     type Output = Duration;
433
434     fn mul(self, rhs: u32) -> Duration {
435         self.checked_mul(rhs).expect("overflow when multiplying duration by scalar")
436     }
437 }
438
439 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
440 impl MulAssign<u32> for Duration {
441     fn mul_assign(&mut self, rhs: u32) {
442         *self = *self * rhs;
443     }
444 }
445
446 #[stable(feature = "duration", since = "1.3.0")]
447 impl Div<u32> for Duration {
448     type Output = Duration;
449
450     fn div(self, rhs: u32) -> Duration {
451         self.checked_div(rhs).expect("divide by zero error when dividing duration by scalar")
452     }
453 }
454
455 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
456 impl DivAssign<u32> for Duration {
457     fn div_assign(&mut self, rhs: u32) {
458         *self = *self / rhs;
459     }
460 }
461
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)
466     }
467 }
468
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)
473     }
474 }
475
476 #[cfg(test)]
477 mod tests {
478     use super::Duration;
479
480     #[test]
481     fn creation() {
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));
488     }
489
490     #[test]
491     fn secs() {
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);
496     }
497
498     #[test]
499     fn nanos() {
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);
506     }
507
508     #[test]
509     fn add() {
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));
514     }
515
516     #[test]
517     fn checked_add() {
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);
523     }
524
525     #[test]
526     fn sub() {
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));
533     }
534
535     #[test]
536     fn checked_sub() {
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);
545     }
546
547     #[test] #[should_panic]
548     fn sub_bad1() {
549         Duration::new(0, 0) - Duration::new(0, 1);
550     }
551
552     #[test] #[should_panic]
553     fn sub_bad2() {
554         Duration::new(0, 0) - Duration::new(1, 0);
555     }
556
557     #[test]
558     fn mul() {
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));
564     }
565
566     #[test]
567     fn checked_mul() {
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);
574     }
575
576     #[test]
577     fn div() {
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));
582     }
583
584     #[test]
585     fn checked_div() {
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);
589     }
590 }