]> git.lizzy.rs Git - rust.git/blob - library/core/src/time.rs
Auto merge of #93741 - Mark-Simulacrum:global-job-id, r=cjgillot
[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     pub const fn new(secs: u64, nanos: u32) -> Duration {
186         let secs = match secs.checked_add((nanos / NANOS_PER_SEC) as u64) {
187             Some(secs) => secs,
188             None => panic!("overflow in Duration::new"),
189         };
190         let nanos = nanos % NANOS_PER_SEC;
191         Duration { secs, nanos }
192     }
193
194     /// Creates a new `Duration` from the specified number of whole seconds.
195     ///
196     /// # Examples
197     ///
198     /// ```
199     /// use std::time::Duration;
200     ///
201     /// let duration = Duration::from_secs(5);
202     ///
203     /// assert_eq!(5, duration.as_secs());
204     /// assert_eq!(0, duration.subsec_nanos());
205     /// ```
206     #[stable(feature = "duration", since = "1.3.0")]
207     #[must_use]
208     #[inline]
209     #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
210     pub const fn from_secs(secs: u64) -> Duration {
211         Duration { secs, nanos: 0 }
212     }
213
214     /// Creates a new `Duration` from the specified number of milliseconds.
215     ///
216     /// # Examples
217     ///
218     /// ```
219     /// use std::time::Duration;
220     ///
221     /// let duration = Duration::from_millis(2569);
222     ///
223     /// assert_eq!(2, duration.as_secs());
224     /// assert_eq!(569_000_000, duration.subsec_nanos());
225     /// ```
226     #[stable(feature = "duration", since = "1.3.0")]
227     #[must_use]
228     #[inline]
229     #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
230     pub const fn from_millis(millis: u64) -> Duration {
231         Duration {
232             secs: millis / MILLIS_PER_SEC,
233             nanos: ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI,
234         }
235     }
236
237     /// Creates a new `Duration` from the specified number of microseconds.
238     ///
239     /// # Examples
240     ///
241     /// ```
242     /// use std::time::Duration;
243     ///
244     /// let duration = Duration::from_micros(1_000_002);
245     ///
246     /// assert_eq!(1, duration.as_secs());
247     /// assert_eq!(2000, duration.subsec_nanos());
248     /// ```
249     #[stable(feature = "duration_from_micros", since = "1.27.0")]
250     #[must_use]
251     #[inline]
252     #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
253     pub const fn from_micros(micros: u64) -> Duration {
254         Duration {
255             secs: micros / MICROS_PER_SEC,
256             nanos: ((micros % MICROS_PER_SEC) as u32) * NANOS_PER_MICRO,
257         }
258     }
259
260     /// Creates a new `Duration` from the specified number of nanoseconds.
261     ///
262     /// # Examples
263     ///
264     /// ```
265     /// use std::time::Duration;
266     ///
267     /// let duration = Duration::from_nanos(1_000_000_123);
268     ///
269     /// assert_eq!(1, duration.as_secs());
270     /// assert_eq!(123, duration.subsec_nanos());
271     /// ```
272     #[stable(feature = "duration_extras", since = "1.27.0")]
273     #[must_use]
274     #[inline]
275     #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
276     pub const fn from_nanos(nanos: u64) -> Duration {
277         Duration {
278             secs: nanos / (NANOS_PER_SEC as u64),
279             nanos: (nanos % (NANOS_PER_SEC as u64)) as u32,
280         }
281     }
282
283     /// Returns true if this `Duration` spans no time.
284     ///
285     /// # Examples
286     ///
287     /// ```
288     /// use std::time::Duration;
289     ///
290     /// assert!(Duration::ZERO.is_zero());
291     /// assert!(Duration::new(0, 0).is_zero());
292     /// assert!(Duration::from_nanos(0).is_zero());
293     /// assert!(Duration::from_secs(0).is_zero());
294     ///
295     /// assert!(!Duration::new(1, 1).is_zero());
296     /// assert!(!Duration::from_nanos(1).is_zero());
297     /// assert!(!Duration::from_secs(1).is_zero());
298     /// ```
299     #[must_use]
300     #[stable(feature = "duration_zero", since = "1.53.0")]
301     #[rustc_const_stable(feature = "duration_zero", since = "1.53.0")]
302     #[inline]
303     pub const fn is_zero(&self) -> bool {
304         self.secs == 0 && self.nanos == 0
305     }
306
307     /// Returns the number of _whole_ seconds contained by this `Duration`.
308     ///
309     /// The returned value does not include the fractional (nanosecond) part of the
310     /// duration, which can be obtained using [`subsec_nanos`].
311     ///
312     /// # Examples
313     ///
314     /// ```
315     /// use std::time::Duration;
316     ///
317     /// let duration = Duration::new(5, 730023852);
318     /// assert_eq!(duration.as_secs(), 5);
319     /// ```
320     ///
321     /// To determine the total number of seconds represented by the `Duration`,
322     /// use `as_secs` in combination with [`subsec_nanos`]:
323     ///
324     /// ```
325     /// use std::time::Duration;
326     ///
327     /// let duration = Duration::new(5, 730023852);
328     ///
329     /// assert_eq!(5.730023852,
330     ///            duration.as_secs() as f64
331     ///            + duration.subsec_nanos() as f64 * 1e-9);
332     /// ```
333     ///
334     /// [`subsec_nanos`]: Duration::subsec_nanos
335     #[stable(feature = "duration", since = "1.3.0")]
336     #[rustc_const_stable(feature = "duration", since = "1.32.0")]
337     #[must_use]
338     #[inline]
339     pub const fn as_secs(&self) -> u64 {
340         self.secs
341     }
342
343     /// Returns the fractional part of this `Duration`, in whole milliseconds.
344     ///
345     /// This method does **not** return the length of the duration when
346     /// represented by milliseconds. The returned number always represents a
347     /// fractional portion of a second (i.e., it is less than one thousand).
348     ///
349     /// # Examples
350     ///
351     /// ```
352     /// use std::time::Duration;
353     ///
354     /// let duration = Duration::from_millis(5432);
355     /// assert_eq!(duration.as_secs(), 5);
356     /// assert_eq!(duration.subsec_millis(), 432);
357     /// ```
358     #[stable(feature = "duration_extras", since = "1.27.0")]
359     #[rustc_const_stable(feature = "duration_extras", since = "1.32.0")]
360     #[must_use]
361     #[inline]
362     pub const fn subsec_millis(&self) -> u32 {
363         self.nanos / NANOS_PER_MILLI
364     }
365
366     /// Returns the fractional part of this `Duration`, in whole microseconds.
367     ///
368     /// This method does **not** return the length of the duration when
369     /// represented by microseconds. The returned number always represents a
370     /// fractional portion of a second (i.e., it is less than one million).
371     ///
372     /// # Examples
373     ///
374     /// ```
375     /// use std::time::Duration;
376     ///
377     /// let duration = Duration::from_micros(1_234_567);
378     /// assert_eq!(duration.as_secs(), 1);
379     /// assert_eq!(duration.subsec_micros(), 234_567);
380     /// ```
381     #[stable(feature = "duration_extras", since = "1.27.0")]
382     #[rustc_const_stable(feature = "duration_extras", since = "1.32.0")]
383     #[must_use]
384     #[inline]
385     pub const fn subsec_micros(&self) -> u32 {
386         self.nanos / NANOS_PER_MICRO
387     }
388
389     /// Returns the fractional part of this `Duration`, in nanoseconds.
390     ///
391     /// This method does **not** return the length of the duration when
392     /// represented by nanoseconds. The returned number always represents a
393     /// fractional portion of a second (i.e., it is less than one billion).
394     ///
395     /// # Examples
396     ///
397     /// ```
398     /// use std::time::Duration;
399     ///
400     /// let duration = Duration::from_millis(5010);
401     /// assert_eq!(duration.as_secs(), 5);
402     /// assert_eq!(duration.subsec_nanos(), 10_000_000);
403     /// ```
404     #[stable(feature = "duration", since = "1.3.0")]
405     #[rustc_const_stable(feature = "duration", since = "1.32.0")]
406     #[must_use]
407     #[inline]
408     pub const fn subsec_nanos(&self) -> u32 {
409         self.nanos
410     }
411
412     /// Returns the total number of whole milliseconds 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_millis(), 5730);
421     /// ```
422     #[stable(feature = "duration_as_u128", since = "1.33.0")]
423     #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
424     #[must_use]
425     #[inline]
426     pub const fn as_millis(&self) -> u128 {
427         self.secs as u128 * MILLIS_PER_SEC as u128 + (self.nanos / NANOS_PER_MILLI) as u128
428     }
429
430     /// Returns the total number of whole microseconds contained by this `Duration`.
431     ///
432     /// # Examples
433     ///
434     /// ```
435     /// use std::time::Duration;
436     ///
437     /// let duration = Duration::new(5, 730023852);
438     /// assert_eq!(duration.as_micros(), 5730023);
439     /// ```
440     #[stable(feature = "duration_as_u128", since = "1.33.0")]
441     #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
442     #[must_use]
443     #[inline]
444     pub const fn as_micros(&self) -> u128 {
445         self.secs as u128 * MICROS_PER_SEC as u128 + (self.nanos / NANOS_PER_MICRO) as u128
446     }
447
448     /// Returns the total number of nanoseconds contained by this `Duration`.
449     ///
450     /// # Examples
451     ///
452     /// ```
453     /// use std::time::Duration;
454     ///
455     /// let duration = Duration::new(5, 730023852);
456     /// assert_eq!(duration.as_nanos(), 5730023852);
457     /// ```
458     #[stable(feature = "duration_as_u128", since = "1.33.0")]
459     #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
460     #[must_use]
461     #[inline]
462     pub const fn as_nanos(&self) -> u128 {
463         self.secs as u128 * NANOS_PER_SEC as u128 + self.nanos as u128
464     }
465
466     /// Checked `Duration` addition. Computes `self + other`, returning [`None`]
467     /// if overflow occurred.
468     ///
469     /// # Examples
470     ///
471     /// Basic usage:
472     ///
473     /// ```
474     /// use std::time::Duration;
475     ///
476     /// assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1)));
477     /// assert_eq!(Duration::new(1, 0).checked_add(Duration::new(u64::MAX, 0)), None);
478     /// ```
479     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
480     #[must_use = "this returns the result of the operation, \
481                   without modifying the original"]
482     #[inline]
483     #[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
484     pub const fn checked_add(self, rhs: Duration) -> Option<Duration> {
485         if let Some(mut secs) = self.secs.checked_add(rhs.secs) {
486             let mut nanos = self.nanos + rhs.nanos;
487             if nanos >= NANOS_PER_SEC {
488                 nanos -= NANOS_PER_SEC;
489                 if let Some(new_secs) = secs.checked_add(1) {
490                     secs = new_secs;
491                 } else {
492                     return None;
493                 }
494             }
495             debug_assert!(nanos < NANOS_PER_SEC);
496             Some(Duration { secs, nanos })
497         } else {
498             None
499         }
500     }
501
502     /// Saturating `Duration` addition. Computes `self + other`, returning [`Duration::MAX`]
503     /// if overflow occurred.
504     ///
505     /// # Examples
506     ///
507     /// ```
508     /// #![feature(duration_constants)]
509     /// use std::time::Duration;
510     ///
511     /// assert_eq!(Duration::new(0, 0).saturating_add(Duration::new(0, 1)), Duration::new(0, 1));
512     /// assert_eq!(Duration::new(1, 0).saturating_add(Duration::new(u64::MAX, 0)), Duration::MAX);
513     /// ```
514     #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
515     #[must_use = "this returns the result of the operation, \
516                   without modifying the original"]
517     #[inline]
518     #[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
519     pub const fn saturating_add(self, rhs: Duration) -> Duration {
520         match self.checked_add(rhs) {
521             Some(res) => res,
522             None => Duration::MAX,
523         }
524     }
525
526     /// Checked `Duration` subtraction. Computes `self - other`, returning [`None`]
527     /// if the result would be negative or if overflow occurred.
528     ///
529     /// # Examples
530     ///
531     /// Basic usage:
532     ///
533     /// ```
534     /// use std::time::Duration;
535     ///
536     /// assert_eq!(Duration::new(0, 1).checked_sub(Duration::new(0, 0)), Some(Duration::new(0, 1)));
537     /// assert_eq!(Duration::new(0, 0).checked_sub(Duration::new(0, 1)), None);
538     /// ```
539     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
540     #[must_use = "this returns the result of the operation, \
541                   without modifying the original"]
542     #[inline]
543     #[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
544     pub const fn checked_sub(self, rhs: Duration) -> Option<Duration> {
545         if let Some(mut secs) = self.secs.checked_sub(rhs.secs) {
546             let nanos = if self.nanos >= rhs.nanos {
547                 self.nanos - rhs.nanos
548             } else if let Some(sub_secs) = secs.checked_sub(1) {
549                 secs = sub_secs;
550                 self.nanos + NANOS_PER_SEC - rhs.nanos
551             } else {
552                 return None;
553             };
554             debug_assert!(nanos < NANOS_PER_SEC);
555             Some(Duration { secs, nanos })
556         } else {
557             None
558         }
559     }
560
561     /// Saturating `Duration` subtraction. Computes `self - other`, returning [`Duration::ZERO`]
562     /// if the result would be negative or if overflow occurred.
563     ///
564     /// # Examples
565     ///
566     /// ```
567     /// use std::time::Duration;
568     ///
569     /// assert_eq!(Duration::new(0, 1).saturating_sub(Duration::new(0, 0)), Duration::new(0, 1));
570     /// assert_eq!(Duration::new(0, 0).saturating_sub(Duration::new(0, 1)), Duration::ZERO);
571     /// ```
572     #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
573     #[must_use = "this returns the result of the operation, \
574                   without modifying the original"]
575     #[inline]
576     #[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
577     pub const fn saturating_sub(self, rhs: Duration) -> Duration {
578         match self.checked_sub(rhs) {
579             Some(res) => res,
580             None => Duration::ZERO,
581         }
582     }
583
584     /// Checked `Duration` multiplication. Computes `self * other`, returning
585     /// [`None`] if overflow occurred.
586     ///
587     /// # Examples
588     ///
589     /// Basic usage:
590     ///
591     /// ```
592     /// use std::time::Duration;
593     ///
594     /// assert_eq!(Duration::new(0, 500_000_001).checked_mul(2), Some(Duration::new(1, 2)));
595     /// assert_eq!(Duration::new(u64::MAX - 1, 0).checked_mul(2), None);
596     /// ```
597     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
598     #[must_use = "this returns the result of the operation, \
599                   without modifying the original"]
600     #[inline]
601     #[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
602     pub const fn checked_mul(self, rhs: u32) -> Option<Duration> {
603         // Multiply nanoseconds as u64, because it cannot overflow that way.
604         let total_nanos = self.nanos as u64 * rhs as u64;
605         let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
606         let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
607         if let Some(s) = self.secs.checked_mul(rhs as u64) {
608             if let Some(secs) = s.checked_add(extra_secs) {
609                 debug_assert!(nanos < NANOS_PER_SEC);
610                 return Some(Duration { secs, nanos });
611             }
612         }
613         None
614     }
615
616     /// Saturating `Duration` multiplication. Computes `self * other`, returning
617     /// [`Duration::MAX`] if overflow occurred.
618     ///
619     /// # Examples
620     ///
621     /// ```
622     /// #![feature(duration_constants)]
623     /// use std::time::Duration;
624     ///
625     /// assert_eq!(Duration::new(0, 500_000_001).saturating_mul(2), Duration::new(1, 2));
626     /// assert_eq!(Duration::new(u64::MAX - 1, 0).saturating_mul(2), Duration::MAX);
627     /// ```
628     #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
629     #[must_use = "this returns the result of the operation, \
630                   without modifying the original"]
631     #[inline]
632     #[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
633     pub const fn saturating_mul(self, rhs: u32) -> Duration {
634         match self.checked_mul(rhs) {
635             Some(res) => res,
636             None => Duration::MAX,
637         }
638     }
639
640     /// Checked `Duration` division. Computes `self / other`, returning [`None`]
641     /// if `other == 0`.
642     ///
643     /// # Examples
644     ///
645     /// Basic usage:
646     ///
647     /// ```
648     /// use std::time::Duration;
649     ///
650     /// assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0)));
651     /// assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000)));
652     /// assert_eq!(Duration::new(2, 0).checked_div(0), None);
653     /// ```
654     #[stable(feature = "duration_checked_ops", since = "1.16.0")]
655     #[must_use = "this returns the result of the operation, \
656                   without modifying the original"]
657     #[inline]
658     #[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
659     pub const fn checked_div(self, rhs: u32) -> Option<Duration> {
660         if rhs != 0 {
661             let secs = self.secs / (rhs as u64);
662             let carry = self.secs - secs * (rhs as u64);
663             let extra_nanos = carry * (NANOS_PER_SEC as u64) / (rhs as u64);
664             let nanos = self.nanos / rhs + (extra_nanos as u32);
665             debug_assert!(nanos < NANOS_PER_SEC);
666             Some(Duration { secs, nanos })
667         } else {
668             None
669         }
670     }
671
672     /// Returns the number of seconds contained by this `Duration` as `f64`.
673     ///
674     /// The returned value does include the fractional (nanosecond) part of the duration.
675     ///
676     /// # Examples
677     /// ```
678     /// use std::time::Duration;
679     ///
680     /// let dur = Duration::new(2, 700_000_000);
681     /// assert_eq!(dur.as_secs_f64(), 2.7);
682     /// ```
683     #[stable(feature = "duration_float", since = "1.38.0")]
684     #[must_use]
685     #[inline]
686     #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")]
687     pub const fn as_secs_f64(&self) -> f64 {
688         (self.secs as f64) + (self.nanos as f64) / (NANOS_PER_SEC as f64)
689     }
690
691     /// Returns the number of seconds contained by this `Duration` as `f32`.
692     ///
693     /// The returned value does include the fractional (nanosecond) part of the duration.
694     ///
695     /// # Examples
696     /// ```
697     /// use std::time::Duration;
698     ///
699     /// let dur = Duration::new(2, 700_000_000);
700     /// assert_eq!(dur.as_secs_f32(), 2.7);
701     /// ```
702     #[stable(feature = "duration_float", since = "1.38.0")]
703     #[must_use]
704     #[inline]
705     #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")]
706     pub const fn as_secs_f32(&self) -> f32 {
707         (self.secs as f32) + (self.nanos as f32) / (NANOS_PER_SEC as f32)
708     }
709
710     /// Creates a new `Duration` from the specified number of seconds represented
711     /// as `f64`.
712     ///
713     /// # Panics
714     /// This constructor will panic if `secs` is negative, overflows `Duration` or not finite.
715     ///
716     /// # Examples
717     /// ```
718     /// use std::time::Duration;
719     ///
720     /// let res = Duration::from_secs_f64(0.0);
721     /// assert_eq!(res, Duration::new(0, 0));
722     /// let res = Duration::from_secs_f64(1e-20);
723     /// assert_eq!(res, Duration::new(0, 0));
724     /// let res = Duration::from_secs_f64(4.2e-7);
725     /// assert_eq!(res, Duration::new(0, 420));
726     /// let res = Duration::from_secs_f64(2.7);
727     /// assert_eq!(res, Duration::new(2, 700_000_000));
728     /// let res = Duration::from_secs_f64(3e10);
729     /// assert_eq!(res, Duration::new(30_000_000_000, 0));
730     /// // subnormal float
731     /// let res = Duration::from_secs_f64(f64::from_bits(1));
732     /// assert_eq!(res, Duration::new(0, 0));
733     /// // conversion uses truncation, not rounding
734     /// let res = Duration::from_secs_f64(0.999e-9);
735     /// assert_eq!(res, Duration::new(0, 0));
736     /// ```
737     #[stable(feature = "duration_float", since = "1.38.0")]
738     #[must_use]
739     #[inline]
740     #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")]
741     pub const fn from_secs_f64(secs: f64) -> Duration {
742         match Duration::try_from_secs_f64(secs) {
743             Ok(v) => v,
744             Err(e) => panic!("{}", e.description()),
745         }
746     }
747
748     /// Creates a new `Duration` from the specified number of seconds represented
749     /// as `f32`.
750     ///
751     /// # Panics
752     /// This constructor will panic if `secs` is negative, overflows `Duration` or not finite.
753     ///
754     /// # Examples
755     /// ```
756     /// use std::time::Duration;
757     ///
758     /// let res = Duration::from_secs_f32(0.0);
759     /// assert_eq!(res, Duration::new(0, 0));
760     /// let res = Duration::from_secs_f32(1e-20);
761     /// assert_eq!(res, Duration::new(0, 0));
762     /// let res = Duration::from_secs_f32(4.2e-7);
763     /// assert_eq!(res, Duration::new(0, 419));
764     /// let res = Duration::from_secs_f32(2.7);
765     /// assert_eq!(res, Duration::new(2, 700_000_047));
766     /// let res = Duration::from_secs_f32(3e10);
767     /// assert_eq!(res, Duration::new(30_000_001_024, 0));
768     /// // subnormal float
769     /// let res = Duration::from_secs_f32(f32::from_bits(1));
770     /// assert_eq!(res, Duration::new(0, 0));
771     /// // conversion uses truncation, not rounding
772     /// let res = Duration::from_secs_f32(0.999e-9);
773     /// assert_eq!(res, Duration::new(0, 0));
774     /// ```
775     #[stable(feature = "duration_float", since = "1.38.0")]
776     #[must_use]
777     #[inline]
778     #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")]
779     pub const fn from_secs_f32(secs: f32) -> Duration {
780         match Duration::try_from_secs_f32(secs) {
781             Ok(v) => v,
782             Err(e) => panic!("{}", e.description()),
783         }
784     }
785
786     /// Multiplies `Duration` by `f64`.
787     ///
788     /// # Panics
789     /// This method will panic if result is negative, overflows `Duration` or not finite.
790     ///
791     /// # Examples
792     /// ```
793     /// use std::time::Duration;
794     ///
795     /// let dur = Duration::new(2, 700_000_000);
796     /// assert_eq!(dur.mul_f64(3.14), Duration::new(8, 478_000_000));
797     /// assert_eq!(dur.mul_f64(3.14e5), Duration::new(847_800, 0));
798     /// ```
799     #[stable(feature = "duration_float", since = "1.38.0")]
800     #[must_use = "this returns the result of the operation, \
801                   without modifying the original"]
802     #[inline]
803     #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")]
804     pub const fn mul_f64(self, rhs: f64) -> Duration {
805         Duration::from_secs_f64(rhs * self.as_secs_f64())
806     }
807
808     /// Multiplies `Duration` by `f32`.
809     ///
810     /// # Panics
811     /// This method will panic if result is negative, overflows `Duration` or not finite.
812     ///
813     /// # Examples
814     /// ```
815     /// use std::time::Duration;
816     ///
817     /// let dur = Duration::new(2, 700_000_000);
818     /// assert_eq!(dur.mul_f32(3.14), Duration::new(8, 478_000_640));
819     /// assert_eq!(dur.mul_f32(3.14e5), Duration::new(847800, 0));
820     /// ```
821     #[stable(feature = "duration_float", since = "1.38.0")]
822     #[must_use = "this returns the result of the operation, \
823                   without modifying the original"]
824     #[inline]
825     #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")]
826     pub const fn mul_f32(self, rhs: f32) -> Duration {
827         Duration::from_secs_f32(rhs * self.as_secs_f32())
828     }
829
830     /// Divide `Duration` by `f64`.
831     ///
832     /// # Panics
833     /// This method will panic if result is negative, overflows `Duration` or not finite.
834     ///
835     /// # Examples
836     /// ```
837     /// use std::time::Duration;
838     ///
839     /// let dur = Duration::new(2, 700_000_000);
840     /// assert_eq!(dur.div_f64(3.14), Duration::new(0, 859_872_611));
841     /// // note that truncation is used, not rounding
842     /// assert_eq!(dur.div_f64(3.14e5), Duration::new(0, 8_598));
843     /// ```
844     #[stable(feature = "duration_float", since = "1.38.0")]
845     #[must_use = "this returns the result of the operation, \
846                   without modifying the original"]
847     #[inline]
848     #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")]
849     pub const fn div_f64(self, rhs: f64) -> Duration {
850         Duration::from_secs_f64(self.as_secs_f64() / rhs)
851     }
852
853     /// Divide `Duration` by `f32`.
854     ///
855     /// # Panics
856     /// This method will panic if result is negative, overflows `Duration` or not finite.
857     ///
858     /// # Examples
859     /// ```
860     /// use std::time::Duration;
861     ///
862     /// let dur = Duration::new(2, 700_000_000);
863     /// // note that due to rounding errors result is slightly
864     /// // different from 0.859_872_611
865     /// assert_eq!(dur.div_f32(3.14), Duration::new(0, 859_872_579));
866     /// // note that truncation is used, not rounding
867     /// assert_eq!(dur.div_f32(3.14e5), Duration::new(0, 8_598));
868     /// ```
869     #[stable(feature = "duration_float", since = "1.38.0")]
870     #[must_use = "this returns the result of the operation, \
871                   without modifying the original"]
872     #[inline]
873     #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")]
874     pub const fn div_f32(self, rhs: f32) -> Duration {
875         Duration::from_secs_f32(self.as_secs_f32() / rhs)
876     }
877
878     /// Divide `Duration` by `Duration` and return `f64`.
879     ///
880     /// # Examples
881     /// ```
882     /// #![feature(div_duration)]
883     /// use std::time::Duration;
884     ///
885     /// let dur1 = Duration::new(2, 700_000_000);
886     /// let dur2 = Duration::new(5, 400_000_000);
887     /// assert_eq!(dur1.div_duration_f64(dur2), 0.5);
888     /// ```
889     #[unstable(feature = "div_duration", issue = "63139")]
890     #[must_use = "this returns the result of the operation, \
891                   without modifying the original"]
892     #[inline]
893     #[rustc_const_unstable(feature = "duration_consts_float", issue = "72440")]
894     pub const fn div_duration_f64(self, rhs: Duration) -> f64 {
895         self.as_secs_f64() / rhs.as_secs_f64()
896     }
897
898     /// Divide `Duration` by `Duration` and return `f32`.
899     ///
900     /// # Examples
901     /// ```
902     /// #![feature(div_duration)]
903     /// use std::time::Duration;
904     ///
905     /// let dur1 = Duration::new(2, 700_000_000);
906     /// let dur2 = Duration::new(5, 400_000_000);
907     /// assert_eq!(dur1.div_duration_f32(dur2), 0.5);
908     /// ```
909     #[unstable(feature = "div_duration", issue = "63139")]
910     #[must_use = "this returns the result of the operation, \
911                   without modifying the original"]
912     #[inline]
913     #[rustc_const_unstable(feature = "duration_consts_float", 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         ///
1046         /// A prefix and postfix may be added. The whole thing is padded
1047         /// to the formatter's `width`, if specified.
1048         fn fmt_decimal(
1049             f: &mut fmt::Formatter<'_>,
1050             mut integer_part: u64,
1051             mut fractional_part: u32,
1052             mut divisor: u32,
1053             prefix: &str,
1054             postfix: &str,
1055         ) -> fmt::Result {
1056             // Encode the fractional part into a temporary buffer. The buffer
1057             // only need to hold 9 elements, because `fractional_part` has to
1058             // be smaller than 10^9. The buffer is prefilled with '0' digits
1059             // to simplify the code below.
1060             let mut buf = [b'0'; 9];
1061
1062             // The next digit is written at this position
1063             let mut pos = 0;
1064
1065             // We keep writing digits into the buffer while there are non-zero
1066             // digits left and we haven't written enough digits yet.
1067             while fractional_part > 0 && pos < f.precision().unwrap_or(9) {
1068                 // Write new digit into the buffer
1069                 buf[pos] = b'0' + (fractional_part / divisor) as u8;
1070
1071                 fractional_part %= divisor;
1072                 divisor /= 10;
1073                 pos += 1;
1074             }
1075
1076             // If a precision < 9 was specified, there may be some non-zero
1077             // digits left that weren't written into the buffer. In that case we
1078             // need to perform rounding to match the semantics of printing
1079             // normal floating point numbers. However, we only need to do work
1080             // when rounding up. This happens if the first digit of the
1081             // remaining ones is >= 5.
1082             if fractional_part > 0 && fractional_part >= divisor * 5 {
1083                 // Round up the number contained in the buffer. We go through
1084                 // the buffer backwards and keep track of the carry.
1085                 let mut rev_pos = pos;
1086                 let mut carry = true;
1087                 while carry && rev_pos > 0 {
1088                     rev_pos -= 1;
1089
1090                     // If the digit in the buffer is not '9', we just need to
1091                     // increment it and can stop then (since we don't have a
1092                     // carry anymore). Otherwise, we set it to '0' (overflow)
1093                     // and continue.
1094                     if buf[rev_pos] < b'9' {
1095                         buf[rev_pos] += 1;
1096                         carry = false;
1097                     } else {
1098                         buf[rev_pos] = b'0';
1099                     }
1100                 }
1101
1102                 // If we still have the carry bit set, that means that we set
1103                 // the whole buffer to '0's and need to increment the integer
1104                 // part.
1105                 if carry {
1106                     integer_part += 1;
1107                 }
1108             }
1109
1110             // Determine the end of the buffer: if precision is set, we just
1111             // use as many digits from the buffer (capped to 9). If it isn't
1112             // set, we only use all digits up to the last non-zero one.
1113             let end = f.precision().map(|p| crate::cmp::min(p, 9)).unwrap_or(pos);
1114
1115             // This closure emits the formatted duration without emitting any
1116             // padding (padding is calculated below).
1117             let emit_without_padding = |f: &mut fmt::Formatter<'_>| {
1118                 write!(f, "{}{}", prefix, integer_part)?;
1119
1120                 // Write the decimal point and the fractional part (if any).
1121                 if end > 0 {
1122                     // SAFETY: We are only writing ASCII digits into the buffer and
1123                     // it was initialized with '0's, so it contains valid UTF8.
1124                     let s = unsafe { crate::str::from_utf8_unchecked(&buf[..end]) };
1125
1126                     // If the user request a precision > 9, we pad '0's at the end.
1127                     let w = f.precision().unwrap_or(pos);
1128                     write!(f, ".{:0<width$}", s, width = w)?;
1129                 }
1130
1131                 write!(f, "{}", postfix)
1132             };
1133
1134             match f.width() {
1135                 None => {
1136                     // No `width` specified. There's no need to calculate the
1137                     // length of the output in this case, just emit it.
1138                     emit_without_padding(f)
1139                 }
1140                 Some(requested_w) => {
1141                     // A `width` was specified. Calculate the actual width of
1142                     // the output in order to calculate the required padding.
1143                     // It consists of 4 parts:
1144                     // 1. The prefix: is either "+" or "", so we can just use len().
1145                     // 2. The postfix: can be "µs" so we have to count UTF8 characters.
1146                     let mut actual_w = prefix.len() + postfix.chars().count();
1147                     // 3. The integer part:
1148                     if let Some(log) = integer_part.checked_log10() {
1149                         // integer_part is > 0, so has length log10(x)+1
1150                         actual_w += 1 + log as usize;
1151                     } else {
1152                         // integer_part is 0, so has length 1.
1153                         actual_w += 1;
1154                     }
1155                     // 4. The fractional part (if any):
1156                     if end > 0 {
1157                         let frac_part_w = f.precision().unwrap_or(pos);
1158                         actual_w += 1 + frac_part_w;
1159                     }
1160
1161                     if requested_w <= actual_w {
1162                         // Output is already longer than `width`, so don't pad.
1163                         emit_without_padding(f)
1164                     } else {
1165                         // We need to add padding. Use the `Formatter::padding` helper function.
1166                         let default_align = crate::fmt::rt::v1::Alignment::Left;
1167                         let post_padding = f.padding(requested_w - actual_w, default_align)?;
1168                         emit_without_padding(f)?;
1169                         post_padding.write(f)
1170                     }
1171                 }
1172             }
1173         }
1174
1175         // Print leading '+' sign if requested
1176         let prefix = if f.sign_plus() { "+" } else { "" };
1177
1178         if self.secs > 0 {
1179             fmt_decimal(f, self.secs, self.nanos, NANOS_PER_SEC / 10, prefix, "s")
1180         } else if self.nanos >= NANOS_PER_MILLI {
1181             fmt_decimal(
1182                 f,
1183                 (self.nanos / NANOS_PER_MILLI) as u64,
1184                 self.nanos % NANOS_PER_MILLI,
1185                 NANOS_PER_MILLI / 10,
1186                 prefix,
1187                 "ms",
1188             )
1189         } else if self.nanos >= NANOS_PER_MICRO {
1190             fmt_decimal(
1191                 f,
1192                 (self.nanos / NANOS_PER_MICRO) as u64,
1193                 self.nanos % NANOS_PER_MICRO,
1194                 NANOS_PER_MICRO / 10,
1195                 prefix,
1196                 "µs",
1197             )
1198         } else {
1199             fmt_decimal(f, self.nanos as u64, 0, 1, prefix, "ns")
1200         }
1201     }
1202 }
1203
1204 /// An error which can be returned when converting a floating-point value of seconds
1205 /// into a [`Duration`].
1206 ///
1207 /// This error is used as the error type for [`Duration::try_from_secs_f32`] and
1208 /// [`Duration::try_from_secs_f64`].
1209 ///
1210 /// # Example
1211 ///
1212 /// ```
1213 /// #![feature(duration_checked_float)]
1214 /// use std::time::Duration;
1215 ///
1216 /// if let Err(e) = Duration::try_from_secs_f32(-1.0) {
1217 ///     println!("Failed conversion to Duration: {}", e);
1218 /// }
1219 /// ```
1220 #[derive(Debug, Clone, PartialEq, Eq)]
1221 #[unstable(feature = "duration_checked_float", issue = "83400")]
1222 pub struct FromFloatSecsError {
1223     kind: FromFloatSecsErrorKind,
1224 }
1225
1226 impl FromFloatSecsError {
1227     const fn description(&self) -> &'static str {
1228         match self.kind {
1229             FromFloatSecsErrorKind::Negative => {
1230                 "can not convert float seconds to Duration: value is negative"
1231             }
1232             FromFloatSecsErrorKind::OverflowOrNan => {
1233                 "can not convert float seconds to Duration: value is either too big or NaN"
1234             }
1235         }
1236     }
1237 }
1238
1239 #[unstable(feature = "duration_checked_float", issue = "83400")]
1240 impl fmt::Display for FromFloatSecsError {
1241     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1242         self.description().fmt(f)
1243     }
1244 }
1245
1246 #[derive(Debug, Clone, PartialEq, Eq)]
1247 enum FromFloatSecsErrorKind {
1248     // Value is negative.
1249     Negative,
1250     // Value is either too big to be represented as `Duration` or `NaN`.
1251     OverflowOrNan,
1252 }
1253
1254 macro_rules! try_from_secs {
1255     (
1256         secs = $secs: expr,
1257         mantissa_bits = $mant_bits: literal,
1258         exponent_bits = $exp_bits: literal,
1259         offset = $offset: literal,
1260         bits_ty = $bits_ty:ty,
1261         double_ty = $double_ty:ty,
1262     ) => {{
1263         const MIN_EXP: i16 = 1 - (1i16 << $exp_bits) / 2;
1264         const MANT_MASK: $bits_ty = (1 << $mant_bits) - 1;
1265         const EXP_MASK: $bits_ty = (1 << $exp_bits) - 1;
1266
1267         if $secs.is_sign_negative() {
1268             return Err(FromFloatSecsError { kind: FromFloatSecsErrorKind::Negative });
1269         }
1270
1271         let bits = $secs.to_bits();
1272         let mant = (bits & MANT_MASK) | (MANT_MASK + 1);
1273         let exp = ((bits >> $mant_bits) & EXP_MASK) as i16 + MIN_EXP;
1274
1275         let (secs, nanos) = if exp < -30 {
1276             // the input represents less than 1ns.
1277             (0u64, 0u32)
1278         } else if exp < 0 {
1279             // the input is less than 1 second
1280             let t = <$double_ty>::from(mant) << ($offset + exp);
1281             let nanos = (u128::from(NANOS_PER_SEC) * u128::from(t)) >> ($mant_bits + $offset);
1282             (0, nanos as u32)
1283         } else if exp < $mant_bits {
1284             let secs = mant >> ($mant_bits - exp);
1285             let t = <$double_ty>::from((mant << exp) & MANT_MASK);
1286             let nanos = (<$double_ty>::from(NANOS_PER_SEC) * t) >> $mant_bits;
1287             (u64::from(secs), nanos as u32)
1288         } else if exp < 64 {
1289             // the input has no fractional part
1290             let secs = u64::from(mant) << (exp - $mant_bits);
1291             (secs, 0)
1292         } else {
1293             return Err(FromFloatSecsError { kind: FromFloatSecsErrorKind::OverflowOrNan });
1294         };
1295
1296         Ok(Duration { secs, nanos })
1297     }};
1298 }
1299
1300 impl Duration {
1301     /// The checked version of [`from_secs_f32`].
1302     ///
1303     /// [`from_secs_f32`]: Duration::from_secs_f32
1304     ///
1305     /// This constructor will return an `Err` if `secs` is negative, overflows `Duration` or not finite.
1306     ///
1307     /// # Examples
1308     /// ```
1309     /// #![feature(duration_checked_float)]
1310     ///
1311     /// use std::time::Duration;
1312     ///
1313     /// let res = Duration::try_from_secs_f32(0.0);
1314     /// assert_eq!(res, Ok(Duration::new(0, 0)));
1315     /// let res = Duration::try_from_secs_f32(1e-20);
1316     /// assert_eq!(res, Ok(Duration::new(0, 0)));
1317     /// let res = Duration::try_from_secs_f32(4.2e-7);
1318     /// assert_eq!(res, Ok(Duration::new(0, 419)));
1319     /// let res = Duration::try_from_secs_f32(2.7);
1320     /// assert_eq!(res, Ok(Duration::new(2, 700_000_047)));
1321     /// let res = Duration::try_from_secs_f32(3e10);
1322     /// assert_eq!(res, Ok(Duration::new(30_000_001_024, 0)));
1323     /// // subnormal float:
1324     /// let res = Duration::try_from_secs_f32(f32::from_bits(1));
1325     /// assert_eq!(res, Ok(Duration::new(0, 0)));
1326     /// // conversion uses truncation, not rounding
1327     /// let res = Duration::try_from_secs_f32(0.999e-9);
1328     /// assert_eq!(res, Ok(Duration::new(0, 0)));
1329     ///
1330     /// let res = Duration::try_from_secs_f32(-5.0);
1331     /// assert!(res.is_err());
1332     /// let res = Duration::try_from_secs_f32(f32::NAN);
1333     /// assert!(res.is_err());
1334     /// let res = Duration::try_from_secs_f32(2e19);
1335     /// assert!(res.is_err());
1336     /// ```
1337     #[unstable(feature = "duration_checked_float", issue = "83400")]
1338     #[inline]
1339     pub const fn try_from_secs_f32(secs: f32) -> Result<Duration, FromFloatSecsError> {
1340         try_from_secs!(
1341             secs = secs,
1342             mantissa_bits = 23,
1343             exponent_bits = 8,
1344             offset = 41,
1345             bits_ty = u32,
1346             double_ty = u64,
1347         )
1348     }
1349
1350     /// The checked version of [`from_secs_f64`].
1351     ///
1352     /// [`from_secs_f64`]: Duration::from_secs_f64
1353     ///
1354     /// This constructor will return an `Err` if `secs` is negative, overflows `Duration` or not finite.
1355     ///
1356     /// # Examples
1357     /// ```
1358     /// #![feature(duration_checked_float)]
1359     ///
1360     /// use std::time::Duration;
1361     ///
1362     /// let res = Duration::try_from_secs_f64(0.0);
1363     /// assert_eq!(res, Ok(Duration::new(0, 0)));
1364     /// let res = Duration::try_from_secs_f64(1e-20);
1365     /// assert_eq!(res, Ok(Duration::new(0, 0)));
1366     /// let res = Duration::try_from_secs_f64(4.2e-7);
1367     /// assert_eq!(res, Ok(Duration::new(0, 420)));
1368     /// let res = Duration::try_from_secs_f64(2.7);
1369     /// assert_eq!(res, Ok(Duration::new(2, 700_000_000)));
1370     /// let res = Duration::try_from_secs_f64(3e10);
1371     /// assert_eq!(res, Ok(Duration::new(30_000_000_000, 0)));
1372     /// // subnormal float
1373     /// let res = Duration::try_from_secs_f64(f64::from_bits(1));
1374     /// assert_eq!(res, Ok(Duration::new(0, 0)));
1375     /// // conversion uses truncation, not rounding
1376     /// let res = Duration::try_from_secs_f32(0.999e-9);
1377     /// assert_eq!(res, Ok(Duration::new(0, 0)));
1378     ///
1379     /// let res = Duration::try_from_secs_f64(-5.0);
1380     /// assert!(res.is_err());
1381     /// let res = Duration::try_from_secs_f64(f64::NAN);
1382     /// assert!(res.is_err());
1383     /// let res = Duration::try_from_secs_f64(2e19);
1384     /// assert!(res.is_err());
1385     /// ```
1386     #[unstable(feature = "duration_checked_float", issue = "83400")]
1387     #[inline]
1388     pub const fn try_from_secs_f64(secs: f64) -> Result<Duration, FromFloatSecsError> {
1389         try_from_secs!(
1390             secs = secs,
1391             mantissa_bits = 52,
1392             exponent_bits = 11,
1393             offset = 44,
1394             bits_ty = u64,
1395             double_ty = u128,
1396         )
1397     }
1398 }