]> git.lizzy.rs Git - rust.git/blob - src/libcore/time.rs
Rollup merge of #66341 - crgl:vec-deque-extend, r=Amanieu
[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     pub fn new(secs: u64, nanos: u32) -> Duration {
134         let secs =
135             secs.checked_add((nanos / NANOS_PER_SEC) as u64).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 {
256         self.secs
257     }
258
259     /// Returns the fractional part of this `Duration`, in whole milliseconds.
260     ///
261     /// This method does **not** return the length of the duration when
262     /// represented by milliseconds. The returned number always represents a
263     /// fractional portion of a second (i.e., it is less than one thousand).
264     ///
265     /// # Examples
266     ///
267     /// ```
268     /// use std::time::Duration;
269     ///
270     /// let duration = Duration::from_millis(5432);
271     /// assert_eq!(duration.as_secs(), 5);
272     /// assert_eq!(duration.subsec_millis(), 432);
273     /// ```
274     #[stable(feature = "duration_extras", since = "1.27.0")]
275     #[inline]
276     pub const fn subsec_millis(&self) -> u32 {
277         self.nanos / NANOS_PER_MILLI
278     }
279
280     /// Returns the fractional part of this `Duration`, in whole microseconds.
281     ///
282     /// This method does **not** return the length of the duration when
283     /// represented by microseconds. The returned number always represents a
284     /// fractional portion of a second (i.e., it is less than one million).
285     ///
286     /// # Examples
287     ///
288     /// ```
289     /// use std::time::Duration;
290     ///
291     /// let duration = Duration::from_micros(1_234_567);
292     /// assert_eq!(duration.as_secs(), 1);
293     /// assert_eq!(duration.subsec_micros(), 234_567);
294     /// ```
295     #[stable(feature = "duration_extras", since = "1.27.0")]
296     #[inline]
297     pub const fn subsec_micros(&self) -> u32 {
298         self.nanos / NANOS_PER_MICRO
299     }
300
301     /// Returns the fractional part of this `Duration`, in nanoseconds.
302     ///
303     /// This method does **not** return the length of the duration when
304     /// represented by nanoseconds. The returned number always represents a
305     /// fractional portion of a second (i.e., it is less than one billion).
306     ///
307     /// # Examples
308     ///
309     /// ```
310     /// use std::time::Duration;
311     ///
312     /// let duration = Duration::from_millis(5010);
313     /// assert_eq!(duration.as_secs(), 5);
314     /// assert_eq!(duration.subsec_nanos(), 10_000_000);
315     /// ```
316     #[stable(feature = "duration", since = "1.3.0")]
317     #[inline]
318     pub const fn subsec_nanos(&self) -> u32 {
319         self.nanos
320     }
321
322     /// Returns the total number of whole milliseconds contained by this `Duration`.
323     ///
324     /// # Examples
325     ///
326     /// ```
327     /// use std::time::Duration;
328     ///
329     /// let duration = Duration::new(5, 730023852);
330     /// assert_eq!(duration.as_millis(), 5730);
331     /// ```
332     #[stable(feature = "duration_as_u128", since = "1.33.0")]
333     #[inline]
334     pub const fn as_millis(&self) -> u128 {
335         self.secs as u128 * MILLIS_PER_SEC as u128 + (self.nanos / NANOS_PER_MILLI) as u128
336     }
337
338     /// Returns the total number of whole microseconds contained by this `Duration`.
339     ///
340     /// # Examples
341     ///
342     /// ```
343     /// use std::time::Duration;
344     ///
345     /// let duration = Duration::new(5, 730023852);
346     /// assert_eq!(duration.as_micros(), 5730023);
347     /// ```
348     #[stable(feature = "duration_as_u128", since = "1.33.0")]
349     #[inline]
350     pub const fn as_micros(&self) -> u128 {
351         self.secs as u128 * MICROS_PER_SEC as u128 + (self.nanos / NANOS_PER_MICRO) as u128
352     }
353
354     /// Returns the total number of nanoseconds contained by this `Duration`.
355     ///
356     /// # Examples
357     ///
358     /// ```
359     /// use std::time::Duration;
360     ///
361     /// let duration = Duration::new(5, 730023852);
362     /// assert_eq!(duration.as_nanos(), 5730023852);
363     /// ```
364     #[stable(feature = "duration_as_u128", since = "1.33.0")]
365     #[inline]
366     pub const fn as_nanos(&self) -> u128 {
367         self.secs as u128 * NANOS_PER_SEC as u128 + self.nanos as u128
368     }
369
370     /// Checked `Duration` addition. Computes `self + other`, returning [`None`]
371     /// if overflow occurred.
372     ///
373     /// [`None`]: ../../std/option/enum.Option.html#variant.None
374     ///
375     /// # Examples
376     ///
377     /// Basic usage:
378     ///
379     /// ```
380     /// use std::time::Duration;
381     ///
382     /// assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1)));
383     /// assert_eq!(Duration::new(1, 0).checked_add(Duration::new(std::u64::MAX, 0)), None);
384     /// ```
385     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
386     #[inline]
387     pub fn checked_add(self, rhs: Duration) -> Option<Duration> {
388         if let Some(mut secs) = self.secs.checked_add(rhs.secs) {
389             let mut nanos = self.nanos + rhs.nanos;
390             if nanos >= NANOS_PER_SEC {
391                 nanos -= NANOS_PER_SEC;
392                 if let Some(new_secs) = secs.checked_add(1) {
393                     secs = new_secs;
394                 } else {
395                     return None;
396                 }
397             }
398             debug_assert!(nanos < NANOS_PER_SEC);
399             Some(Duration { secs, nanos })
400         } else {
401             None
402         }
403     }
404
405     /// Checked `Duration` subtraction. Computes `self - other`, returning [`None`]
406     /// if the result would be negative or if overflow occurred.
407     ///
408     /// [`None`]: ../../std/option/enum.Option.html#variant.None
409     ///
410     /// # Examples
411     ///
412     /// Basic usage:
413     ///
414     /// ```
415     /// use std::time::Duration;
416     ///
417     /// assert_eq!(Duration::new(0, 1).checked_sub(Duration::new(0, 0)), Some(Duration::new(0, 1)));
418     /// assert_eq!(Duration::new(0, 0).checked_sub(Duration::new(0, 1)), None);
419     /// ```
420     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
421     #[inline]
422     pub fn checked_sub(self, rhs: Duration) -> Option<Duration> {
423         if let Some(mut secs) = self.secs.checked_sub(rhs.secs) {
424             let nanos = if self.nanos >= rhs.nanos {
425                 self.nanos - rhs.nanos
426             } else {
427                 if let Some(sub_secs) = secs.checked_sub(1) {
428                     secs = sub_secs;
429                     self.nanos + NANOS_PER_SEC - rhs.nanos
430                 } else {
431                     return None;
432                 }
433             };
434             debug_assert!(nanos < NANOS_PER_SEC);
435             Some(Duration { secs, nanos })
436         } else {
437             None
438         }
439     }
440
441     /// Checked `Duration` multiplication. Computes `self * other`, returning
442     /// [`None`] if overflow occurred.
443     ///
444     /// [`None`]: ../../std/option/enum.Option.html#variant.None
445     ///
446     /// # Examples
447     ///
448     /// Basic usage:
449     ///
450     /// ```
451     /// use std::time::Duration;
452     ///
453     /// assert_eq!(Duration::new(0, 500_000_001).checked_mul(2), Some(Duration::new(1, 2)));
454     /// assert_eq!(Duration::new(std::u64::MAX - 1, 0).checked_mul(2), None);
455     /// ```
456     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
457     #[inline]
458     pub fn checked_mul(self, rhs: u32) -> Option<Duration> {
459         // Multiply nanoseconds as u64, because it cannot overflow that way.
460         let total_nanos = self.nanos as u64 * rhs as u64;
461         let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
462         let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
463         if let Some(secs) =
464             self.secs.checked_mul(rhs as u64).and_then(|s| s.checked_add(extra_secs))
465         {
466             debug_assert!(nanos < NANOS_PER_SEC);
467             Some(Duration { secs, nanos })
468         } else {
469             None
470         }
471     }
472
473     /// Checked `Duration` division. Computes `self / other`, returning [`None`]
474     /// if `other == 0`.
475     ///
476     /// [`None`]: ../../std/option/enum.Option.html#variant.None
477     ///
478     /// # Examples
479     ///
480     /// Basic usage:
481     ///
482     /// ```
483     /// use std::time::Duration;
484     ///
485     /// assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0)));
486     /// assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000)));
487     /// assert_eq!(Duration::new(2, 0).checked_div(0), None);
488     /// ```
489     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
490     #[inline]
491     pub fn checked_div(self, rhs: u32) -> Option<Duration> {
492         if rhs != 0 {
493             let secs = self.secs / (rhs as u64);
494             let carry = self.secs - secs * (rhs as u64);
495             let extra_nanos = carry * (NANOS_PER_SEC as u64) / (rhs as u64);
496             let nanos = self.nanos / rhs + (extra_nanos as u32);
497             debug_assert!(nanos < NANOS_PER_SEC);
498             Some(Duration { secs, nanos })
499         } else {
500             None
501         }
502     }
503
504     /// Returns the number of seconds contained by this `Duration` as `f64`.
505     ///
506     /// The returned value does include the fractional (nanosecond) part of the duration.
507     ///
508     /// # Examples
509     /// ```
510     /// use std::time::Duration;
511     ///
512     /// let dur = Duration::new(2, 700_000_000);
513     /// assert_eq!(dur.as_secs_f64(), 2.7);
514     /// ```
515     #[stable(feature = "duration_float", since = "1.38.0")]
516     #[inline]
517     pub fn as_secs_f64(&self) -> f64 {
518         (self.secs as f64) + (self.nanos as f64) / (NANOS_PER_SEC as f64)
519     }
520
521     /// Returns the number of seconds contained by this `Duration` as `f32`.
522     ///
523     /// The returned value does include the fractional (nanosecond) part of the duration.
524     ///
525     /// # Examples
526     /// ```
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     #[stable(feature = "duration_float", since = "1.38.0")]
533     #[inline]
534     pub 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     /// use std::time::Duration;
547     ///
548     /// let dur = Duration::from_secs_f64(2.7);
549     /// assert_eq!(dur, Duration::new(2, 700_000_000));
550     /// ```
551     #[stable(feature = "duration_float", since = "1.38.0")]
552     #[inline]
553     pub fn from_secs_f64(secs: f64) -> Duration {
554         const MAX_NANOS_F64: f64 = ((u64::MAX as u128 + 1) * (NANOS_PER_SEC as u128)) as f64;
555         let nanos = secs * (NANOS_PER_SEC as f64);
556         if !nanos.is_finite() {
557             panic!("got non-finite value when converting float to duration");
558         }
559         if nanos >= MAX_NANOS_F64 {
560             panic!("overflow when converting float to duration");
561         }
562         if nanos < 0.0 {
563             panic!("underflow when converting float to duration");
564         }
565         let nanos = nanos as u128;
566         Duration {
567             secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
568             nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
569         }
570     }
571
572     /// Creates a new `Duration` from the specified number of seconds represented
573     /// as `f32`.
574     ///
575     /// # Panics
576     /// This constructor will panic if `secs` is not finite, negative or overflows `Duration`.
577     ///
578     /// # Examples
579     /// ```
580     /// use std::time::Duration;
581     ///
582     /// let dur = Duration::from_secs_f32(2.7);
583     /// assert_eq!(dur, Duration::new(2, 700_000_000));
584     /// ```
585     #[stable(feature = "duration_float", since = "1.38.0")]
586     #[inline]
587     pub fn from_secs_f32(secs: f32) -> Duration {
588         const MAX_NANOS_F32: f32 = ((u64::MAX as u128 + 1) * (NANOS_PER_SEC as u128)) as f32;
589         let nanos = secs * (NANOS_PER_SEC as f32);
590         if !nanos.is_finite() {
591             panic!("got non-finite value when converting float to duration");
592         }
593         if nanos >= MAX_NANOS_F32 {
594             panic!("overflow when converting float to duration");
595         }
596         if nanos < 0.0 {
597             panic!("underflow when converting float to duration");
598         }
599         let nanos = nanos as u128;
600         Duration {
601             secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
602             nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
603         }
604     }
605
606     /// Multiplies `Duration` by `f64`.
607     ///
608     /// # Panics
609     /// This method will panic if result is not finite, negative or overflows `Duration`.
610     ///
611     /// # Examples
612     /// ```
613     /// use std::time::Duration;
614     ///
615     /// let dur = Duration::new(2, 700_000_000);
616     /// assert_eq!(dur.mul_f64(3.14), Duration::new(8, 478_000_000));
617     /// assert_eq!(dur.mul_f64(3.14e5), Duration::new(847_800, 0));
618     /// ```
619     #[stable(feature = "duration_float", since = "1.38.0")]
620     #[inline]
621     pub fn mul_f64(self, rhs: f64) -> Duration {
622         Duration::from_secs_f64(rhs * self.as_secs_f64())
623     }
624
625     /// Multiplies `Duration` by `f32`.
626     ///
627     /// # Panics
628     /// This method will panic if result is not finite, negative or overflows `Duration`.
629     ///
630     /// # Examples
631     /// ```
632     /// use std::time::Duration;
633     ///
634     /// let dur = Duration::new(2, 700_000_000);
635     /// // note that due to rounding errors result is slightly different
636     /// // from 8.478 and 847800.0
637     /// assert_eq!(dur.mul_f32(3.14), Duration::new(8, 478_000_640));
638     /// assert_eq!(dur.mul_f32(3.14e5), Duration::new(847799, 969_120_256));
639     /// ```
640     #[stable(feature = "duration_float", since = "1.38.0")]
641     #[inline]
642     pub fn mul_f32(self, rhs: f32) -> Duration {
643         Duration::from_secs_f32(rhs * self.as_secs_f32())
644     }
645
646     /// Divide `Duration` by `f64`.
647     ///
648     /// # Panics
649     /// This method will panic if result is not finite, negative or overflows `Duration`.
650     ///
651     /// # Examples
652     /// ```
653     /// use std::time::Duration;
654     ///
655     /// let dur = Duration::new(2, 700_000_000);
656     /// assert_eq!(dur.div_f64(3.14), Duration::new(0, 859_872_611));
657     /// // note that truncation is used, not rounding
658     /// assert_eq!(dur.div_f64(3.14e5), Duration::new(0, 8_598));
659     /// ```
660     #[stable(feature = "duration_float", since = "1.38.0")]
661     #[inline]
662     pub fn div_f64(self, rhs: f64) -> Duration {
663         Duration::from_secs_f64(self.as_secs_f64() / rhs)
664     }
665
666     /// Divide `Duration` by `f32`.
667     ///
668     /// # Panics
669     /// This method will panic if result is not finite, negative or overflows `Duration`.
670     ///
671     /// # Examples
672     /// ```
673     /// use std::time::Duration;
674     ///
675     /// let dur = Duration::new(2, 700_000_000);
676     /// // note that due to rounding errors result is slightly
677     /// // different from 0.859_872_611
678     /// assert_eq!(dur.div_f32(3.14), Duration::new(0, 859_872_576));
679     /// // note that truncation is used, not rounding
680     /// assert_eq!(dur.div_f32(3.14e5), Duration::new(0, 8_598));
681     /// ```
682     #[stable(feature = "duration_float", since = "1.38.0")]
683     #[inline]
684     pub fn div_f32(self, rhs: f32) -> Duration {
685         Duration::from_secs_f32(self.as_secs_f32() / rhs)
686     }
687
688     /// Divide `Duration` by `Duration` and return `f64`.
689     ///
690     /// # Examples
691     /// ```
692     /// #![feature(div_duration)]
693     /// use std::time::Duration;
694     ///
695     /// let dur1 = Duration::new(2, 700_000_000);
696     /// let dur2 = Duration::new(5, 400_000_000);
697     /// assert_eq!(dur1.div_duration_f64(dur2), 0.5);
698     /// ```
699     #[unstable(feature = "div_duration", issue = "63139")]
700     #[inline]
701     pub fn div_duration_f64(self, rhs: Duration) -> f64 {
702         self.as_secs_f64() / rhs.as_secs_f64()
703     }
704
705     /// Divide `Duration` by `Duration` and return `f32`.
706     ///
707     /// # Examples
708     /// ```
709     /// #![feature(div_duration)]
710     /// use std::time::Duration;
711     ///
712     /// let dur1 = Duration::new(2, 700_000_000);
713     /// let dur2 = Duration::new(5, 400_000_000);
714     /// assert_eq!(dur1.div_duration_f32(dur2), 0.5);
715     /// ```
716     #[unstable(feature = "div_duration", issue = "63139")]
717     #[inline]
718     pub fn div_duration_f32(self, rhs: Duration) -> f32 {
719         self.as_secs_f32() / rhs.as_secs_f32()
720     }
721 }
722
723 #[stable(feature = "duration", since = "1.3.0")]
724 impl Add for Duration {
725     type Output = Duration;
726
727     fn add(self, rhs: Duration) -> Duration {
728         self.checked_add(rhs).expect("overflow when adding durations")
729     }
730 }
731
732 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
733 impl AddAssign for Duration {
734     fn add_assign(&mut self, rhs: Duration) {
735         *self = *self + rhs;
736     }
737 }
738
739 #[stable(feature = "duration", since = "1.3.0")]
740 impl Sub for Duration {
741     type Output = Duration;
742
743     fn sub(self, rhs: Duration) -> Duration {
744         self.checked_sub(rhs).expect("overflow when subtracting durations")
745     }
746 }
747
748 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
749 impl SubAssign for Duration {
750     fn sub_assign(&mut self, rhs: Duration) {
751         *self = *self - rhs;
752     }
753 }
754
755 #[stable(feature = "duration", since = "1.3.0")]
756 impl Mul<u32> for Duration {
757     type Output = Duration;
758
759     fn mul(self, rhs: u32) -> Duration {
760         self.checked_mul(rhs).expect("overflow when multiplying duration by scalar")
761     }
762 }
763
764 #[stable(feature = "symmetric_u32_duration_mul", since = "1.31.0")]
765 impl Mul<Duration> for u32 {
766     type Output = Duration;
767
768     fn mul(self, rhs: Duration) -> Duration {
769         rhs * self
770     }
771 }
772
773 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
774 impl MulAssign<u32> for Duration {
775     fn mul_assign(&mut self, rhs: u32) {
776         *self = *self * rhs;
777     }
778 }
779
780 #[stable(feature = "duration", since = "1.3.0")]
781 impl Div<u32> for Duration {
782     type Output = Duration;
783
784     fn div(self, rhs: u32) -> Duration {
785         self.checked_div(rhs).expect("divide by zero error when dividing duration by scalar")
786     }
787 }
788
789 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
790 impl DivAssign<u32> for Duration {
791     fn div_assign(&mut self, rhs: u32) {
792         *self = *self / rhs;
793     }
794 }
795
796 macro_rules! sum_durations {
797     ($iter:expr) => {{
798         let mut total_secs: u64 = 0;
799         let mut total_nanos: u64 = 0;
800
801         for entry in $iter {
802             total_secs =
803                 total_secs.checked_add(entry.secs).expect("overflow in iter::sum over durations");
804             total_nanos = match total_nanos.checked_add(entry.nanos as u64) {
805                 Some(n) => n,
806                 None => {
807                     total_secs = total_secs
808                         .checked_add(total_nanos / NANOS_PER_SEC as u64)
809                         .expect("overflow in iter::sum over durations");
810                     (total_nanos % NANOS_PER_SEC as u64) + entry.nanos as u64
811                 }
812             };
813         }
814         total_secs = total_secs
815             .checked_add(total_nanos / NANOS_PER_SEC as u64)
816             .expect("overflow in iter::sum over durations");
817         total_nanos = total_nanos % NANOS_PER_SEC as u64;
818         Duration { secs: total_secs, nanos: total_nanos as u32 }
819     }};
820 }
821
822 #[stable(feature = "duration_sum", since = "1.16.0")]
823 impl Sum for Duration {
824     fn sum<I: Iterator<Item = Duration>>(iter: I) -> Duration {
825         sum_durations!(iter)
826     }
827 }
828
829 #[stable(feature = "duration_sum", since = "1.16.0")]
830 impl<'a> Sum<&'a Duration> for Duration {
831     fn sum<I: Iterator<Item = &'a Duration>>(iter: I) -> Duration {
832         sum_durations!(iter)
833     }
834 }
835
836 #[stable(feature = "duration_debug_impl", since = "1.27.0")]
837 impl fmt::Debug for Duration {
838     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
839         /// Formats a floating point number in decimal notation.
840         ///
841         /// The number is given as the `integer_part` and a fractional part.
842         /// The value of the fractional part is `fractional_part / divisor`. So
843         /// `integer_part` = 3, `fractional_part` = 12 and `divisor` = 100
844         /// represents the number `3.012`. Trailing zeros are omitted.
845         ///
846         /// `divisor` must not be above 100_000_000. It also should be a power
847         /// of 10, everything else doesn't make sense. `fractional_part` has
848         /// to be less than `10 * divisor`!
849         fn fmt_decimal(
850             f: &mut fmt::Formatter<'_>,
851             mut integer_part: u64,
852             mut fractional_part: u32,
853             mut divisor: u32,
854         ) -> fmt::Result {
855             // Encode the fractional part into a temporary buffer. The buffer
856             // only need to hold 9 elements, because `fractional_part` has to
857             // be smaller than 10^9. The buffer is prefilled with '0' digits
858             // to simplify the code below.
859             let mut buf = [b'0'; 9];
860
861             // The next digit is written at this position
862             let mut pos = 0;
863
864             // We keep writing digits into the buffer while there are non-zero
865             // digits left and we haven't written enough digits yet.
866             while fractional_part > 0 && pos < f.precision().unwrap_or(9) {
867                 // Write new digit into the buffer
868                 buf[pos] = b'0' + (fractional_part / divisor) as u8;
869
870                 fractional_part %= divisor;
871                 divisor /= 10;
872                 pos += 1;
873             }
874
875             // If a precision < 9 was specified, there may be some non-zero
876             // digits left that weren't written into the buffer. In that case we
877             // need to perform rounding to match the semantics of printing
878             // normal floating point numbers. However, we only need to do work
879             // when rounding up. This happens if the first digit of the
880             // remaining ones is >= 5.
881             if fractional_part > 0 && fractional_part >= divisor * 5 {
882                 // Round up the number contained in the buffer. We go through
883                 // the buffer backwards and keep track of the carry.
884                 let mut rev_pos = pos;
885                 let mut carry = true;
886                 while carry && rev_pos > 0 {
887                     rev_pos -= 1;
888
889                     // If the digit in the buffer is not '9', we just need to
890                     // increment it and can stop then (since we don't have a
891                     // carry anymore). Otherwise, we set it to '0' (overflow)
892                     // and continue.
893                     if buf[rev_pos] < b'9' {
894                         buf[rev_pos] += 1;
895                         carry = false;
896                     } else {
897                         buf[rev_pos] = b'0';
898                     }
899                 }
900
901                 // If we still have the carry bit set, that means that we set
902                 // the whole buffer to '0's and need to increment the integer
903                 // part.
904                 if carry {
905                     integer_part += 1;
906                 }
907             }
908
909             // Determine the end of the buffer: if precision is set, we just
910             // use as many digits from the buffer (capped to 9). If it isn't
911             // set, we only use all digits up to the last non-zero one.
912             let end = f.precision().map(|p| crate::cmp::min(p, 9)).unwrap_or(pos);
913
914             // If we haven't emitted a single fractional digit and the precision
915             // wasn't set to a non-zero value, we don't print the decimal point.
916             if end == 0 {
917                 write!(f, "{}", integer_part)
918             } else {
919                 // SAFETY: We are only writing ASCII digits into the buffer and it was
920                 // initialized with '0's, so it contains valid UTF8.
921                 let s = unsafe { crate::str::from_utf8_unchecked(&buf[..end]) };
922
923                 // If the user request a precision > 9, we pad '0's at the end.
924                 let w = f.precision().unwrap_or(pos);
925                 write!(f, "{}.{:0<width$}", integer_part, s, width = w)
926             }
927         }
928
929         // Print leading '+' sign if requested
930         if f.sign_plus() {
931             write!(f, "+")?;
932         }
933
934         if self.secs > 0 {
935             fmt_decimal(f, self.secs, self.nanos, 100_000_000)?;
936             f.write_str("s")
937         } else if self.nanos >= 1_000_000 {
938             fmt_decimal(f, self.nanos as u64 / 1_000_000, self.nanos % 1_000_000, 100_000)?;
939             f.write_str("ms")
940         } else if self.nanos >= 1_000 {
941             fmt_decimal(f, self.nanos as u64 / 1_000, self.nanos % 1_000, 100)?;
942             f.write_str("µs")
943         } else {
944             fmt_decimal(f, self.nanos as u64, 0, 1)?;
945             f.write_str("ns")
946         }
947     }
948 }