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