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