]> git.lizzy.rs Git - rust.git/blob - src/libcore/time.rs
Rollup merge of #55575 - parched:trap, r=RalfJung
[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.25.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 {fmt, u64};
25 use iter::Sum;
26 use ops::{Add, Sub, Mul, Div, AddAssign, SubAssign, MulAssign, DivAssign};
27
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 + 1)*(NANOS_PER_SEC as u128)) as f64;
34
35 /// A `Duration` type to represent a span of time, typically used for system
36 /// timeouts.
37 ///
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.
42 ///
43 /// `Duration`s implement many common traits, including [`Add`], [`Sub`], and other
44 /// [`ops`] traits.
45 ///
46 /// [`Add`]: ../../std/ops/trait.Add.html
47 /// [`Sub`]: ../../std/ops/trait.Sub.html
48 /// [`ops`]: ../../std/ops/index.html
49 ///
50 /// # Examples
51 ///
52 /// ```
53 /// use std::time::Duration;
54 ///
55 /// let five_seconds = Duration::new(5, 0);
56 /// let five_seconds_and_five_nanos = five_seconds + Duration::new(0, 5);
57 ///
58 /// assert_eq!(five_seconds_and_five_nanos.as_secs(), 5);
59 /// assert_eq!(five_seconds_and_five_nanos.subsec_nanos(), 5);
60 ///
61 /// let ten_millis = Duration::from_millis(10);
62 /// ```
63 #[stable(feature = "duration", since = "1.3.0")]
64 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
65 pub struct Duration {
66     secs: u64,
67     nanos: u32, // Always 0 <= nanos < NANOS_PER_SEC
68 }
69
70 impl Duration {
71     /// Creates a new `Duration` from the specified number of whole seconds and
72     /// additional nanoseconds.
73     ///
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.
76     ///
77     /// # Panics
78     ///
79     /// This constructor will panic if the carry from the nanoseconds overflows
80     /// the seconds counter.
81     ///
82     /// # Examples
83     ///
84     /// ```
85     /// use std::time::Duration;
86     ///
87     /// let five_seconds = Duration::new(5, 0);
88     /// ```
89     #[stable(feature = "duration", since = "1.3.0")]
90     #[inline]
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, nanos }
96     }
97
98     /// Creates a new `Duration` from the specified number of whole seconds.
99     ///
100     /// # Examples
101     ///
102     /// ```
103     /// use std::time::Duration;
104     ///
105     /// let duration = Duration::from_secs(5);
106     ///
107     /// assert_eq!(5, duration.as_secs());
108     /// assert_eq!(0, duration.subsec_nanos());
109     /// ```
110     #[stable(feature = "duration", since = "1.3.0")]
111     #[inline]
112     #[rustc_promotable]
113     pub const fn from_secs(secs: u64) -> Duration {
114         Duration { secs, nanos: 0 }
115     }
116
117     /// Creates a new `Duration` from the specified number of milliseconds.
118     ///
119     /// # Examples
120     ///
121     /// ```
122     /// use std::time::Duration;
123     ///
124     /// let duration = Duration::from_millis(2569);
125     ///
126     /// assert_eq!(2, duration.as_secs());
127     /// assert_eq!(569_000_000, duration.subsec_nanos());
128     /// ```
129     #[stable(feature = "duration", since = "1.3.0")]
130     #[inline]
131     #[rustc_promotable]
132     pub const fn from_millis(millis: u64) -> Duration {
133         Duration {
134             secs: millis / MILLIS_PER_SEC,
135             nanos: ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI,
136         }
137     }
138
139     /// Creates a new `Duration` from the specified number of microseconds.
140     ///
141     /// # Examples
142     ///
143     /// ```
144     /// use std::time::Duration;
145     ///
146     /// let duration = Duration::from_micros(1_000_002);
147     ///
148     /// assert_eq!(1, duration.as_secs());
149     /// assert_eq!(2000, duration.subsec_nanos());
150     /// ```
151     #[stable(feature = "duration_from_micros", since = "1.27.0")]
152     #[inline]
153     #[rustc_promotable]
154     pub const fn from_micros(micros: u64) -> Duration {
155         Duration {
156             secs: micros / MICROS_PER_SEC,
157             nanos: ((micros % MICROS_PER_SEC) as u32) * NANOS_PER_MICRO,
158         }
159     }
160
161     /// Creates a new `Duration` from the specified number of nanoseconds.
162     ///
163     /// # Examples
164     ///
165     /// ```
166     /// use std::time::Duration;
167     ///
168     /// let duration = Duration::from_nanos(1_000_000_123);
169     ///
170     /// assert_eq!(1, duration.as_secs());
171     /// assert_eq!(123, duration.subsec_nanos());
172     /// ```
173     #[stable(feature = "duration_extras", since = "1.27.0")]
174     #[inline]
175     #[rustc_promotable]
176     pub const fn from_nanos(nanos: u64) -> Duration {
177         Duration {
178             secs: nanos / (NANOS_PER_SEC as u64),
179             nanos: (nanos % (NANOS_PER_SEC as u64)) as u32,
180         }
181     }
182
183     /// Returns the number of _whole_ seconds contained by this `Duration`.
184     ///
185     /// The returned value does not include the fractional (nanosecond) part of the
186     /// duration, which can be obtained using [`subsec_nanos`].
187     ///
188     /// # Examples
189     ///
190     /// ```
191     /// use std::time::Duration;
192     ///
193     /// let duration = Duration::new(5, 730023852);
194     /// assert_eq!(duration.as_secs(), 5);
195     /// ```
196     ///
197     /// To determine the total number of seconds represented by the `Duration`,
198     /// use `as_secs` in combination with [`subsec_nanos`]:
199     ///
200     /// ```
201     /// use std::time::Duration;
202     ///
203     /// let duration = Duration::new(5, 730023852);
204     ///
205     /// assert_eq!(5.730023852,
206     ///            duration.as_secs() as f64
207     ///            + duration.subsec_nanos() as f64 * 1e-9);
208     /// ```
209     ///
210     /// [`subsec_nanos`]: #method.subsec_nanos
211     #[stable(feature = "duration", since = "1.3.0")]
212     #[rustc_const_unstable(feature="duration_getters")]
213     #[inline]
214     pub const fn as_secs(&self) -> u64 { self.secs }
215
216     /// Returns the fractional part of this `Duration`, in whole milliseconds.
217     ///
218     /// This method does **not** return the length of the duration when
219     /// represented by milliseconds. The returned number always represents a
220     /// fractional portion of a second (i.e. it is less than one thousand).
221     ///
222     /// # Examples
223     ///
224     /// ```
225     /// use std::time::Duration;
226     ///
227     /// let duration = Duration::from_millis(5432);
228     /// assert_eq!(duration.as_secs(), 5);
229     /// assert_eq!(duration.subsec_millis(), 432);
230     /// ```
231     #[stable(feature = "duration_extras", since = "1.27.0")]
232     #[rustc_const_unstable(feature="duration_getters")]
233     #[inline]
234     pub const fn subsec_millis(&self) -> u32 { self.nanos / NANOS_PER_MILLI }
235
236     /// Returns the fractional part of this `Duration`, in whole microseconds.
237     ///
238     /// This method does **not** return the length of the duration when
239     /// represented by microseconds. The returned number always represents a
240     /// fractional portion of a second (i.e. it is less than one million).
241     ///
242     /// # Examples
243     ///
244     /// ```
245     /// use std::time::Duration;
246     ///
247     /// let duration = Duration::from_micros(1_234_567);
248     /// assert_eq!(duration.as_secs(), 1);
249     /// assert_eq!(duration.subsec_micros(), 234_567);
250     /// ```
251     #[stable(feature = "duration_extras", since = "1.27.0")]
252     #[rustc_const_unstable(feature="duration_getters")]
253     #[inline]
254     pub const fn subsec_micros(&self) -> u32 { self.nanos / NANOS_PER_MICRO }
255
256     /// Returns the fractional part of this `Duration`, in nanoseconds.
257     ///
258     /// This method does **not** return the length of the duration when
259     /// represented by nanoseconds. The returned number always represents a
260     /// fractional portion of a second (i.e. it is less than one billion).
261     ///
262     /// # Examples
263     ///
264     /// ```
265     /// use std::time::Duration;
266     ///
267     /// let duration = Duration::from_millis(5010);
268     /// assert_eq!(duration.as_secs(), 5);
269     /// assert_eq!(duration.subsec_nanos(), 10_000_000);
270     /// ```
271     #[stable(feature = "duration", since = "1.3.0")]
272     #[rustc_const_unstable(feature="duration_getters")]
273     #[inline]
274     pub const fn subsec_nanos(&self) -> u32 { self.nanos }
275
276     /// Returns the total number of whole milliseconds contained by this `Duration`.
277     ///
278     /// # Examples
279     ///
280     /// ```
281     /// # #![feature(duration_as_u128)]
282     /// use std::time::Duration;
283     ///
284     /// let duration = Duration::new(5, 730023852);
285     /// assert_eq!(duration.as_millis(), 5730);
286     /// ```
287     #[unstable(feature = "duration_as_u128", issue = "50202")]
288     #[inline]
289     pub fn as_millis(&self) -> u128 {
290         self.secs as u128 * MILLIS_PER_SEC as u128 + (self.nanos / NANOS_PER_MILLI) as u128
291     }
292
293     /// Returns the total number of whole microseconds contained by this `Duration`.
294     ///
295     /// # Examples
296     ///
297     /// ```
298     /// # #![feature(duration_as_u128)]
299     /// use std::time::Duration;
300     ///
301     /// let duration = Duration::new(5, 730023852);
302     /// assert_eq!(duration.as_micros(), 5730023);
303     /// ```
304     #[unstable(feature = "duration_as_u128", issue = "50202")]
305     #[inline]
306     pub fn as_micros(&self) -> u128 {
307         self.secs as u128 * MICROS_PER_SEC as u128 + (self.nanos / NANOS_PER_MICRO) as u128
308     }
309
310     /// Returns the total number of nanoseconds contained by this `Duration`.
311     ///
312     /// # Examples
313     ///
314     /// ```
315     /// # #![feature(duration_as_u128)]
316     /// use std::time::Duration;
317     ///
318     /// let duration = Duration::new(5, 730023852);
319     /// assert_eq!(duration.as_nanos(), 5730023852);
320     /// ```
321     #[unstable(feature = "duration_as_u128", issue = "50202")]
322     #[inline]
323     pub fn as_nanos(&self) -> u128 {
324         self.secs as u128 * NANOS_PER_SEC as u128 + self.nanos as u128
325     }
326
327     /// Checked `Duration` addition. Computes `self + other`, returning [`None`]
328     /// if overflow occurred.
329     ///
330     /// [`None`]: ../../std/option/enum.Option.html#variant.None
331     ///
332     /// # Examples
333     ///
334     /// Basic usage:
335     ///
336     /// ```
337     /// use std::time::Duration;
338     ///
339     /// assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1)));
340     /// assert_eq!(Duration::new(1, 0).checked_add(Duration::new(std::u64::MAX, 0)), None);
341     /// ```
342     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
343     #[inline]
344     pub fn checked_add(self, rhs: Duration) -> Option<Duration> {
345         if let Some(mut secs) = self.secs.checked_add(rhs.secs) {
346             let mut nanos = self.nanos + rhs.nanos;
347             if nanos >= NANOS_PER_SEC {
348                 nanos -= NANOS_PER_SEC;
349                 if let Some(new_secs) = secs.checked_add(1) {
350                     secs = new_secs;
351                 } else {
352                     return None;
353                 }
354             }
355             debug_assert!(nanos < NANOS_PER_SEC);
356             Some(Duration {
357                 secs,
358                 nanos,
359             })
360         } else {
361             None
362         }
363     }
364
365     /// Checked `Duration` subtraction. Computes `self - other`, returning [`None`]
366     /// if the result would be negative or if overflow occurred.
367     ///
368     /// [`None`]: ../../std/option/enum.Option.html#variant.None
369     ///
370     /// # Examples
371     ///
372     /// Basic usage:
373     ///
374     /// ```
375     /// use std::time::Duration;
376     ///
377     /// assert_eq!(Duration::new(0, 1).checked_sub(Duration::new(0, 0)), Some(Duration::new(0, 1)));
378     /// assert_eq!(Duration::new(0, 0).checked_sub(Duration::new(0, 1)), None);
379     /// ```
380     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
381     #[inline]
382     pub fn checked_sub(self, rhs: Duration) -> Option<Duration> {
383         if let Some(mut secs) = self.secs.checked_sub(rhs.secs) {
384             let nanos = if self.nanos >= rhs.nanos {
385                 self.nanos - rhs.nanos
386             } else {
387                 if let Some(sub_secs) = secs.checked_sub(1) {
388                     secs = sub_secs;
389                     self.nanos + NANOS_PER_SEC - rhs.nanos
390                 } else {
391                     return None;
392                 }
393             };
394             debug_assert!(nanos < NANOS_PER_SEC);
395             Some(Duration { secs, nanos })
396         } else {
397             None
398         }
399     }
400
401     /// Checked `Duration` multiplication. Computes `self * other`, returning
402     /// [`None`] if overflow occurred.
403     ///
404     /// [`None`]: ../../std/option/enum.Option.html#variant.None
405     ///
406     /// # Examples
407     ///
408     /// Basic usage:
409     ///
410     /// ```
411     /// use std::time::Duration;
412     ///
413     /// assert_eq!(Duration::new(0, 500_000_001).checked_mul(2), Some(Duration::new(1, 2)));
414     /// assert_eq!(Duration::new(std::u64::MAX - 1, 0).checked_mul(2), None);
415     /// ```
416     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
417     #[inline]
418     pub fn checked_mul(self, rhs: u32) -> Option<Duration> {
419         // Multiply nanoseconds as u64, because it cannot overflow that way.
420         let total_nanos = self.nanos as u64 * rhs as u64;
421         let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
422         let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
423         if let Some(secs) = self.secs
424             .checked_mul(rhs as u64)
425             .and_then(|s| s.checked_add(extra_secs)) {
426             debug_assert!(nanos < NANOS_PER_SEC);
427             Some(Duration {
428                 secs,
429                 nanos,
430             })
431         } else {
432             None
433         }
434     }
435
436     /// Checked `Duration` division. Computes `self / other`, returning [`None`]
437     /// if `other == 0`.
438     ///
439     /// [`None`]: ../../std/option/enum.Option.html#variant.None
440     ///
441     /// # Examples
442     ///
443     /// Basic usage:
444     ///
445     /// ```
446     /// use std::time::Duration;
447     ///
448     /// assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0)));
449     /// assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000)));
450     /// assert_eq!(Duration::new(2, 0).checked_div(0), None);
451     /// ```
452     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
453     #[inline]
454     pub fn checked_div(self, rhs: u32) -> Option<Duration> {
455         if rhs != 0 {
456             let secs = self.secs / (rhs as u64);
457             let carry = self.secs - secs * (rhs as u64);
458             let extra_nanos = carry * (NANOS_PER_SEC as u64) / (rhs as u64);
459             let nanos = self.nanos / rhs + (extra_nanos as u32);
460             debug_assert!(nanos < NANOS_PER_SEC);
461             Some(Duration { secs, nanos })
462         } else {
463             None
464         }
465     }
466
467     /// Returns the number of seconds contained by this `Duration` as `f64`.
468     ///
469     /// The returned value does include the fractional (nanosecond) part of the duration.
470     ///
471     /// # Examples
472     /// ```
473     /// #![feature(duration_float)]
474     /// use std::time::Duration;
475     ///
476     /// let dur = Duration::new(2, 700_000_000);
477     /// assert_eq!(dur.as_float_secs(), 2.7);
478     /// ```
479     #[unstable(feature = "duration_float", issue = "54361")]
480     #[inline]
481     pub fn as_float_secs(&self) -> f64 {
482         (self.secs as f64) + (self.nanos as f64) / (NANOS_PER_SEC as f64)
483     }
484
485     /// Creates a new `Duration` from the specified number of seconds.
486     ///
487     /// # Panics
488     /// This constructor will panic if `secs` is not finite, negative or overflows `Duration`.
489     ///
490     /// # Examples
491     /// ```
492     /// #![feature(duration_float)]
493     /// use std::time::Duration;
494     ///
495     /// let dur = Duration::from_float_secs(2.7);
496     /// assert_eq!(dur, Duration::new(2, 700_000_000));
497     /// ```
498     #[unstable(feature = "duration_float", issue = "54361")]
499     #[inline]
500     pub fn from_float_secs(secs: f64) -> Duration {
501         let nanos =  secs * (NANOS_PER_SEC as f64);
502         if !nanos.is_finite() {
503             panic!("got non-finite value when converting float to duration");
504         }
505         if nanos >= MAX_NANOS_F64 {
506             panic!("overflow when converting float to duration");
507         }
508         if nanos < 0.0 {
509             panic!("underflow when converting float to duration");
510         }
511         let nanos =  nanos as u128;
512         Duration {
513             secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
514             nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
515         }
516     }
517
518     /// Multiply `Duration` by `f64`.
519     ///
520     /// # Panics
521     /// This method will panic if result is not finite, negative or overflows `Duration`.
522     ///
523     /// # Examples
524     /// ```
525     /// #![feature(duration_float)]
526     /// use std::time::Duration;
527     ///
528     /// let dur = Duration::new(2, 700_000_000);
529     /// assert_eq!(dur.mul_f64(3.14), Duration::new(8, 478_000_000));
530     /// assert_eq!(dur.mul_f64(3.14e5), Duration::new(847_800, 0));
531     /// ```
532     #[unstable(feature = "duration_float", issue = "54361")]
533     #[inline]
534     pub fn mul_f64(self, rhs: f64) -> Duration {
535         Duration::from_float_secs(rhs * self.as_float_secs())
536     }
537
538     /// Divide `Duration` by `f64`.
539     ///
540     /// # Panics
541     /// This method will panic if result is not finite, negative or overflows `Duration`.
542     ///
543     /// # Examples
544     /// ```
545     /// #![feature(duration_float)]
546     /// use std::time::Duration;
547     ///
548     /// let dur = Duration::new(2, 700_000_000);
549     /// assert_eq!(dur.div_f64(3.14), Duration::new(0, 859_872_611));
550     /// // note that truncation is used, not rounding
551     /// assert_eq!(dur.div_f64(3.14e5), Duration::new(0, 8_598));
552     /// ```
553     #[unstable(feature = "duration_float", issue = "54361")]
554     #[inline]
555     pub fn div_f64(self, rhs: f64) -> Duration {
556         Duration::from_float_secs(self.as_float_secs() / rhs)
557     }
558
559     /// Divide `Duration` by `Duration` and return `f64`.
560     ///
561     /// # Examples
562     /// ```
563     /// #![feature(duration_float)]
564     /// use std::time::Duration;
565     ///
566     /// let dur1 = Duration::new(2, 700_000_000);
567     /// let dur2 = Duration::new(5, 400_000_000);
568     /// assert_eq!(dur1.div_duration(dur2), 0.5);
569     /// ```
570     #[unstable(feature = "duration_float", issue = "54361")]
571     #[inline]
572     pub fn div_duration(self, rhs: Duration) -> f64 {
573         self.as_float_secs() / rhs.as_float_secs()
574     }
575 }
576
577 #[stable(feature = "duration", since = "1.3.0")]
578 impl Add for Duration {
579     type Output = Duration;
580
581     fn add(self, rhs: Duration) -> Duration {
582         self.checked_add(rhs).expect("overflow when adding durations")
583     }
584 }
585
586 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
587 impl AddAssign for Duration {
588     fn add_assign(&mut self, rhs: Duration) {
589         *self = *self + rhs;
590     }
591 }
592
593 #[stable(feature = "duration", since = "1.3.0")]
594 impl Sub for Duration {
595     type Output = Duration;
596
597     fn sub(self, rhs: Duration) -> Duration {
598         self.checked_sub(rhs).expect("overflow when subtracting durations")
599     }
600 }
601
602 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
603 impl SubAssign for Duration {
604     fn sub_assign(&mut self, rhs: Duration) {
605         *self = *self - rhs;
606     }
607 }
608
609 #[stable(feature = "duration", since = "1.3.0")]
610 impl Mul<u32> for Duration {
611     type Output = Duration;
612
613     fn mul(self, rhs: u32) -> Duration {
614         self.checked_mul(rhs).expect("overflow when multiplying duration by scalar")
615     }
616 }
617
618 #[stable(feature = "symmetric_u32_duration_mul", since = "1.31.0")]
619 impl Mul<Duration> for u32 {
620     type Output = Duration;
621
622     fn mul(self, rhs: Duration) -> Duration {
623         rhs * self
624     }
625 }
626
627 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
628 impl MulAssign<u32> for Duration {
629     fn mul_assign(&mut self, rhs: u32) {
630         *self = *self * rhs;
631     }
632 }
633
634 #[stable(feature = "duration", since = "1.3.0")]
635 impl Div<u32> for Duration {
636     type Output = Duration;
637
638     fn div(self, rhs: u32) -> Duration {
639         self.checked_div(rhs).expect("divide by zero error when dividing duration by scalar")
640     }
641 }
642
643 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
644 impl DivAssign<u32> for Duration {
645     fn div_assign(&mut self, rhs: u32) {
646         *self = *self / rhs;
647     }
648 }
649
650 macro_rules! sum_durations {
651     ($iter:expr) => {{
652         let mut total_secs: u64 = 0;
653         let mut total_nanos: u64 = 0;
654
655         for entry in $iter {
656             total_secs = total_secs
657                 .checked_add(entry.secs)
658                 .expect("overflow in iter::sum over durations");
659             total_nanos = match total_nanos.checked_add(entry.nanos as u64) {
660                 Some(n) => n,
661                 None => {
662                     total_secs = total_secs
663                         .checked_add(total_nanos / NANOS_PER_SEC as u64)
664                         .expect("overflow in iter::sum over durations");
665                     (total_nanos % NANOS_PER_SEC as u64) + entry.nanos as u64
666                 }
667             };
668         }
669         total_secs = total_secs
670             .checked_add(total_nanos / NANOS_PER_SEC as u64)
671             .expect("overflow in iter::sum over durations");
672         total_nanos = total_nanos % NANOS_PER_SEC as u64;
673         Duration {
674             secs: total_secs,
675             nanos: total_nanos as u32,
676         }
677     }};
678 }
679
680 #[stable(feature = "duration_sum", since = "1.16.0")]
681 impl Sum for Duration {
682     fn sum<I: Iterator<Item=Duration>>(iter: I) -> Duration {
683         sum_durations!(iter)
684     }
685 }
686
687 #[stable(feature = "duration_sum", since = "1.16.0")]
688 impl<'a> Sum<&'a Duration> for Duration {
689     fn sum<I: Iterator<Item=&'a Duration>>(iter: I) -> Duration {
690         sum_durations!(iter)
691     }
692 }
693
694 #[stable(feature = "duration_debug_impl", since = "1.27.0")]
695 impl fmt::Debug for Duration {
696     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
697         /// Formats a floating point number in decimal notation.
698         ///
699         /// The number is given as the `integer_part` and a fractional part.
700         /// The value of the fractional part is `fractional_part / divisor`. So
701         /// `integer_part` = 3, `fractional_part` = 12 and `divisor` = 100
702         /// represents the number `3.012`. Trailing zeros are omitted.
703         ///
704         /// `divisor` must not be above 100_000_000. It also should be a power
705         /// of 10, everything else doesn't make sense. `fractional_part` has
706         /// to be less than `10 * divisor`!
707         fn fmt_decimal(
708             f: &mut fmt::Formatter,
709             mut integer_part: u64,
710             mut fractional_part: u32,
711             mut divisor: u32,
712         ) -> fmt::Result {
713             // Encode the fractional part into a temporary buffer. The buffer
714             // only need to hold 9 elements, because `fractional_part` has to
715             // be smaller than 10^9. The buffer is prefilled with '0' digits
716             // to simplify the code below.
717             let mut buf = [b'0'; 9];
718
719             // The next digit is written at this position
720             let mut pos = 0;
721
722             // We keep writing digits into the buffer while there are non-zero
723             // digits left and we haven't written enough digits yet.
724             while fractional_part > 0 && pos < f.precision().unwrap_or(9) {
725                 // Write new digit into the buffer
726                 buf[pos] = b'0' + (fractional_part / divisor) as u8;
727
728                 fractional_part %= divisor;
729                 divisor /= 10;
730                 pos += 1;
731             }
732
733             // If a precision < 9 was specified, there may be some non-zero
734             // digits left that weren't written into the buffer. In that case we
735             // need to perform rounding to match the semantics of printing
736             // normal floating point numbers. However, we only need to do work
737             // when rounding up. This happens if the first digit of the
738             // remaining ones is >= 5.
739             if fractional_part > 0 && fractional_part >= divisor * 5 {
740                 // Round up the number contained in the buffer. We go through
741                 // the buffer backwards and keep track of the carry.
742                 let mut rev_pos = pos;
743                 let mut carry = true;
744                 while carry && rev_pos > 0 {
745                     rev_pos -= 1;
746
747                     // If the digit in the buffer is not '9', we just need to
748                     // increment it and can stop then (since we don't have a
749                     // carry anymore). Otherwise, we set it to '0' (overflow)
750                     // and continue.
751                     if buf[rev_pos] < b'9' {
752                         buf[rev_pos] += 1;
753                         carry = false;
754                     } else {
755                         buf[rev_pos] = b'0';
756                     }
757                 }
758
759                 // If we still have the carry bit set, that means that we set
760                 // the whole buffer to '0's and need to increment the integer
761                 // part.
762                 if carry {
763                     integer_part += 1;
764                 }
765             }
766
767             // Determine the end of the buffer: if precision is set, we just
768             // use as many digits from the buffer (capped to 9). If it isn't
769             // set, we only use all digits up to the last non-zero one.
770             let end = f.precision().map(|p| ::cmp::min(p, 9)).unwrap_or(pos);
771
772             // If we haven't emitted a single fractional digit and the precision
773             // wasn't set to a non-zero value, we don't print the decimal point.
774             if end == 0 {
775                 write!(f, "{}", integer_part)
776             } else {
777                 // We are only writing ASCII digits into the buffer and it was
778                 // initialized with '0's, so it contains valid UTF8.
779                 let s = unsafe {
780                     ::str::from_utf8_unchecked(&buf[..end])
781                 };
782
783                 // If the user request a precision > 9, we pad '0's at the end.
784                 let w = f.precision().unwrap_or(pos);
785                 write!(f, "{}.{:0<width$}", integer_part, s, width = w)
786             }
787         }
788
789         // Print leading '+' sign if requested
790         if f.sign_plus() {
791             write!(f, "+")?;
792         }
793
794         if self.secs > 0 {
795             fmt_decimal(f, self.secs, self.nanos, 100_000_000)?;
796             f.write_str("s")
797         } else if self.nanos >= 1_000_000 {
798             fmt_decimal(f, self.nanos as u64 / 1_000_000, self.nanos % 1_000_000, 100_000)?;
799             f.write_str("ms")
800         } else if self.nanos >= 1_000 {
801             fmt_decimal(f, self.nanos as u64 / 1_000, self.nanos % 1_000, 100)?;
802             f.write_str("µs")
803         } else {
804             fmt_decimal(f, self.nanos as u64, 0, 1)?;
805             f.write_str("ns")
806         }
807     }
808 }