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