]> git.lizzy.rs Git - rust.git/blob - src/libcore/time.rs
Rollup merge of #67321 - lzutao:htons, r=dtolnay
[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 crate::iter::Sum;
16 use crate::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
17 use crate::{fmt, u64};
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     #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
134     pub fn new(secs: u64, nanos: u32) -> Duration {
135         let secs =
136             secs.checked_add((nanos / NANOS_PER_SEC) as u64).expect("overflow in Duration::new");
137         let nanos = nanos % NANOS_PER_SEC;
138         Duration { secs, nanos }
139     }
140
141     /// Creates a new `Duration` from the specified number of whole seconds.
142     ///
143     /// # Examples
144     ///
145     /// ```
146     /// use std::time::Duration;
147     ///
148     /// let duration = Duration::from_secs(5);
149     ///
150     /// assert_eq!(5, duration.as_secs());
151     /// assert_eq!(0, duration.subsec_nanos());
152     /// ```
153     #[stable(feature = "duration", since = "1.3.0")]
154     #[inline]
155     #[rustc_promotable]
156     #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
157     pub const fn from_secs(secs: u64) -> Duration {
158         Duration { secs, nanos: 0 }
159     }
160
161     /// Creates a new `Duration` from the specified number of milliseconds.
162     ///
163     /// # Examples
164     ///
165     /// ```
166     /// use std::time::Duration;
167     ///
168     /// let duration = Duration::from_millis(2569);
169     ///
170     /// assert_eq!(2, duration.as_secs());
171     /// assert_eq!(569_000_000, duration.subsec_nanos());
172     /// ```
173     #[stable(feature = "duration", since = "1.3.0")]
174     #[inline]
175     #[rustc_promotable]
176     #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
177     pub const fn from_millis(millis: u64) -> Duration {
178         Duration {
179             secs: millis / MILLIS_PER_SEC,
180             nanos: ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI,
181         }
182     }
183
184     /// Creates a new `Duration` from the specified number of microseconds.
185     ///
186     /// # Examples
187     ///
188     /// ```
189     /// use std::time::Duration;
190     ///
191     /// let duration = Duration::from_micros(1_000_002);
192     ///
193     /// assert_eq!(1, duration.as_secs());
194     /// assert_eq!(2000, duration.subsec_nanos());
195     /// ```
196     #[stable(feature = "duration_from_micros", since = "1.27.0")]
197     #[inline]
198     #[rustc_promotable]
199     #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
200     pub const fn from_micros(micros: u64) -> Duration {
201         Duration {
202             secs: micros / MICROS_PER_SEC,
203             nanos: ((micros % MICROS_PER_SEC) as u32) * NANOS_PER_MICRO,
204         }
205     }
206
207     /// Creates a new `Duration` from the specified number of nanoseconds.
208     ///
209     /// # Examples
210     ///
211     /// ```
212     /// use std::time::Duration;
213     ///
214     /// let duration = Duration::from_nanos(1_000_000_123);
215     ///
216     /// assert_eq!(1, duration.as_secs());
217     /// assert_eq!(123, duration.subsec_nanos());
218     /// ```
219     #[stable(feature = "duration_extras", since = "1.27.0")]
220     #[inline]
221     #[rustc_promotable]
222     #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
223     pub const fn from_nanos(nanos: u64) -> Duration {
224         Duration {
225             secs: nanos / (NANOS_PER_SEC as u64),
226             nanos: (nanos % (NANOS_PER_SEC as u64)) as u32,
227         }
228     }
229
230     /// Returns the number of _whole_ seconds contained by this `Duration`.
231     ///
232     /// The returned value does not include the fractional (nanosecond) part of the
233     /// duration, which can be obtained using [`subsec_nanos`].
234     ///
235     /// # Examples
236     ///
237     /// ```
238     /// use std::time::Duration;
239     ///
240     /// let duration = Duration::new(5, 730023852);
241     /// assert_eq!(duration.as_secs(), 5);
242     /// ```
243     ///
244     /// To determine the total number of seconds represented by the `Duration`,
245     /// use `as_secs` in combination with [`subsec_nanos`]:
246     ///
247     /// ```
248     /// use std::time::Duration;
249     ///
250     /// let duration = Duration::new(5, 730023852);
251     ///
252     /// assert_eq!(5.730023852,
253     ///            duration.as_secs() as f64
254     ///            + duration.subsec_nanos() as f64 * 1e-9);
255     /// ```
256     ///
257     /// [`subsec_nanos`]: #method.subsec_nanos
258     #[stable(feature = "duration", since = "1.3.0")]
259     #[rustc_const_stable(feature = "duration", since = "1.32.0")]
260     #[inline]
261     pub const fn as_secs(&self) -> u64 {
262         self.secs
263     }
264
265     /// Returns the fractional part of this `Duration`, in whole milliseconds.
266     ///
267     /// This method does **not** return the length of the duration when
268     /// represented by milliseconds. The returned number always represents a
269     /// fractional portion of a second (i.e., it is less than one thousand).
270     ///
271     /// # Examples
272     ///
273     /// ```
274     /// use std::time::Duration;
275     ///
276     /// let duration = Duration::from_millis(5432);
277     /// assert_eq!(duration.as_secs(), 5);
278     /// assert_eq!(duration.subsec_millis(), 432);
279     /// ```
280     #[stable(feature = "duration_extras", since = "1.27.0")]
281     #[rustc_const_stable(feature = "duration_extras", since = "1.32.0")]
282     #[inline]
283     pub const fn subsec_millis(&self) -> u32 {
284         self.nanos / NANOS_PER_MILLI
285     }
286
287     /// Returns the fractional part of this `Duration`, in whole microseconds.
288     ///
289     /// This method does **not** return the length of the duration when
290     /// represented by microseconds. The returned number always represents a
291     /// fractional portion of a second (i.e., it is less than one million).
292     ///
293     /// # Examples
294     ///
295     /// ```
296     /// use std::time::Duration;
297     ///
298     /// let duration = Duration::from_micros(1_234_567);
299     /// assert_eq!(duration.as_secs(), 1);
300     /// assert_eq!(duration.subsec_micros(), 234_567);
301     /// ```
302     #[stable(feature = "duration_extras", since = "1.27.0")]
303     #[rustc_const_stable(feature = "duration_extras", since = "1.32.0")]
304     #[inline]
305     pub const fn subsec_micros(&self) -> u32 {
306         self.nanos / NANOS_PER_MICRO
307     }
308
309     /// Returns the fractional part of this `Duration`, in nanoseconds.
310     ///
311     /// This method does **not** return the length of the duration when
312     /// represented by nanoseconds. The returned number always represents a
313     /// fractional portion of a second (i.e., it is less than one billion).
314     ///
315     /// # Examples
316     ///
317     /// ```
318     /// use std::time::Duration;
319     ///
320     /// let duration = Duration::from_millis(5010);
321     /// assert_eq!(duration.as_secs(), 5);
322     /// assert_eq!(duration.subsec_nanos(), 10_000_000);
323     /// ```
324     #[stable(feature = "duration", since = "1.3.0")]
325     #[rustc_const_stable(feature = "duration", since = "1.32.0")]
326     #[inline]
327     pub const fn subsec_nanos(&self) -> u32 {
328         self.nanos
329     }
330
331     /// Returns the total number of whole milliseconds contained by this `Duration`.
332     ///
333     /// # Examples
334     ///
335     /// ```
336     /// use std::time::Duration;
337     ///
338     /// let duration = Duration::new(5, 730023852);
339     /// assert_eq!(duration.as_millis(), 5730);
340     /// ```
341     #[stable(feature = "duration_as_u128", since = "1.33.0")]
342     #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
343     #[inline]
344     pub const fn as_millis(&self) -> u128 {
345         self.secs as u128 * MILLIS_PER_SEC as u128 + (self.nanos / NANOS_PER_MILLI) as u128
346     }
347
348     /// Returns the total number of whole microseconds contained by this `Duration`.
349     ///
350     /// # Examples
351     ///
352     /// ```
353     /// use std::time::Duration;
354     ///
355     /// let duration = Duration::new(5, 730023852);
356     /// assert_eq!(duration.as_micros(), 5730023);
357     /// ```
358     #[stable(feature = "duration_as_u128", since = "1.33.0")]
359     #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
360     #[inline]
361     pub const fn as_micros(&self) -> u128 {
362         self.secs as u128 * MICROS_PER_SEC as u128 + (self.nanos / NANOS_PER_MICRO) as u128
363     }
364
365     /// Returns the total number of nanoseconds contained by this `Duration`.
366     ///
367     /// # Examples
368     ///
369     /// ```
370     /// use std::time::Duration;
371     ///
372     /// let duration = Duration::new(5, 730023852);
373     /// assert_eq!(duration.as_nanos(), 5730023852);
374     /// ```
375     #[stable(feature = "duration_as_u128", since = "1.33.0")]
376     #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
377     #[inline]
378     pub const fn as_nanos(&self) -> u128 {
379         self.secs as u128 * NANOS_PER_SEC as u128 + self.nanos as u128
380     }
381
382     /// Checked `Duration` addition. Computes `self + other`, returning [`None`]
383     /// if overflow occurred.
384     ///
385     /// [`None`]: ../../std/option/enum.Option.html#variant.None
386     ///
387     /// # Examples
388     ///
389     /// Basic usage:
390     ///
391     /// ```
392     /// use std::time::Duration;
393     ///
394     /// assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1)));
395     /// assert_eq!(Duration::new(1, 0).checked_add(Duration::new(std::u64::MAX, 0)), None);
396     /// ```
397     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
398     #[inline]
399     pub fn checked_add(self, rhs: Duration) -> Option<Duration> {
400         if let Some(mut secs) = self.secs.checked_add(rhs.secs) {
401             let mut nanos = self.nanos + rhs.nanos;
402             if nanos >= NANOS_PER_SEC {
403                 nanos -= NANOS_PER_SEC;
404                 if let Some(new_secs) = secs.checked_add(1) {
405                     secs = new_secs;
406                 } else {
407                     return None;
408                 }
409             }
410             debug_assert!(nanos < NANOS_PER_SEC);
411             Some(Duration { secs, nanos })
412         } else {
413             None
414         }
415     }
416
417     /// Checked `Duration` subtraction. Computes `self - other`, returning [`None`]
418     /// if the result would be negative or if overflow occurred.
419     ///
420     /// [`None`]: ../../std/option/enum.Option.html#variant.None
421     ///
422     /// # Examples
423     ///
424     /// Basic usage:
425     ///
426     /// ```
427     /// use std::time::Duration;
428     ///
429     /// assert_eq!(Duration::new(0, 1).checked_sub(Duration::new(0, 0)), Some(Duration::new(0, 1)));
430     /// assert_eq!(Duration::new(0, 0).checked_sub(Duration::new(0, 1)), None);
431     /// ```
432     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
433     #[inline]
434     pub fn checked_sub(self, rhs: Duration) -> Option<Duration> {
435         if let Some(mut secs) = self.secs.checked_sub(rhs.secs) {
436             let nanos = if self.nanos >= rhs.nanos {
437                 self.nanos - rhs.nanos
438             } else {
439                 if let Some(sub_secs) = secs.checked_sub(1) {
440                     secs = sub_secs;
441                     self.nanos + NANOS_PER_SEC - rhs.nanos
442                 } else {
443                     return None;
444                 }
445             };
446             debug_assert!(nanos < NANOS_PER_SEC);
447             Some(Duration { secs, nanos })
448         } else {
449             None
450         }
451     }
452
453     /// Checked `Duration` multiplication. Computes `self * other`, returning
454     /// [`None`] if overflow occurred.
455     ///
456     /// [`None`]: ../../std/option/enum.Option.html#variant.None
457     ///
458     /// # Examples
459     ///
460     /// Basic usage:
461     ///
462     /// ```
463     /// use std::time::Duration;
464     ///
465     /// assert_eq!(Duration::new(0, 500_000_001).checked_mul(2), Some(Duration::new(1, 2)));
466     /// assert_eq!(Duration::new(std::u64::MAX - 1, 0).checked_mul(2), None);
467     /// ```
468     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
469     #[inline]
470     pub fn checked_mul(self, rhs: u32) -> Option<Duration> {
471         // Multiply nanoseconds as u64, because it cannot overflow that way.
472         let total_nanos = self.nanos as u64 * rhs as u64;
473         let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
474         let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
475         if let Some(secs) =
476             self.secs.checked_mul(rhs as u64).and_then(|s| s.checked_add(extra_secs))
477         {
478             debug_assert!(nanos < NANOS_PER_SEC);
479             Some(Duration { secs, nanos })
480         } else {
481             None
482         }
483     }
484
485     /// Checked `Duration` division. Computes `self / other`, returning [`None`]
486     /// if `other == 0`.
487     ///
488     /// [`None`]: ../../std/option/enum.Option.html#variant.None
489     ///
490     /// # Examples
491     ///
492     /// Basic usage:
493     ///
494     /// ```
495     /// use std::time::Duration;
496     ///
497     /// assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0)));
498     /// assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000)));
499     /// assert_eq!(Duration::new(2, 0).checked_div(0), None);
500     /// ```
501     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
502     #[inline]
503     pub fn checked_div(self, rhs: u32) -> Option<Duration> {
504         if rhs != 0 {
505             let secs = self.secs / (rhs as u64);
506             let carry = self.secs - secs * (rhs as u64);
507             let extra_nanos = carry * (NANOS_PER_SEC as u64) / (rhs as u64);
508             let nanos = self.nanos / rhs + (extra_nanos as u32);
509             debug_assert!(nanos < NANOS_PER_SEC);
510             Some(Duration { secs, nanos })
511         } else {
512             None
513         }
514     }
515
516     /// Returns the number of seconds contained by this `Duration` as `f64`.
517     ///
518     /// The returned value does include the fractional (nanosecond) part of the duration.
519     ///
520     /// # Examples
521     /// ```
522     /// use std::time::Duration;
523     ///
524     /// let dur = Duration::new(2, 700_000_000);
525     /// assert_eq!(dur.as_secs_f64(), 2.7);
526     /// ```
527     #[stable(feature = "duration_float", since = "1.38.0")]
528     #[inline]
529     pub fn as_secs_f64(&self) -> f64 {
530         (self.secs as f64) + (self.nanos as f64) / (NANOS_PER_SEC as f64)
531     }
532
533     /// Returns the number of seconds contained by this `Duration` as `f32`.
534     ///
535     /// The returned value does include the fractional (nanosecond) part of the duration.
536     ///
537     /// # Examples
538     /// ```
539     /// use std::time::Duration;
540     ///
541     /// let dur = Duration::new(2, 700_000_000);
542     /// assert_eq!(dur.as_secs_f32(), 2.7);
543     /// ```
544     #[stable(feature = "duration_float", since = "1.38.0")]
545     #[inline]
546     pub fn as_secs_f32(&self) -> f32 {
547         (self.secs as f32) + (self.nanos as f32) / (NANOS_PER_SEC as f32)
548     }
549
550     /// Creates a new `Duration` from the specified number of seconds represented
551     /// as `f64`.
552     ///
553     /// # Panics
554     /// This constructor will panic if `secs` is not finite, negative or overflows `Duration`.
555     ///
556     /// # Examples
557     /// ```
558     /// use std::time::Duration;
559     ///
560     /// let dur = Duration::from_secs_f64(2.7);
561     /// assert_eq!(dur, Duration::new(2, 700_000_000));
562     /// ```
563     #[stable(feature = "duration_float", since = "1.38.0")]
564     #[inline]
565     pub fn from_secs_f64(secs: f64) -> Duration {
566         const MAX_NANOS_F64: f64 = ((u64::MAX as u128 + 1) * (NANOS_PER_SEC as u128)) as f64;
567         let nanos = secs * (NANOS_PER_SEC as f64);
568         if !nanos.is_finite() {
569             panic!("got non-finite value when converting float to duration");
570         }
571         if nanos >= MAX_NANOS_F64 {
572             panic!("overflow when converting float to duration");
573         }
574         if nanos < 0.0 {
575             panic!("underflow when converting float to duration");
576         }
577         let nanos = nanos as u128;
578         Duration {
579             secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
580             nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
581         }
582     }
583
584     /// Creates a new `Duration` from the specified number of seconds represented
585     /// as `f32`.
586     ///
587     /// # Panics
588     /// This constructor will panic if `secs` is not finite, negative or overflows `Duration`.
589     ///
590     /// # Examples
591     /// ```
592     /// use std::time::Duration;
593     ///
594     /// let dur = Duration::from_secs_f32(2.7);
595     /// assert_eq!(dur, Duration::new(2, 700_000_000));
596     /// ```
597     #[stable(feature = "duration_float", since = "1.38.0")]
598     #[inline]
599     pub fn from_secs_f32(secs: f32) -> Duration {
600         const MAX_NANOS_F32: f32 = ((u64::MAX as u128 + 1) * (NANOS_PER_SEC as u128)) as f32;
601         let nanos = secs * (NANOS_PER_SEC as f32);
602         if !nanos.is_finite() {
603             panic!("got non-finite value when converting float to duration");
604         }
605         if nanos >= MAX_NANOS_F32 {
606             panic!("overflow when converting float to duration");
607         }
608         if nanos < 0.0 {
609             panic!("underflow when converting float to duration");
610         }
611         let nanos = nanos as u128;
612         Duration {
613             secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
614             nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
615         }
616     }
617
618     /// Multiplies `Duration` by `f64`.
619     ///
620     /// # Panics
621     /// This method will panic if result is not finite, negative or overflows `Duration`.
622     ///
623     /// # Examples
624     /// ```
625     /// use std::time::Duration;
626     ///
627     /// let dur = Duration::new(2, 700_000_000);
628     /// assert_eq!(dur.mul_f64(3.14), Duration::new(8, 478_000_000));
629     /// assert_eq!(dur.mul_f64(3.14e5), Duration::new(847_800, 0));
630     /// ```
631     #[stable(feature = "duration_float", since = "1.38.0")]
632     #[inline]
633     pub fn mul_f64(self, rhs: f64) -> Duration {
634         Duration::from_secs_f64(rhs * self.as_secs_f64())
635     }
636
637     /// Multiplies `Duration` by `f32`.
638     ///
639     /// # Panics
640     /// This method will panic if result is not finite, negative or overflows `Duration`.
641     ///
642     /// # Examples
643     /// ```
644     /// use std::time::Duration;
645     ///
646     /// let dur = Duration::new(2, 700_000_000);
647     /// // note that due to rounding errors result is slightly different
648     /// // from 8.478 and 847800.0
649     /// assert_eq!(dur.mul_f32(3.14), Duration::new(8, 478_000_640));
650     /// assert_eq!(dur.mul_f32(3.14e5), Duration::new(847799, 969_120_256));
651     /// ```
652     #[stable(feature = "duration_float", since = "1.38.0")]
653     #[inline]
654     pub fn mul_f32(self, rhs: f32) -> Duration {
655         Duration::from_secs_f32(rhs * self.as_secs_f32())
656     }
657
658     /// Divide `Duration` by `f64`.
659     ///
660     /// # Panics
661     /// This method will panic if result is not finite, negative or overflows `Duration`.
662     ///
663     /// # Examples
664     /// ```
665     /// use std::time::Duration;
666     ///
667     /// let dur = Duration::new(2, 700_000_000);
668     /// assert_eq!(dur.div_f64(3.14), Duration::new(0, 859_872_611));
669     /// // note that truncation is used, not rounding
670     /// assert_eq!(dur.div_f64(3.14e5), Duration::new(0, 8_598));
671     /// ```
672     #[stable(feature = "duration_float", since = "1.38.0")]
673     #[inline]
674     pub fn div_f64(self, rhs: f64) -> Duration {
675         Duration::from_secs_f64(self.as_secs_f64() / rhs)
676     }
677
678     /// Divide `Duration` by `f32`.
679     ///
680     /// # Panics
681     /// This method will panic if result is not finite, negative or overflows `Duration`.
682     ///
683     /// # Examples
684     /// ```
685     /// use std::time::Duration;
686     ///
687     /// let dur = Duration::new(2, 700_000_000);
688     /// // note that due to rounding errors result is slightly
689     /// // different from 0.859_872_611
690     /// assert_eq!(dur.div_f32(3.14), Duration::new(0, 859_872_576));
691     /// // note that truncation is used, not rounding
692     /// assert_eq!(dur.div_f32(3.14e5), Duration::new(0, 8_598));
693     /// ```
694     #[stable(feature = "duration_float", since = "1.38.0")]
695     #[inline]
696     pub fn div_f32(self, rhs: f32) -> Duration {
697         Duration::from_secs_f32(self.as_secs_f32() / rhs)
698     }
699
700     /// Divide `Duration` by `Duration` and return `f64`.
701     ///
702     /// # Examples
703     /// ```
704     /// #![feature(div_duration)]
705     /// use std::time::Duration;
706     ///
707     /// let dur1 = Duration::new(2, 700_000_000);
708     /// let dur2 = Duration::new(5, 400_000_000);
709     /// assert_eq!(dur1.div_duration_f64(dur2), 0.5);
710     /// ```
711     #[unstable(feature = "div_duration", issue = "63139")]
712     #[inline]
713     pub fn div_duration_f64(self, rhs: Duration) -> f64 {
714         self.as_secs_f64() / rhs.as_secs_f64()
715     }
716
717     /// Divide `Duration` by `Duration` and return `f32`.
718     ///
719     /// # Examples
720     /// ```
721     /// #![feature(div_duration)]
722     /// use std::time::Duration;
723     ///
724     /// let dur1 = Duration::new(2, 700_000_000);
725     /// let dur2 = Duration::new(5, 400_000_000);
726     /// assert_eq!(dur1.div_duration_f32(dur2), 0.5);
727     /// ```
728     #[unstable(feature = "div_duration", issue = "63139")]
729     #[inline]
730     pub fn div_duration_f32(self, rhs: Duration) -> f32 {
731         self.as_secs_f32() / rhs.as_secs_f32()
732     }
733 }
734
735 #[stable(feature = "duration", since = "1.3.0")]
736 impl Add for Duration {
737     type Output = Duration;
738
739     fn add(self, rhs: Duration) -> Duration {
740         self.checked_add(rhs).expect("overflow when adding durations")
741     }
742 }
743
744 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
745 impl AddAssign for Duration {
746     fn add_assign(&mut self, rhs: Duration) {
747         *self = *self + rhs;
748     }
749 }
750
751 #[stable(feature = "duration", since = "1.3.0")]
752 impl Sub for Duration {
753     type Output = Duration;
754
755     fn sub(self, rhs: Duration) -> Duration {
756         self.checked_sub(rhs).expect("overflow when subtracting durations")
757     }
758 }
759
760 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
761 impl SubAssign for Duration {
762     fn sub_assign(&mut self, rhs: Duration) {
763         *self = *self - rhs;
764     }
765 }
766
767 #[stable(feature = "duration", since = "1.3.0")]
768 impl Mul<u32> for Duration {
769     type Output = Duration;
770
771     fn mul(self, rhs: u32) -> Duration {
772         self.checked_mul(rhs).expect("overflow when multiplying duration by scalar")
773     }
774 }
775
776 #[stable(feature = "symmetric_u32_duration_mul", since = "1.31.0")]
777 impl Mul<Duration> for u32 {
778     type Output = Duration;
779
780     fn mul(self, rhs: Duration) -> Duration {
781         rhs * self
782     }
783 }
784
785 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
786 impl MulAssign<u32> for Duration {
787     fn mul_assign(&mut self, rhs: u32) {
788         *self = *self * rhs;
789     }
790 }
791
792 #[stable(feature = "duration", since = "1.3.0")]
793 impl Div<u32> for Duration {
794     type Output = Duration;
795
796     fn div(self, rhs: u32) -> Duration {
797         self.checked_div(rhs).expect("divide by zero error when dividing duration by scalar")
798     }
799 }
800
801 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
802 impl DivAssign<u32> for Duration {
803     fn div_assign(&mut self, rhs: u32) {
804         *self = *self / rhs;
805     }
806 }
807
808 macro_rules! sum_durations {
809     ($iter:expr) => {{
810         let mut total_secs: u64 = 0;
811         let mut total_nanos: u64 = 0;
812
813         for entry in $iter {
814             total_secs =
815                 total_secs.checked_add(entry.secs).expect("overflow in iter::sum over durations");
816             total_nanos = match total_nanos.checked_add(entry.nanos as u64) {
817                 Some(n) => n,
818                 None => {
819                     total_secs = total_secs
820                         .checked_add(total_nanos / NANOS_PER_SEC as u64)
821                         .expect("overflow in iter::sum over durations");
822                     (total_nanos % NANOS_PER_SEC as u64) + entry.nanos as u64
823                 }
824             };
825         }
826         total_secs = total_secs
827             .checked_add(total_nanos / NANOS_PER_SEC as u64)
828             .expect("overflow in iter::sum over durations");
829         total_nanos = total_nanos % NANOS_PER_SEC as u64;
830         Duration { secs: total_secs, nanos: total_nanos as u32 }
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| crate::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                 // SAFETY: 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 { crate::str::from_utf8_unchecked(&buf[..end]) };
934
935                 // If the user request a precision > 9, we pad '0's at the end.
936                 let w = f.precision().unwrap_or(pos);
937                 write!(f, "{}.{:0<width$}", integer_part, s, width = w)
938             }
939         }
940
941         // Print leading '+' sign if requested
942         if f.sign_plus() {
943             write!(f, "+")?;
944         }
945
946         if self.secs > 0 {
947             fmt_decimal(f, self.secs, self.nanos, 100_000_000)?;
948             f.write_str("s")
949         } else if self.nanos >= 1_000_000 {
950             fmt_decimal(f, self.nanos as u64 / 1_000_000, self.nanos % 1_000_000, 100_000)?;
951             f.write_str("ms")
952         } else if self.nanos >= 1_000 {
953             fmt_decimal(f, self.nanos as u64 / 1_000, self.nanos % 1_000, 100)?;
954             f.write_str("µs")
955         } else {
956             fmt_decimal(f, self.nanos as u64, 0, 1)?;
957             f.write_str("ns")
958         }
959     }
960 }