]> git.lizzy.rs Git - rust.git/blob - src/libcore/time.rs
Rollup merge of #72600 - Aaron1011:fix/anon-const-encoding, r=varkor
[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::fmt;
16 use crate::iter::Sum;
17 use crate::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
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_const_stable(feature = "duration_consts", since = "1.32.0")]
156     pub const fn from_secs(secs: u64) -> Duration {
157         Duration { secs, nanos: 0 }
158     }
159
160     /// Creates a new `Duration` from the specified number of milliseconds.
161     ///
162     /// # Examples
163     ///
164     /// ```
165     /// use std::time::Duration;
166     ///
167     /// let duration = Duration::from_millis(2569);
168     ///
169     /// assert_eq!(2, duration.as_secs());
170     /// assert_eq!(569_000_000, duration.subsec_nanos());
171     /// ```
172     #[stable(feature = "duration", since = "1.3.0")]
173     #[inline]
174     #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
175     pub const fn from_millis(millis: u64) -> Duration {
176         Duration {
177             secs: millis / MILLIS_PER_SEC,
178             nanos: ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI,
179         }
180     }
181
182     /// Creates a new `Duration` from the specified number of microseconds.
183     ///
184     /// # Examples
185     ///
186     /// ```
187     /// use std::time::Duration;
188     ///
189     /// let duration = Duration::from_micros(1_000_002);
190     ///
191     /// assert_eq!(1, duration.as_secs());
192     /// assert_eq!(2000, duration.subsec_nanos());
193     /// ```
194     #[stable(feature = "duration_from_micros", since = "1.27.0")]
195     #[inline]
196     #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
197     pub const fn from_micros(micros: u64) -> Duration {
198         Duration {
199             secs: micros / MICROS_PER_SEC,
200             nanos: ((micros % MICROS_PER_SEC) as u32) * NANOS_PER_MICRO,
201         }
202     }
203
204     /// Creates a new `Duration` from the specified number of nanoseconds.
205     ///
206     /// # Examples
207     ///
208     /// ```
209     /// use std::time::Duration;
210     ///
211     /// let duration = Duration::from_nanos(1_000_000_123);
212     ///
213     /// assert_eq!(1, duration.as_secs());
214     /// assert_eq!(123, duration.subsec_nanos());
215     /// ```
216     #[stable(feature = "duration_extras", since = "1.27.0")]
217     #[inline]
218     #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
219     pub const fn from_nanos(nanos: u64) -> Duration {
220         Duration {
221             secs: nanos / (NANOS_PER_SEC as u64),
222             nanos: (nanos % (NANOS_PER_SEC as u64)) as u32,
223         }
224     }
225
226     /// Returns the number of _whole_ seconds contained by this `Duration`.
227     ///
228     /// The returned value does not include the fractional (nanosecond) part of the
229     /// duration, which can be obtained using [`subsec_nanos`].
230     ///
231     /// # Examples
232     ///
233     /// ```
234     /// use std::time::Duration;
235     ///
236     /// let duration = Duration::new(5, 730023852);
237     /// assert_eq!(duration.as_secs(), 5);
238     /// ```
239     ///
240     /// To determine the total number of seconds represented by the `Duration`,
241     /// use `as_secs` in combination with [`subsec_nanos`]:
242     ///
243     /// ```
244     /// use std::time::Duration;
245     ///
246     /// let duration = Duration::new(5, 730023852);
247     ///
248     /// assert_eq!(5.730023852,
249     ///            duration.as_secs() as f64
250     ///            + duration.subsec_nanos() as f64 * 1e-9);
251     /// ```
252     ///
253     /// [`subsec_nanos`]: #method.subsec_nanos
254     #[stable(feature = "duration", since = "1.3.0")]
255     #[rustc_const_stable(feature = "duration", since = "1.32.0")]
256     #[inline]
257     pub const fn as_secs(&self) -> u64 {
258         self.secs
259     }
260
261     /// Returns the fractional part of this `Duration`, in whole milliseconds.
262     ///
263     /// This method does **not** return the length of the duration when
264     /// represented by milliseconds. The returned number always represents a
265     /// fractional portion of a second (i.e., it is less than one thousand).
266     ///
267     /// # Examples
268     ///
269     /// ```
270     /// use std::time::Duration;
271     ///
272     /// let duration = Duration::from_millis(5432);
273     /// assert_eq!(duration.as_secs(), 5);
274     /// assert_eq!(duration.subsec_millis(), 432);
275     /// ```
276     #[stable(feature = "duration_extras", since = "1.27.0")]
277     #[rustc_const_stable(feature = "duration_extras", since = "1.32.0")]
278     #[inline]
279     pub const fn subsec_millis(&self) -> u32 {
280         self.nanos / NANOS_PER_MILLI
281     }
282
283     /// Returns the fractional part of this `Duration`, in whole microseconds.
284     ///
285     /// This method does **not** return the length of the duration when
286     /// represented by microseconds. The returned number always represents a
287     /// fractional portion of a second (i.e., it is less than one million).
288     ///
289     /// # Examples
290     ///
291     /// ```
292     /// use std::time::Duration;
293     ///
294     /// let duration = Duration::from_micros(1_234_567);
295     /// assert_eq!(duration.as_secs(), 1);
296     /// assert_eq!(duration.subsec_micros(), 234_567);
297     /// ```
298     #[stable(feature = "duration_extras", since = "1.27.0")]
299     #[rustc_const_stable(feature = "duration_extras", since = "1.32.0")]
300     #[inline]
301     pub const fn subsec_micros(&self) -> u32 {
302         self.nanos / NANOS_PER_MICRO
303     }
304
305     /// Returns the fractional part of this `Duration`, in nanoseconds.
306     ///
307     /// This method does **not** return the length of the duration when
308     /// represented by nanoseconds. The returned number always represents a
309     /// fractional portion of a second (i.e., it is less than one billion).
310     ///
311     /// # Examples
312     ///
313     /// ```
314     /// use std::time::Duration;
315     ///
316     /// let duration = Duration::from_millis(5010);
317     /// assert_eq!(duration.as_secs(), 5);
318     /// assert_eq!(duration.subsec_nanos(), 10_000_000);
319     /// ```
320     #[stable(feature = "duration", since = "1.3.0")]
321     #[rustc_const_stable(feature = "duration", since = "1.32.0")]
322     #[inline]
323     pub const fn subsec_nanos(&self) -> u32 {
324         self.nanos
325     }
326
327     /// Returns the total number of whole milliseconds contained by this `Duration`.
328     ///
329     /// # Examples
330     ///
331     /// ```
332     /// use std::time::Duration;
333     ///
334     /// let duration = Duration::new(5, 730023852);
335     /// assert_eq!(duration.as_millis(), 5730);
336     /// ```
337     #[stable(feature = "duration_as_u128", since = "1.33.0")]
338     #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
339     #[inline]
340     pub const fn as_millis(&self) -> u128 {
341         self.secs as u128 * MILLIS_PER_SEC as u128 + (self.nanos / NANOS_PER_MILLI) as u128
342     }
343
344     /// Returns the total number of whole microseconds contained by this `Duration`.
345     ///
346     /// # Examples
347     ///
348     /// ```
349     /// use std::time::Duration;
350     ///
351     /// let duration = Duration::new(5, 730023852);
352     /// assert_eq!(duration.as_micros(), 5730023);
353     /// ```
354     #[stable(feature = "duration_as_u128", since = "1.33.0")]
355     #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
356     #[inline]
357     pub const fn as_micros(&self) -> u128 {
358         self.secs as u128 * MICROS_PER_SEC as u128 + (self.nanos / NANOS_PER_MICRO) as u128
359     }
360
361     /// Returns the total number of nanoseconds contained by this `Duration`.
362     ///
363     /// # Examples
364     ///
365     /// ```
366     /// use std::time::Duration;
367     ///
368     /// let duration = Duration::new(5, 730023852);
369     /// assert_eq!(duration.as_nanos(), 5730023852);
370     /// ```
371     #[stable(feature = "duration_as_u128", since = "1.33.0")]
372     #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
373     #[inline]
374     pub const fn as_nanos(&self) -> u128 {
375         self.secs as u128 * NANOS_PER_SEC as u128 + self.nanos as u128
376     }
377
378     /// Checked `Duration` addition. Computes `self + other`, returning [`None`]
379     /// if overflow occurred.
380     ///
381     /// [`None`]: ../../std/option/enum.Option.html#variant.None
382     ///
383     /// # Examples
384     ///
385     /// Basic usage:
386     ///
387     /// ```
388     /// use std::time::Duration;
389     ///
390     /// assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1)));
391     /// assert_eq!(Duration::new(1, 0).checked_add(Duration::new(u64::MAX, 0)), None);
392     /// ```
393     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
394     #[inline]
395     pub fn checked_add(self, rhs: Duration) -> Option<Duration> {
396         if let Some(mut secs) = self.secs.checked_add(rhs.secs) {
397             let mut nanos = self.nanos + rhs.nanos;
398             if nanos >= NANOS_PER_SEC {
399                 nanos -= NANOS_PER_SEC;
400                 if let Some(new_secs) = secs.checked_add(1) {
401                     secs = new_secs;
402                 } else {
403                     return None;
404                 }
405             }
406             debug_assert!(nanos < NANOS_PER_SEC);
407             Some(Duration { secs, nanos })
408         } else {
409             None
410         }
411     }
412
413     /// Checked `Duration` subtraction. Computes `self - other`, returning [`None`]
414     /// if the result would be negative or if overflow occurred.
415     ///
416     /// [`None`]: ../../std/option/enum.Option.html#variant.None
417     ///
418     /// # Examples
419     ///
420     /// Basic usage:
421     ///
422     /// ```
423     /// use std::time::Duration;
424     ///
425     /// assert_eq!(Duration::new(0, 1).checked_sub(Duration::new(0, 0)), Some(Duration::new(0, 1)));
426     /// assert_eq!(Duration::new(0, 0).checked_sub(Duration::new(0, 1)), None);
427     /// ```
428     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
429     #[inline]
430     pub fn checked_sub(self, rhs: Duration) -> Option<Duration> {
431         if let Some(mut secs) = self.secs.checked_sub(rhs.secs) {
432             let nanos = if self.nanos >= rhs.nanos {
433                 self.nanos - rhs.nanos
434             } else {
435                 if let Some(sub_secs) = secs.checked_sub(1) {
436                     secs = sub_secs;
437                     self.nanos + NANOS_PER_SEC - rhs.nanos
438                 } else {
439                     return None;
440                 }
441             };
442             debug_assert!(nanos < NANOS_PER_SEC);
443             Some(Duration { secs, nanos })
444         } else {
445             None
446         }
447     }
448
449     /// Checked `Duration` multiplication. Computes `self * other`, returning
450     /// [`None`] if overflow occurred.
451     ///
452     /// [`None`]: ../../std/option/enum.Option.html#variant.None
453     ///
454     /// # Examples
455     ///
456     /// Basic usage:
457     ///
458     /// ```
459     /// use std::time::Duration;
460     ///
461     /// assert_eq!(Duration::new(0, 500_000_001).checked_mul(2), Some(Duration::new(1, 2)));
462     /// assert_eq!(Duration::new(u64::MAX - 1, 0).checked_mul(2), None);
463     /// ```
464     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
465     #[inline]
466     pub fn checked_mul(self, rhs: u32) -> Option<Duration> {
467         // Multiply nanoseconds as u64, because it cannot overflow that way.
468         let total_nanos = self.nanos as u64 * rhs as u64;
469         let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
470         let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
471         if let Some(secs) =
472             self.secs.checked_mul(rhs as u64).and_then(|s| s.checked_add(extra_secs))
473         {
474             debug_assert!(nanos < NANOS_PER_SEC);
475             Some(Duration { secs, nanos })
476         } else {
477             None
478         }
479     }
480
481     /// Checked `Duration` division. Computes `self / other`, returning [`None`]
482     /// if `other == 0`.
483     ///
484     /// [`None`]: ../../std/option/enum.Option.html#variant.None
485     ///
486     /// # Examples
487     ///
488     /// Basic usage:
489     ///
490     /// ```
491     /// use std::time::Duration;
492     ///
493     /// assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0)));
494     /// assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000)));
495     /// assert_eq!(Duration::new(2, 0).checked_div(0), None);
496     /// ```
497     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
498     #[inline]
499     pub fn checked_div(self, rhs: u32) -> Option<Duration> {
500         if rhs != 0 {
501             let secs = self.secs / (rhs as u64);
502             let carry = self.secs - secs * (rhs as u64);
503             let extra_nanos = carry * (NANOS_PER_SEC as u64) / (rhs as u64);
504             let nanos = self.nanos / rhs + (extra_nanos as u32);
505             debug_assert!(nanos < NANOS_PER_SEC);
506             Some(Duration { secs, nanos })
507         } else {
508             None
509         }
510     }
511
512     /// Returns the number of seconds contained by this `Duration` as `f64`.
513     ///
514     /// The returned value does include the fractional (nanosecond) part of the duration.
515     ///
516     /// # Examples
517     /// ```
518     /// use std::time::Duration;
519     ///
520     /// let dur = Duration::new(2, 700_000_000);
521     /// assert_eq!(dur.as_secs_f64(), 2.7);
522     /// ```
523     #[stable(feature = "duration_float", since = "1.38.0")]
524     #[inline]
525     pub fn as_secs_f64(&self) -> f64 {
526         (self.secs as f64) + (self.nanos as f64) / (NANOS_PER_SEC as f64)
527     }
528
529     /// Returns the number of seconds contained by this `Duration` as `f32`.
530     ///
531     /// The returned value does include the fractional (nanosecond) part of the duration.
532     ///
533     /// # Examples
534     /// ```
535     /// use std::time::Duration;
536     ///
537     /// let dur = Duration::new(2, 700_000_000);
538     /// assert_eq!(dur.as_secs_f32(), 2.7);
539     /// ```
540     #[stable(feature = "duration_float", since = "1.38.0")]
541     #[inline]
542     pub fn as_secs_f32(&self) -> f32 {
543         (self.secs as f32) + (self.nanos as f32) / (NANOS_PER_SEC as f32)
544     }
545
546     /// Creates a new `Duration` from the specified number of seconds represented
547     /// as `f64`.
548     ///
549     /// # Panics
550     /// This constructor will panic if `secs` is not finite, negative or overflows `Duration`.
551     ///
552     /// # Examples
553     /// ```
554     /// use std::time::Duration;
555     ///
556     /// let dur = Duration::from_secs_f64(2.7);
557     /// assert_eq!(dur, Duration::new(2, 700_000_000));
558     /// ```
559     #[stable(feature = "duration_float", since = "1.38.0")]
560     #[inline]
561     pub fn from_secs_f64(secs: f64) -> Duration {
562         const MAX_NANOS_F64: f64 = ((u64::MAX as u128 + 1) * (NANOS_PER_SEC as u128)) as f64;
563         let nanos = secs * (NANOS_PER_SEC as f64);
564         if !nanos.is_finite() {
565             panic!("got non-finite value when converting float to duration");
566         }
567         if nanos >= MAX_NANOS_F64 {
568             panic!("overflow when converting float to duration");
569         }
570         if nanos < 0.0 {
571             panic!("underflow when converting float to duration");
572         }
573         let nanos = nanos as u128;
574         Duration {
575             secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
576             nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
577         }
578     }
579
580     /// Creates a new `Duration` from the specified number of seconds represented
581     /// as `f32`.
582     ///
583     /// # Panics
584     /// This constructor will panic if `secs` is not finite, negative or overflows `Duration`.
585     ///
586     /// # Examples
587     /// ```
588     /// use std::time::Duration;
589     ///
590     /// let dur = Duration::from_secs_f32(2.7);
591     /// assert_eq!(dur, Duration::new(2, 700_000_000));
592     /// ```
593     #[stable(feature = "duration_float", since = "1.38.0")]
594     #[inline]
595     pub fn from_secs_f32(secs: f32) -> Duration {
596         const MAX_NANOS_F32: f32 = ((u64::MAX as u128 + 1) * (NANOS_PER_SEC as u128)) as f32;
597         let nanos = secs * (NANOS_PER_SEC as f32);
598         if !nanos.is_finite() {
599             panic!("got non-finite value when converting float to duration");
600         }
601         if nanos >= MAX_NANOS_F32 {
602             panic!("overflow when converting float to duration");
603         }
604         if nanos < 0.0 {
605             panic!("underflow when converting float to duration");
606         }
607         let nanos = nanos as u128;
608         Duration {
609             secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
610             nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
611         }
612     }
613
614     /// Multiplies `Duration` by `f64`.
615     ///
616     /// # Panics
617     /// This method will panic if result is not finite, negative or overflows `Duration`.
618     ///
619     /// # Examples
620     /// ```
621     /// use std::time::Duration;
622     ///
623     /// let dur = Duration::new(2, 700_000_000);
624     /// assert_eq!(dur.mul_f64(3.14), Duration::new(8, 478_000_000));
625     /// assert_eq!(dur.mul_f64(3.14e5), Duration::new(847_800, 0));
626     /// ```
627     #[stable(feature = "duration_float", since = "1.38.0")]
628     #[inline]
629     pub fn mul_f64(self, rhs: f64) -> Duration {
630         Duration::from_secs_f64(rhs * self.as_secs_f64())
631     }
632
633     /// Multiplies `Duration` by `f32`.
634     ///
635     /// # Panics
636     /// This method will panic if result is not finite, negative or overflows `Duration`.
637     ///
638     /// # Examples
639     /// ```
640     /// use std::time::Duration;
641     ///
642     /// let dur = Duration::new(2, 700_000_000);
643     /// // note that due to rounding errors result is slightly different
644     /// // from 8.478 and 847800.0
645     /// assert_eq!(dur.mul_f32(3.14), Duration::new(8, 478_000_640));
646     /// assert_eq!(dur.mul_f32(3.14e5), Duration::new(847799, 969_120_256));
647     /// ```
648     #[stable(feature = "duration_float", since = "1.38.0")]
649     #[inline]
650     pub fn mul_f32(self, rhs: f32) -> Duration {
651         Duration::from_secs_f32(rhs * self.as_secs_f32())
652     }
653
654     /// Divide `Duration` by `f64`.
655     ///
656     /// # Panics
657     /// This method will panic if result is not finite, negative or overflows `Duration`.
658     ///
659     /// # Examples
660     /// ```
661     /// use std::time::Duration;
662     ///
663     /// let dur = Duration::new(2, 700_000_000);
664     /// assert_eq!(dur.div_f64(3.14), Duration::new(0, 859_872_611));
665     /// // note that truncation is used, not rounding
666     /// assert_eq!(dur.div_f64(3.14e5), Duration::new(0, 8_598));
667     /// ```
668     #[stable(feature = "duration_float", since = "1.38.0")]
669     #[inline]
670     pub fn div_f64(self, rhs: f64) -> Duration {
671         Duration::from_secs_f64(self.as_secs_f64() / rhs)
672     }
673
674     /// Divide `Duration` by `f32`.
675     ///
676     /// # Panics
677     /// This method will panic if result is not finite, negative or overflows `Duration`.
678     ///
679     /// # Examples
680     /// ```
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     #[stable(feature = "duration_float", since = "1.38.0")]
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(div_duration)]
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 = "div_duration", issue = "63139")]
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(div_duration)]
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 = "div_duration", issue = "63139")]
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 =
811                 total_secs.checked_add(entry.secs).expect("overflow in iter::sum over durations");
812             total_nanos = match total_nanos.checked_add(entry.nanos as u64) {
813                 Some(n) => n,
814                 None => {
815                     total_secs = total_secs
816                         .checked_add(total_nanos / NANOS_PER_SEC as u64)
817                         .expect("overflow in iter::sum over durations");
818                     (total_nanos % NANOS_PER_SEC as u64) + entry.nanos as u64
819                 }
820             };
821         }
822         total_secs = total_secs
823             .checked_add(total_nanos / NANOS_PER_SEC as u64)
824             .expect("overflow in iter::sum over durations");
825         total_nanos = total_nanos % NANOS_PER_SEC as u64;
826         Duration { secs: total_secs, nanos: total_nanos as u32 }
827     }};
828 }
829
830 #[stable(feature = "duration_sum", since = "1.16.0")]
831 impl Sum for Duration {
832     fn sum<I: Iterator<Item = Duration>>(iter: I) -> Duration {
833         sum_durations!(iter)
834     }
835 }
836
837 #[stable(feature = "duration_sum", since = "1.16.0")]
838 impl<'a> Sum<&'a Duration> for Duration {
839     fn sum<I: Iterator<Item = &'a Duration>>(iter: I) -> Duration {
840         sum_durations!(iter)
841     }
842 }
843
844 #[stable(feature = "duration_debug_impl", since = "1.27.0")]
845 impl fmt::Debug for Duration {
846     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
847         /// Formats a floating point number in decimal notation.
848         ///
849         /// The number is given as the `integer_part` and a fractional part.
850         /// The value of the fractional part is `fractional_part / divisor`. So
851         /// `integer_part` = 3, `fractional_part` = 12 and `divisor` = 100
852         /// represents the number `3.012`. Trailing zeros are omitted.
853         ///
854         /// `divisor` must not be above 100_000_000. It also should be a power
855         /// of 10, everything else doesn't make sense. `fractional_part` has
856         /// to be less than `10 * divisor`!
857         fn fmt_decimal(
858             f: &mut fmt::Formatter<'_>,
859             mut integer_part: u64,
860             mut fractional_part: u32,
861             mut divisor: u32,
862         ) -> fmt::Result {
863             // Encode the fractional part into a temporary buffer. The buffer
864             // only need to hold 9 elements, because `fractional_part` has to
865             // be smaller than 10^9. The buffer is prefilled with '0' digits
866             // to simplify the code below.
867             let mut buf = [b'0'; 9];
868
869             // The next digit is written at this position
870             let mut pos = 0;
871
872             // We keep writing digits into the buffer while there are non-zero
873             // digits left and we haven't written enough digits yet.
874             while fractional_part > 0 && pos < f.precision().unwrap_or(9) {
875                 // Write new digit into the buffer
876                 buf[pos] = b'0' + (fractional_part / divisor) as u8;
877
878                 fractional_part %= divisor;
879                 divisor /= 10;
880                 pos += 1;
881             }
882
883             // If a precision < 9 was specified, there may be some non-zero
884             // digits left that weren't written into the buffer. In that case we
885             // need to perform rounding to match the semantics of printing
886             // normal floating point numbers. However, we only need to do work
887             // when rounding up. This happens if the first digit of the
888             // remaining ones is >= 5.
889             if fractional_part > 0 && fractional_part >= divisor * 5 {
890                 // Round up the number contained in the buffer. We go through
891                 // the buffer backwards and keep track of the carry.
892                 let mut rev_pos = pos;
893                 let mut carry = true;
894                 while carry && rev_pos > 0 {
895                     rev_pos -= 1;
896
897                     // If the digit in the buffer is not '9', we just need to
898                     // increment it and can stop then (since we don't have a
899                     // carry anymore). Otherwise, we set it to '0' (overflow)
900                     // and continue.
901                     if buf[rev_pos] < b'9' {
902                         buf[rev_pos] += 1;
903                         carry = false;
904                     } else {
905                         buf[rev_pos] = b'0';
906                     }
907                 }
908
909                 // If we still have the carry bit set, that means that we set
910                 // the whole buffer to '0's and need to increment the integer
911                 // part.
912                 if carry {
913                     integer_part += 1;
914                 }
915             }
916
917             // Determine the end of the buffer: if precision is set, we just
918             // use as many digits from the buffer (capped to 9). If it isn't
919             // set, we only use all digits up to the last non-zero one.
920             let end = f.precision().map(|p| crate::cmp::min(p, 9)).unwrap_or(pos);
921
922             // If we haven't emitted a single fractional digit and the precision
923             // wasn't set to a non-zero value, we don't print the decimal point.
924             if end == 0 {
925                 write!(f, "{}", integer_part)
926             } else {
927                 // SAFETY: We are only writing ASCII digits into the buffer and it was
928                 // initialized with '0's, so it contains valid UTF8.
929                 let s = unsafe { crate::str::from_utf8_unchecked(&buf[..end]) };
930
931                 // If the user request a precision > 9, we pad '0's at the end.
932                 let w = f.precision().unwrap_or(pos);
933                 write!(f, "{}.{:0<width$}", integer_part, s, width = w)
934             }
935         }
936
937         // Print leading '+' sign if requested
938         if f.sign_plus() {
939             write!(f, "+")?;
940         }
941
942         if self.secs > 0 {
943             fmt_decimal(f, self.secs, self.nanos, 100_000_000)?;
944             f.write_str("s")
945         } else if self.nanos >= 1_000_000 {
946             fmt_decimal(f, self.nanos as u64 / 1_000_000, self.nanos % 1_000_000, 100_000)?;
947             f.write_str("ms")
948         } else if self.nanos >= 1_000 {
949             fmt_decimal(f, self.nanos as u64 / 1_000, self.nanos % 1_000, 100)?;
950             f.write_str("µs")
951         } else {
952             fmt_decimal(f, self.nanos as u64, 0, 1)?;
953             f.write_str("ns")
954         }
955     }
956 }