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