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