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