]> git.lizzy.rs Git - rust.git/blob - src/libcore/time.rs
Auto merge of #47203 - varkor:output-filename-conflicts-with-directory, r=estebank
[rust.git] / src / libcore / time.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 #![stable(feature = "duration_core", since = "1.24.0")]
11
12 //! Temporal quantification.
13 //!
14 //! Example:
15 //!
16 //! ```
17 //! use std::time::Duration;
18 //!
19 //! let five_seconds = Duration::new(5, 0);
20 //! // both declarations are equivalent
21 //! assert_eq!(Duration::new(5, 0), Duration::from_secs(5));
22 //! ```
23
24 use iter::Sum;
25 use ops::{Add, Sub, Mul, Div, AddAssign, SubAssign, MulAssign, DivAssign};
26
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;
32
33 /// A `Duration` type to represent a span of time, typically used for system
34 /// timeouts.
35 ///
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.
40 ///
41 /// `Duration`s implement many common traits, including [`Add`], [`Sub`], and other
42 /// [`ops`] traits.
43 ///
44 /// [`Add`]: ../../std/ops/trait.Add.html
45 /// [`Sub`]: ../../std/ops/trait.Sub.html
46 /// [`ops`]: ../../std/ops/index.html
47 ///
48 /// # Examples
49 ///
50 /// ```
51 /// use std::time::Duration;
52 ///
53 /// let five_seconds = Duration::new(5, 0);
54 /// let five_seconds_and_five_nanos = five_seconds + Duration::new(0, 5);
55 ///
56 /// assert_eq!(five_seconds_and_five_nanos.as_secs(), 5);
57 /// assert_eq!(five_seconds_and_five_nanos.subsec_nanos(), 5);
58 ///
59 /// let ten_millis = Duration::from_millis(10);
60 /// ```
61 #[stable(feature = "duration_core", since = "1.24.0")]
62 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash, Default)]
63 pub struct Duration {
64     secs: u64,
65     nanos: u32, // Always 0 <= nanos < NANOS_PER_SEC
66 }
67
68 impl Duration {
69     /// Creates a new `Duration` from the specified number of whole seconds and
70     /// additional nanoseconds.
71     ///
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.
74     ///
75     /// # Panics
76     ///
77     /// This constructor will panic if the carry from the nanoseconds overflows
78     /// the seconds counter.
79     ///
80     /// # Examples
81     ///
82     /// ```
83     /// use std::time::Duration;
84     ///
85     /// let five_seconds = Duration::new(5, 0);
86     /// ```
87     #[stable(feature = "duration", since = "1.3.0")]
88     #[inline]
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 }
94     }
95
96     /// Creates a new `Duration` from the specified number of whole seconds.
97     ///
98     /// # Examples
99     ///
100     /// ```
101     /// use std::time::Duration;
102     ///
103     /// let duration = Duration::from_secs(5);
104     ///
105     /// assert_eq!(5, duration.as_secs());
106     /// assert_eq!(0, duration.subsec_nanos());
107     /// ```
108     #[stable(feature = "duration", since = "1.3.0")]
109     #[inline]
110     pub const fn from_secs(secs: u64) -> Duration {
111         Duration { secs: secs, nanos: 0 }
112     }
113
114     /// Creates a new `Duration` from the specified number of milliseconds.
115     ///
116     /// # Examples
117     ///
118     /// ```
119     /// use std::time::Duration;
120     ///
121     /// let duration = Duration::from_millis(2569);
122     ///
123     /// assert_eq!(2, duration.as_secs());
124     /// assert_eq!(569_000_000, duration.subsec_nanos());
125     /// ```
126     #[stable(feature = "duration", since = "1.3.0")]
127     #[inline]
128     pub const fn from_millis(millis: u64) -> Duration {
129         Duration {
130             secs: millis / MILLIS_PER_SEC,
131             nanos: ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI,
132         }
133     }
134
135     /// Creates a new `Duration` from the specified number of microseconds.
136     ///
137     /// # Examples
138     ///
139     /// ```
140     /// #![feature(duration_from_micros)]
141     /// use std::time::Duration;
142     ///
143     /// let duration = Duration::from_micros(1_000_002);
144     ///
145     /// assert_eq!(1, duration.as_secs());
146     /// assert_eq!(2000, duration.subsec_nanos());
147     /// ```
148     #[unstable(feature = "duration_from_micros", issue = "44400")]
149     #[inline]
150     pub const fn from_micros(micros: u64) -> Duration {
151         Duration {
152             secs: micros / MICROS_PER_SEC,
153             nanos: ((micros % MICROS_PER_SEC) as u32) * NANOS_PER_MICRO,
154         }
155     }
156
157     /// Creates a new `Duration` from the specified number of nanoseconds.
158     ///
159     /// # Examples
160     ///
161     /// ```
162     /// #![feature(duration_extras)]
163     /// use std::time::Duration;
164     ///
165     /// let duration = Duration::from_nanos(1_000_000_123);
166     ///
167     /// assert_eq!(1, duration.as_secs());
168     /// assert_eq!(123, duration.subsec_nanos());
169     /// ```
170     #[unstable(feature = "duration_extras", issue = "46507")]
171     #[inline]
172     pub const fn from_nanos(nanos: u64) -> Duration {
173         Duration {
174             secs: nanos / (NANOS_PER_SEC as u64),
175             nanos: (nanos % (NANOS_PER_SEC as u64)) as u32,
176         }
177     }
178
179     /// Returns the number of _whole_ seconds contained by this `Duration`.
180     ///
181     /// The returned value does not include the fractional (nanosecond) part of the
182     /// duration, which can be obtained using [`subsec_nanos`].
183     ///
184     /// # Examples
185     ///
186     /// ```
187     /// use std::time::Duration;
188     ///
189     /// let duration = Duration::new(5, 730023852);
190     /// assert_eq!(duration.as_secs(), 5);
191     /// ```
192     ///
193     /// To determine the total number of seconds represented by the `Duration`,
194     /// use `as_secs` in combination with [`subsec_nanos`]:
195     ///
196     /// ```
197     /// use std::time::Duration;
198     ///
199     /// let duration = Duration::new(5, 730023852);
200     ///
201     /// assert_eq!(5.730023852,
202     ///            duration.as_secs() as f64
203     ///            + duration.subsec_nanos() as f64 * 1e-9);
204     /// ```
205     ///
206     /// [`subsec_nanos`]: #method.subsec_nanos
207     #[stable(feature = "duration", since = "1.3.0")]
208     #[inline]
209     pub fn as_secs(&self) -> u64 { self.secs }
210
211     /// Returns the fractional part of this `Duration`, in milliseconds.
212     ///
213     /// This method does **not** return the length of the duration when
214     /// represented by milliseconds. The returned number always represents a
215     /// fractional portion of a second (i.e. it is less than one thousand).
216     ///
217     /// # Examples
218     ///
219     /// ```
220     /// #![feature(duration_extras)]
221     /// use std::time::Duration;
222     ///
223     /// let duration = Duration::from_millis(5432);
224     /// assert_eq!(duration.as_secs(), 5);
225     /// assert_eq!(duration.subsec_millis(), 432);
226     /// ```
227     #[unstable(feature = "duration_extras", issue = "46507")]
228     #[inline]
229     pub fn subsec_millis(&self) -> u32 { self.nanos / NANOS_PER_MILLI }
230
231     /// Returns the fractional part of this `Duration`, in microseconds.
232     ///
233     /// This method does **not** return the length of the duration when
234     /// represented by microseconds. The returned number always represents a
235     /// fractional portion of a second (i.e. it is less than one million).
236     ///
237     /// # Examples
238     ///
239     /// ```
240     /// #![feature(duration_extras, duration_from_micros)]
241     /// use std::time::Duration;
242     ///
243     /// let duration = Duration::from_micros(1_234_567);
244     /// assert_eq!(duration.as_secs(), 1);
245     /// assert_eq!(duration.subsec_micros(), 234_567);
246     /// ```
247     #[unstable(feature = "duration_extras", issue = "46507")]
248     #[inline]
249     pub fn subsec_micros(&self) -> u32 { self.nanos / NANOS_PER_MICRO }
250
251     /// Returns the fractional part of this `Duration`, in nanoseconds.
252     ///
253     /// This method does **not** return the length of the duration when
254     /// represented by nanoseconds. The returned number always represents a
255     /// fractional portion of a second (i.e. it is less than one billion).
256     ///
257     /// # Examples
258     ///
259     /// ```
260     /// use std::time::Duration;
261     ///
262     /// let duration = Duration::from_millis(5010);
263     /// assert_eq!(duration.as_secs(), 5);
264     /// assert_eq!(duration.subsec_nanos(), 10_000_000);
265     /// ```
266     #[stable(feature = "duration", since = "1.3.0")]
267     #[inline]
268     pub fn subsec_nanos(&self) -> u32 { self.nanos }
269
270     /// Checked `Duration` addition. Computes `self + other`, returning [`None`]
271     /// if overflow occurred.
272     ///
273     /// [`None`]: ../../std/option/enum.Option.html#variant.None
274     ///
275     /// # Examples
276     ///
277     /// Basic usage:
278     ///
279     /// ```
280     /// use std::time::Duration;
281     ///
282     /// assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1)));
283     /// assert_eq!(Duration::new(1, 0).checked_add(Duration::new(std::u64::MAX, 0)), None);
284     /// ```
285     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
286     #[inline]
287     pub fn checked_add(self, rhs: Duration) -> Option<Duration> {
288         if let Some(mut secs) = self.secs.checked_add(rhs.secs) {
289             let mut nanos = self.nanos + rhs.nanos;
290             if nanos >= NANOS_PER_SEC {
291                 nanos -= NANOS_PER_SEC;
292                 if let Some(new_secs) = secs.checked_add(1) {
293                     secs = new_secs;
294                 } else {
295                     return None;
296                 }
297             }
298             debug_assert!(nanos < NANOS_PER_SEC);
299             Some(Duration {
300                 secs,
301                 nanos,
302             })
303         } else {
304             None
305         }
306     }
307
308     /// Checked `Duration` subtraction. Computes `self - other`, returning [`None`]
309     /// if the result would be negative or if overflow occurred.
310     ///
311     /// [`None`]: ../../std/option/enum.Option.html#variant.None
312     ///
313     /// # Examples
314     ///
315     /// Basic usage:
316     ///
317     /// ```
318     /// use std::time::Duration;
319     ///
320     /// assert_eq!(Duration::new(0, 1).checked_sub(Duration::new(0, 0)), Some(Duration::new(0, 1)));
321     /// assert_eq!(Duration::new(0, 0).checked_sub(Duration::new(0, 1)), None);
322     /// ```
323     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
324     #[inline]
325     pub fn checked_sub(self, rhs: Duration) -> Option<Duration> {
326         if let Some(mut secs) = self.secs.checked_sub(rhs.secs) {
327             let nanos = if self.nanos >= rhs.nanos {
328                 self.nanos - rhs.nanos
329             } else {
330                 if let Some(sub_secs) = secs.checked_sub(1) {
331                     secs = sub_secs;
332                     self.nanos + NANOS_PER_SEC - rhs.nanos
333                 } else {
334                     return None;
335                 }
336             };
337             debug_assert!(nanos < NANOS_PER_SEC);
338             Some(Duration { secs: secs, nanos: nanos })
339         } else {
340             None
341         }
342     }
343
344     /// Checked `Duration` multiplication. Computes `self * other`, returning
345     /// [`None`] if overflow occurred.
346     ///
347     /// [`None`]: ../../std/option/enum.Option.html#variant.None
348     ///
349     /// # Examples
350     ///
351     /// Basic usage:
352     ///
353     /// ```
354     /// use std::time::Duration;
355     ///
356     /// assert_eq!(Duration::new(0, 500_000_001).checked_mul(2), Some(Duration::new(1, 2)));
357     /// assert_eq!(Duration::new(std::u64::MAX - 1, 0).checked_mul(2), None);
358     /// ```
359     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
360     #[inline]
361     pub fn checked_mul(self, rhs: u32) -> Option<Duration> {
362         // Multiply nanoseconds as u64, because it cannot overflow that way.
363         let total_nanos = self.nanos as u64 * rhs as u64;
364         let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
365         let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
366         if let Some(secs) = self.secs
367             .checked_mul(rhs as u64)
368             .and_then(|s| s.checked_add(extra_secs)) {
369             debug_assert!(nanos < NANOS_PER_SEC);
370             Some(Duration {
371                 secs,
372                 nanos,
373             })
374         } else {
375             None
376         }
377     }
378
379     /// Checked `Duration` division. Computes `self / other`, returning [`None`]
380     /// if `other == 0`.
381     ///
382     /// [`None`]: ../../std/option/enum.Option.html#variant.None
383     ///
384     /// # Examples
385     ///
386     /// Basic usage:
387     ///
388     /// ```
389     /// use std::time::Duration;
390     ///
391     /// assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0)));
392     /// assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000)));
393     /// assert_eq!(Duration::new(2, 0).checked_div(0), None);
394     /// ```
395     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
396     #[inline]
397     pub fn checked_div(self, rhs: u32) -> Option<Duration> {
398         if rhs != 0 {
399             let secs = self.secs / (rhs as u64);
400             let carry = self.secs - secs * (rhs as u64);
401             let extra_nanos = carry * (NANOS_PER_SEC as u64) / (rhs as u64);
402             let nanos = self.nanos / rhs + (extra_nanos as u32);
403             debug_assert!(nanos < NANOS_PER_SEC);
404             Some(Duration { secs: secs, nanos: nanos })
405         } else {
406             None
407         }
408     }
409 }
410
411 #[stable(feature = "duration", since = "1.3.0")]
412 impl Add for Duration {
413     type Output = Duration;
414
415     fn add(self, rhs: Duration) -> Duration {
416         self.checked_add(rhs).expect("overflow when adding durations")
417     }
418 }
419
420 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
421 impl AddAssign for Duration {
422     fn add_assign(&mut self, rhs: Duration) {
423         *self = *self + rhs;
424     }
425 }
426
427 #[stable(feature = "duration", since = "1.3.0")]
428 impl Sub for Duration {
429     type Output = Duration;
430
431     fn sub(self, rhs: Duration) -> Duration {
432         self.checked_sub(rhs).expect("overflow when subtracting durations")
433     }
434 }
435
436 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
437 impl SubAssign for Duration {
438     fn sub_assign(&mut self, rhs: Duration) {
439         *self = *self - rhs;
440     }
441 }
442
443 #[stable(feature = "duration", since = "1.3.0")]
444 impl Mul<u32> for Duration {
445     type Output = Duration;
446
447     fn mul(self, rhs: u32) -> Duration {
448         self.checked_mul(rhs).expect("overflow when multiplying duration by scalar")
449     }
450 }
451
452 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
453 impl MulAssign<u32> for Duration {
454     fn mul_assign(&mut self, rhs: u32) {
455         *self = *self * rhs;
456     }
457 }
458
459 #[stable(feature = "duration", since = "1.3.0")]
460 impl Div<u32> for Duration {
461     type Output = Duration;
462
463     fn div(self, rhs: u32) -> Duration {
464         self.checked_div(rhs).expect("divide by zero error when dividing duration by scalar")
465     }
466 }
467
468 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
469 impl DivAssign<u32> for Duration {
470     fn div_assign(&mut self, rhs: u32) {
471         *self = *self / rhs;
472     }
473 }
474
475 #[stable(feature = "duration_sum", since = "1.16.0")]
476 impl Sum for Duration {
477     fn sum<I: Iterator<Item=Duration>>(iter: I) -> Duration {
478         iter.fold(Duration::new(0, 0), |a, b| a + b)
479     }
480 }
481
482 #[stable(feature = "duration_sum", since = "1.16.0")]
483 impl<'a> Sum<&'a Duration> for Duration {
484     fn sum<I: Iterator<Item=&'a Duration>>(iter: I) -> Duration {
485         iter.fold(Duration::new(0, 0), |a, b| a + *b)
486     }
487 }
488
489 #[cfg(test)]
490 mod tests {
491     use super::Duration;
492
493     #[test]
494     fn creation() {
495         assert!(Duration::from_secs(1) != Duration::from_secs(0));
496         assert_eq!(Duration::from_secs(1) + Duration::from_secs(2),
497                    Duration::from_secs(3));
498         assert_eq!(Duration::from_millis(10) + Duration::from_secs(4),
499                    Duration::new(4, 10 * 1_000_000));
500         assert_eq!(Duration::from_millis(4000), Duration::new(4, 0));
501     }
502
503     #[test]
504     fn secs() {
505         assert_eq!(Duration::new(0, 0).as_secs(), 0);
506         assert_eq!(Duration::from_secs(1).as_secs(), 1);
507         assert_eq!(Duration::from_millis(999).as_secs(), 0);
508         assert_eq!(Duration::from_millis(1001).as_secs(), 1);
509     }
510
511     #[test]
512     fn nanos() {
513         assert_eq!(Duration::new(0, 0).subsec_nanos(), 0);
514         assert_eq!(Duration::new(0, 5).subsec_nanos(), 5);
515         assert_eq!(Duration::new(0, 1_000_000_001).subsec_nanos(), 1);
516         assert_eq!(Duration::from_secs(1).subsec_nanos(), 0);
517         assert_eq!(Duration::from_millis(999).subsec_nanos(), 999 * 1_000_000);
518         assert_eq!(Duration::from_millis(1001).subsec_nanos(), 1 * 1_000_000);
519     }
520
521     #[test]
522     fn add() {
523         assert_eq!(Duration::new(0, 0) + Duration::new(0, 1),
524                    Duration::new(0, 1));
525         assert_eq!(Duration::new(0, 500_000_000) + Duration::new(0, 500_000_001),
526                    Duration::new(1, 1));
527     }
528
529     #[test]
530     fn checked_add() {
531         assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)),
532                    Some(Duration::new(0, 1)));
533         assert_eq!(Duration::new(0, 500_000_000).checked_add(Duration::new(0, 500_000_001)),
534                    Some(Duration::new(1, 1)));
535         assert_eq!(Duration::new(1, 0).checked_add(Duration::new(::u64::MAX, 0)), None);
536     }
537
538     #[test]
539     fn sub() {
540         assert_eq!(Duration::new(0, 1) - Duration::new(0, 0),
541                    Duration::new(0, 1));
542         assert_eq!(Duration::new(0, 500_000_001) - Duration::new(0, 500_000_000),
543                    Duration::new(0, 1));
544         assert_eq!(Duration::new(1, 0) - Duration::new(0, 1),
545                    Duration::new(0, 999_999_999));
546     }
547
548     #[test]
549     fn checked_sub() {
550         let zero = Duration::new(0, 0);
551         let one_nano = Duration::new(0, 1);
552         let one_sec = Duration::new(1, 0);
553         assert_eq!(one_nano.checked_sub(zero), Some(Duration::new(0, 1)));
554         assert_eq!(one_sec.checked_sub(one_nano),
555                    Some(Duration::new(0, 999_999_999)));
556         assert_eq!(zero.checked_sub(one_nano), None);
557         assert_eq!(zero.checked_sub(one_sec), None);
558     }
559
560     #[test] #[should_panic]
561     fn sub_bad1() {
562         Duration::new(0, 0) - Duration::new(0, 1);
563     }
564
565     #[test] #[should_panic]
566     fn sub_bad2() {
567         Duration::new(0, 0) - Duration::new(1, 0);
568     }
569
570     #[test]
571     fn mul() {
572         assert_eq!(Duration::new(0, 1) * 2, Duration::new(0, 2));
573         assert_eq!(Duration::new(1, 1) * 3, Duration::new(3, 3));
574         assert_eq!(Duration::new(0, 500_000_001) * 4, Duration::new(2, 4));
575         assert_eq!(Duration::new(0, 500_000_001) * 4000,
576                    Duration::new(2000, 4000));
577     }
578
579     #[test]
580     fn checked_mul() {
581         assert_eq!(Duration::new(0, 1).checked_mul(2), Some(Duration::new(0, 2)));
582         assert_eq!(Duration::new(1, 1).checked_mul(3), Some(Duration::new(3, 3)));
583         assert_eq!(Duration::new(0, 500_000_001).checked_mul(4), Some(Duration::new(2, 4)));
584         assert_eq!(Duration::new(0, 500_000_001).checked_mul(4000),
585                    Some(Duration::new(2000, 4000)));
586         assert_eq!(Duration::new(::u64::MAX - 1, 0).checked_mul(2), None);
587     }
588
589     #[test]
590     fn div() {
591         assert_eq!(Duration::new(0, 1) / 2, Duration::new(0, 0));
592         assert_eq!(Duration::new(1, 1) / 3, Duration::new(0, 333_333_333));
593         assert_eq!(Duration::new(99, 999_999_000) / 100,
594                    Duration::new(0, 999_999_990));
595     }
596
597     #[test]
598     fn checked_div() {
599         assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0)));
600         assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000)));
601         assert_eq!(Duration::new(2, 0).checked_div(0), None);
602     }
603 }