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