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