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