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