core/
time.rs

1#![stable(feature = "duration_core", since = "1.25.0")]
2#![cfg_attr(feature = "ferrocene_subset", allow(dead_code))]
3
4//! Temporal quantification.
5//!
6//! # Examples:
7//!
8//! There are multiple ways to create a new [`Duration`]:
9//!
10//! ```
11//! # use std::time::Duration;
12//! let five_seconds = Duration::from_secs(5);
13//! assert_eq!(five_seconds, Duration::from_millis(5_000));
14//! assert_eq!(five_seconds, Duration::from_micros(5_000_000));
15//! assert_eq!(five_seconds, Duration::from_nanos(5_000_000_000));
16//!
17//! let ten_seconds = Duration::from_secs(10);
18//! let seven_nanos = Duration::from_nanos(7);
19//! let total = ten_seconds + seven_nanos;
20//! assert_eq!(total, Duration::new(10, 7));
21//! ```
22
23#[cfg(not(feature = "ferrocene_subset"))]
24use crate::fmt;
25#[cfg(not(feature = "ferrocene_subset"))]
26use crate::iter::Sum;
27use crate::num::niche_types::Nanoseconds;
28#[cfg(not(feature = "ferrocene_subset"))]
29use crate::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
30
31// Ferrocene addition: imports for certified subset
32#[cfg(feature = "ferrocene_subset")]
33#[rustfmt::skip]
34use crate::ops::{Add, Div, Sub};
35
36const NANOS_PER_SEC: u32 = 1_000_000_000;
37const NANOS_PER_MILLI: u32 = 1_000_000;
38const NANOS_PER_MICRO: u32 = 1_000;
39const MILLIS_PER_SEC: u64 = 1_000;
40const MICROS_PER_SEC: u64 = 1_000_000;
41#[unstable(feature = "duration_units", issue = "120301")]
42const SECS_PER_MINUTE: u64 = 60;
43#[unstable(feature = "duration_units", issue = "120301")]
44const MINS_PER_HOUR: u64 = 60;
45#[unstable(feature = "duration_units", issue = "120301")]
46const HOURS_PER_DAY: u64 = 24;
47#[unstable(feature = "duration_units", issue = "120301")]
48const DAYS_PER_WEEK: u64 = 7;
49
50/// A `Duration` type to represent a span of time, typically used for system
51/// timeouts.
52///
53/// Each `Duration` is composed of a whole number of seconds and a fractional part
54/// represented in nanoseconds. If the underlying system does not support
55/// nanosecond-level precision, APIs binding a system timeout will typically round up
56/// the number of nanoseconds.
57///
58/// [`Duration`]s implement many common traits, including [`Add`], [`Sub`], and other
59/// [`ops`] traits. It implements [`Default`] by returning a zero-length `Duration`.
60///
61/// [`ops`]: crate::ops
62///
63/// # Examples
64///
65/// ```
66/// use std::time::Duration;
67///
68/// let five_seconds = Duration::new(5, 0);
69/// let five_seconds_and_five_nanos = five_seconds + Duration::new(0, 5);
70///
71/// assert_eq!(five_seconds_and_five_nanos.as_secs(), 5);
72/// assert_eq!(five_seconds_and_five_nanos.subsec_nanos(), 5);
73///
74/// let ten_millis = Duration::from_millis(10);
75/// ```
76///
77/// # Formatting `Duration` values
78///
79/// `Duration` intentionally does not have a `Display` impl, as there are a
80/// variety of ways to format spans of time for human readability. `Duration`
81/// provides a `Debug` impl that shows the full precision of the value.
82///
83/// The `Debug` output uses the non-ASCII "µs" suffix for microseconds. If your
84/// program output may appear in contexts that cannot rely on full Unicode
85/// compatibility, you may wish to format `Duration` objects yourself or use a
86/// crate to do so.
87#[stable(feature = "duration", since = "1.3.0")]
88#[rustfmt::skip] // Ferrocene addition: avoid multi-line cfg_attr
89#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
90#[rustc_diagnostic_item = "Duration"]
91pub struct Duration {
92    secs: u64,
93    nanos: Nanoseconds, // Always 0 <= nanos < NANOS_PER_SEC
94}
95
96impl Duration {
97    /// The duration of one second.
98    ///
99    /// # Examples
100    ///
101    /// ```
102    /// #![feature(duration_constants)]
103    /// use std::time::Duration;
104    ///
105    /// assert_eq!(Duration::SECOND, Duration::from_secs(1));
106    /// ```
107    #[unstable(feature = "duration_constants", issue = "57391")]
108    pub const SECOND: Duration = Duration::from_secs(1);
109
110    /// The duration of one millisecond.
111    ///
112    /// # Examples
113    ///
114    /// ```
115    /// #![feature(duration_constants)]
116    /// use std::time::Duration;
117    ///
118    /// assert_eq!(Duration::MILLISECOND, Duration::from_millis(1));
119    /// ```
120    #[unstable(feature = "duration_constants", issue = "57391")]
121    pub const MILLISECOND: Duration = Duration::from_millis(1);
122
123    /// The duration of one microsecond.
124    ///
125    /// # Examples
126    ///
127    /// ```
128    /// #![feature(duration_constants)]
129    /// use std::time::Duration;
130    ///
131    /// assert_eq!(Duration::MICROSECOND, Duration::from_micros(1));
132    /// ```
133    #[unstable(feature = "duration_constants", issue = "57391")]
134    pub const MICROSECOND: Duration = Duration::from_micros(1);
135
136    /// The duration of one nanosecond.
137    ///
138    /// # Examples
139    ///
140    /// ```
141    /// #![feature(duration_constants)]
142    /// use std::time::Duration;
143    ///
144    /// assert_eq!(Duration::NANOSECOND, Duration::from_nanos(1));
145    /// ```
146    #[unstable(feature = "duration_constants", issue = "57391")]
147    pub const NANOSECOND: Duration = Duration::from_nanos(1);
148
149    /// A duration of zero time.
150    ///
151    /// # Examples
152    ///
153    /// ```
154    /// use std::time::Duration;
155    ///
156    /// let duration = Duration::ZERO;
157    /// assert!(duration.is_zero());
158    /// assert_eq!(duration.as_nanos(), 0);
159    /// ```
160    #[stable(feature = "duration_zero", since = "1.53.0")]
161    pub const ZERO: Duration = Duration::from_nanos(0);
162
163    /// The maximum duration.
164    ///
165    /// May vary by platform as necessary. Must be able to contain the difference between
166    /// two instances of [`Instant`] or two instances of [`SystemTime`].
167    /// This constraint gives it a value of about 584,942,417,355 years in practice,
168    /// which is currently used on all platforms.
169    ///
170    /// # Examples
171    ///
172    /// ```
173    /// use std::time::Duration;
174    ///
175    /// assert_eq!(Duration::MAX, Duration::new(u64::MAX, 1_000_000_000 - 1));
176    /// ```
177    /// [`Instant`]: ../../std/time/struct.Instant.html
178    /// [`SystemTime`]: ../../std/time/struct.SystemTime.html
179    #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
180    #[cfg(not(feature = "ferrocene_subset"))]
181    pub const MAX: Duration = Duration::new(u64::MAX, NANOS_PER_SEC - 1);
182
183    /// Creates a new `Duration` from the specified number of whole seconds and
184    /// additional nanoseconds.
185    ///
186    /// If the number of nanoseconds is greater than 1 billion (the number of
187    /// nanoseconds in a second), then it will carry over into the seconds provided.
188    ///
189    /// # Panics
190    ///
191    /// This constructor will panic if the carry from the nanoseconds overflows
192    /// the seconds counter.
193    ///
194    /// # Examples
195    ///
196    /// ```
197    /// use std::time::Duration;
198    ///
199    /// let five_seconds = Duration::new(5, 0);
200    /// ```
201    #[stable(feature = "duration", since = "1.3.0")]
202    #[inline]
203    #[must_use]
204    #[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
205    pub const fn new(secs: u64, nanos: u32) -> Duration {
206        if nanos < NANOS_PER_SEC {
207            // SAFETY: nanos < NANOS_PER_SEC, therefore nanos is within the valid range
208            Duration { secs, nanos: unsafe { Nanoseconds::new_unchecked(nanos) } }
209        } else {
210            let secs = secs
211                .checked_add((nanos / NANOS_PER_SEC) as u64)
212                .expect("overflow in Duration::new");
213            let nanos = nanos % NANOS_PER_SEC;
214            // SAFETY: nanos % NANOS_PER_SEC < NANOS_PER_SEC, therefore nanos is within the valid range
215            Duration { secs, nanos: unsafe { Nanoseconds::new_unchecked(nanos) } }
216        }
217    }
218
219    /// Creates a new `Duration` from the specified number of whole seconds.
220    ///
221    /// # Examples
222    ///
223    /// ```
224    /// use std::time::Duration;
225    ///
226    /// let duration = Duration::from_secs(5);
227    ///
228    /// assert_eq!(5, duration.as_secs());
229    /// assert_eq!(0, duration.subsec_nanos());
230    /// ```
231    #[stable(feature = "duration", since = "1.3.0")]
232    #[must_use]
233    #[inline]
234    #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
235    pub const fn from_secs(secs: u64) -> Duration {
236        Duration { secs, nanos: Nanoseconds::ZERO }
237    }
238
239    /// Creates a new `Duration` from the specified number of milliseconds.
240    ///
241    /// # Examples
242    ///
243    /// ```
244    /// use std::time::Duration;
245    ///
246    /// let duration = Duration::from_millis(2_569);
247    ///
248    /// assert_eq!(2, duration.as_secs());
249    /// assert_eq!(569_000_000, duration.subsec_nanos());
250    /// ```
251    #[stable(feature = "duration", since = "1.3.0")]
252    #[must_use]
253    #[inline]
254    #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
255    pub const fn from_millis(millis: u64) -> Duration {
256        let secs = millis / MILLIS_PER_SEC;
257        let subsec_millis = (millis % MILLIS_PER_SEC) as u32;
258        // SAFETY: (x % 1_000) * 1_000_000 < 1_000_000_000
259        //         => x % 1_000 < 1_000
260        let subsec_nanos = unsafe { Nanoseconds::new_unchecked(subsec_millis * NANOS_PER_MILLI) };
261
262        Duration { secs, nanos: subsec_nanos }
263    }
264
265    /// Creates a new `Duration` from the specified number of microseconds.
266    ///
267    /// # Examples
268    ///
269    /// ```
270    /// use std::time::Duration;
271    ///
272    /// let duration = Duration::from_micros(1_000_002);
273    ///
274    /// assert_eq!(1, duration.as_secs());
275    /// assert_eq!(2_000, duration.subsec_nanos());
276    /// ```
277    #[stable(feature = "duration_from_micros", since = "1.27.0")]
278    #[must_use]
279    #[inline]
280    #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
281    pub const fn from_micros(micros: u64) -> Duration {
282        let secs = micros / MICROS_PER_SEC;
283        let subsec_micros = (micros % MICROS_PER_SEC) as u32;
284        // SAFETY: (x % 1_000_000) * 1_000 < 1_000_000_000
285        //         => x % 1_000_000 < 1_000_000
286        let subsec_nanos = unsafe { Nanoseconds::new_unchecked(subsec_micros * NANOS_PER_MICRO) };
287
288        Duration { secs, nanos: subsec_nanos }
289    }
290
291    /// Creates a new `Duration` from the specified number of nanoseconds.
292    ///
293    /// Note: Using this on the return value of `as_nanos()` might cause unexpected behavior:
294    /// `as_nanos()` returns a u128, and can return values that do not fit in u64, e.g. 585 years.
295    /// Instead, consider using the pattern `Duration::new(d.as_secs(), d.subsec_nanos())`
296    /// if you cannot copy/clone the Duration directly.
297    ///
298    /// # Examples
299    ///
300    /// ```
301    /// use std::time::Duration;
302    ///
303    /// let duration = Duration::from_nanos(1_000_000_123);
304    ///
305    /// assert_eq!(1, duration.as_secs());
306    /// assert_eq!(123, duration.subsec_nanos());
307    /// ```
308    #[stable(feature = "duration_extras", since = "1.27.0")]
309    #[must_use]
310    #[inline]
311    #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
312    pub const fn from_nanos(nanos: u64) -> Duration {
313        const NANOS_PER_SEC: u64 = self::NANOS_PER_SEC as u64;
314        let secs = nanos / NANOS_PER_SEC;
315        let subsec_nanos = (nanos % NANOS_PER_SEC) as u32;
316        // SAFETY: x % 1_000_000_000 < 1_000_000_000
317        let subsec_nanos = unsafe { Nanoseconds::new_unchecked(subsec_nanos) };
318
319        Duration { secs, nanos: subsec_nanos }
320    }
321
322    /// Creates a new `Duration` from the specified number of nanoseconds.
323    ///
324    /// # Panics
325    ///
326    /// Panics if the given number of nanoseconds is greater than [`Duration::MAX`].
327    ///
328    /// # Examples
329    ///
330    /// ```
331    /// use std::time::Duration;
332    ///
333    /// let nanos = 10_u128.pow(24) + 321;
334    /// let duration = Duration::from_nanos_u128(nanos);
335    ///
336    /// assert_eq!(10_u64.pow(15), duration.as_secs());
337    /// assert_eq!(321, duration.subsec_nanos());
338    /// ```
339    #[stable(feature = "duration_from_nanos_u128", since = "CURRENT_RUSTC_VERSION")]
340    #[rustc_const_stable(feature = "duration_from_nanos_u128", since = "CURRENT_RUSTC_VERSION")]
341    #[must_use]
342    #[inline]
343    #[track_caller]
344    #[cfg(not(feature = "ferrocene_subset"))]
345    #[rustc_allow_const_fn_unstable(const_trait_impl, const_convert)] // for `u64::try_from`
346    pub const fn from_nanos_u128(nanos: u128) -> Duration {
347        const NANOS_PER_SEC: u128 = self::NANOS_PER_SEC as u128;
348        let Ok(secs) = u64::try_from(nanos / NANOS_PER_SEC) else {
349            panic!("overflow in `Duration::from_nanos_u128`");
350        };
351        let subsec_nanos = (nanos % NANOS_PER_SEC) as u32;
352        // SAFETY: x % 1_000_000_000 < 1_000_000_000 also, subsec_nanos >= 0 since u128 >=0 and u32 >=0
353        let subsec_nanos = unsafe { Nanoseconds::new_unchecked(subsec_nanos) };
354
355        Duration { secs: secs as u64, nanos: subsec_nanos }
356    }
357
358    /// Creates a new `Duration` from the specified number of weeks.
359    ///
360    /// # Panics
361    ///
362    /// Panics if the given number of weeks overflows the `Duration` size.
363    ///
364    /// # Examples
365    ///
366    /// ```
367    /// #![feature(duration_constructors)]
368    /// use std::time::Duration;
369    ///
370    /// let duration = Duration::from_weeks(4);
371    ///
372    /// assert_eq!(4 * 7 * 24 * 60 * 60, duration.as_secs());
373    /// assert_eq!(0, duration.subsec_nanos());
374    /// ```
375    #[unstable(feature = "duration_constructors", issue = "120301")]
376    #[must_use]
377    #[inline]
378    pub const fn from_weeks(weeks: u64) -> Duration {
379        if weeks > u64::MAX / (SECS_PER_MINUTE * MINS_PER_HOUR * HOURS_PER_DAY * DAYS_PER_WEEK) {
380            panic!("overflow in Duration::from_weeks");
381        }
382
383        Duration::from_secs(weeks * MINS_PER_HOUR * SECS_PER_MINUTE * HOURS_PER_DAY * DAYS_PER_WEEK)
384    }
385
386    /// Creates a new `Duration` from the specified number of days.
387    ///
388    /// # Panics
389    ///
390    /// Panics if the given number of days overflows the `Duration` size.
391    ///
392    /// # Examples
393    ///
394    /// ```
395    /// #![feature(duration_constructors)]
396    /// use std::time::Duration;
397    ///
398    /// let duration = Duration::from_days(7);
399    ///
400    /// assert_eq!(7 * 24 * 60 * 60, duration.as_secs());
401    /// assert_eq!(0, duration.subsec_nanos());
402    /// ```
403    #[unstable(feature = "duration_constructors", issue = "120301")]
404    #[must_use]
405    #[inline]
406    pub const fn from_days(days: u64) -> Duration {
407        if days > u64::MAX / (SECS_PER_MINUTE * MINS_PER_HOUR * HOURS_PER_DAY) {
408            panic!("overflow in Duration::from_days");
409        }
410
411        Duration::from_secs(days * MINS_PER_HOUR * SECS_PER_MINUTE * HOURS_PER_DAY)
412    }
413
414    /// Creates a new `Duration` from the specified number of hours.
415    ///
416    /// # Panics
417    ///
418    /// Panics if the given number of hours overflows the `Duration` size.
419    ///
420    /// # Examples
421    ///
422    /// ```
423    /// use std::time::Duration;
424    ///
425    /// let duration = Duration::from_hours(6);
426    ///
427    /// assert_eq!(6 * 60 * 60, duration.as_secs());
428    /// assert_eq!(0, duration.subsec_nanos());
429    /// ```
430    #[stable(feature = "duration_constructors_lite", since = "1.91.0")]
431    #[rustc_const_stable(feature = "duration_constructors_lite", since = "1.91.0")]
432    #[must_use]
433    #[inline]
434    pub const fn from_hours(hours: u64) -> Duration {
435        if hours > u64::MAX / (SECS_PER_MINUTE * MINS_PER_HOUR) {
436            panic!("overflow in Duration::from_hours");
437        }
438
439        Duration::from_secs(hours * MINS_PER_HOUR * SECS_PER_MINUTE)
440    }
441
442    /// Creates a new `Duration` from the specified number of minutes.
443    ///
444    /// # Panics
445    ///
446    /// Panics if the given number of minutes overflows the `Duration` size.
447    ///
448    /// # Examples
449    ///
450    /// ```
451    /// use std::time::Duration;
452    ///
453    /// let duration = Duration::from_mins(10);
454    ///
455    /// assert_eq!(10 * 60, duration.as_secs());
456    /// assert_eq!(0, duration.subsec_nanos());
457    /// ```
458    #[stable(feature = "duration_constructors_lite", since = "1.91.0")]
459    #[rustc_const_stable(feature = "duration_constructors_lite", since = "1.91.0")]
460    #[must_use]
461    #[inline]
462    pub const fn from_mins(mins: u64) -> Duration {
463        if mins > u64::MAX / SECS_PER_MINUTE {
464            panic!("overflow in Duration::from_mins");
465        }
466
467        Duration::from_secs(mins * SECS_PER_MINUTE)
468    }
469
470    /// Returns true if this `Duration` spans no time.
471    ///
472    /// # Examples
473    ///
474    /// ```
475    /// use std::time::Duration;
476    ///
477    /// assert!(Duration::ZERO.is_zero());
478    /// assert!(Duration::new(0, 0).is_zero());
479    /// assert!(Duration::from_nanos(0).is_zero());
480    /// assert!(Duration::from_secs(0).is_zero());
481    ///
482    /// assert!(!Duration::new(1, 1).is_zero());
483    /// assert!(!Duration::from_nanos(1).is_zero());
484    /// assert!(!Duration::from_secs(1).is_zero());
485    /// ```
486    #[must_use]
487    #[stable(feature = "duration_zero", since = "1.53.0")]
488    #[rustc_const_stable(feature = "duration_zero", since = "1.53.0")]
489    #[inline]
490    pub const fn is_zero(&self) -> bool {
491        self.secs == 0 && self.nanos.as_inner() == 0
492    }
493
494    /// Returns the number of _whole_ seconds contained by this `Duration`.
495    ///
496    /// The returned value does not include the fractional (nanosecond) part of the
497    /// duration, which can be obtained using [`subsec_nanos`].
498    ///
499    /// # Examples
500    ///
501    /// ```
502    /// use std::time::Duration;
503    ///
504    /// let duration = Duration::new(5, 730_023_852);
505    /// assert_eq!(duration.as_secs(), 5);
506    /// ```
507    ///
508    /// To determine the total number of seconds represented by the `Duration`
509    /// including the fractional part, use [`as_secs_f64`] or [`as_secs_f32`]
510    ///
511    /// [`as_secs_f64`]: Duration::as_secs_f64
512    /// [`as_secs_f32`]: Duration::as_secs_f32
513    /// [`subsec_nanos`]: Duration::subsec_nanos
514    #[stable(feature = "duration", since = "1.3.0")]
515    #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
516    #[must_use]
517    #[inline]
518    pub const fn as_secs(&self) -> u64 {
519        self.secs
520    }
521
522    /// Returns the fractional part of this `Duration`, in whole milliseconds.
523    ///
524    /// This method does **not** return the length of the duration when
525    /// represented by milliseconds. The returned number always represents a
526    /// fractional portion of a second (i.e., it is less than one thousand).
527    ///
528    /// # Examples
529    ///
530    /// ```
531    /// use std::time::Duration;
532    ///
533    /// let duration = Duration::from_millis(5_432);
534    /// assert_eq!(duration.as_secs(), 5);
535    /// assert_eq!(duration.subsec_millis(), 432);
536    /// ```
537    #[stable(feature = "duration_extras", since = "1.27.0")]
538    #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
539    #[must_use]
540    #[inline]
541    pub const fn subsec_millis(&self) -> u32 {
542        self.nanos.as_inner() / NANOS_PER_MILLI
543    }
544
545    /// Returns the fractional part of this `Duration`, in whole microseconds.
546    ///
547    /// This method does **not** return the length of the duration when
548    /// represented by microseconds. The returned number always represents a
549    /// fractional portion of a second (i.e., it is less than one million).
550    ///
551    /// # Examples
552    ///
553    /// ```
554    /// use std::time::Duration;
555    ///
556    /// let duration = Duration::from_micros(1_234_567);
557    /// assert_eq!(duration.as_secs(), 1);
558    /// assert_eq!(duration.subsec_micros(), 234_567);
559    /// ```
560    #[stable(feature = "duration_extras", since = "1.27.0")]
561    #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
562    #[must_use]
563    #[inline]
564    pub const fn subsec_micros(&self) -> u32 {
565        self.nanos.as_inner() / NANOS_PER_MICRO
566    }
567
568    /// Returns the fractional part of this `Duration`, in nanoseconds.
569    ///
570    /// This method does **not** return the length of the duration when
571    /// represented by nanoseconds. The returned number always represents a
572    /// fractional portion of a second (i.e., it is less than one billion).
573    ///
574    /// # Examples
575    ///
576    /// ```
577    /// use std::time::Duration;
578    ///
579    /// let duration = Duration::from_millis(5_010);
580    /// assert_eq!(duration.as_secs(), 5);
581    /// assert_eq!(duration.subsec_nanos(), 10_000_000);
582    /// ```
583    #[stable(feature = "duration", since = "1.3.0")]
584    #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
585    #[must_use]
586    #[inline]
587    pub const fn subsec_nanos(&self) -> u32 {
588        self.nanos.as_inner()
589    }
590
591    /// Returns the total number of whole milliseconds contained by this `Duration`.
592    ///
593    /// # Examples
594    ///
595    /// ```
596    /// use std::time::Duration;
597    ///
598    /// let duration = Duration::new(5, 730_023_852);
599    /// assert_eq!(duration.as_millis(), 5_730);
600    /// ```
601    #[stable(feature = "duration_as_u128", since = "1.33.0")]
602    #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
603    #[must_use]
604    #[inline]
605    pub const fn as_millis(&self) -> u128 {
606        self.secs as u128 * MILLIS_PER_SEC as u128
607            + (self.nanos.as_inner() / NANOS_PER_MILLI) as u128
608    }
609
610    /// Returns the total number of whole microseconds contained by this `Duration`.
611    ///
612    /// # Examples
613    ///
614    /// ```
615    /// use std::time::Duration;
616    ///
617    /// let duration = Duration::new(5, 730_023_852);
618    /// assert_eq!(duration.as_micros(), 5_730_023);
619    /// ```
620    #[stable(feature = "duration_as_u128", since = "1.33.0")]
621    #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
622    #[must_use]
623    #[inline]
624    pub const fn as_micros(&self) -> u128 {
625        self.secs as u128 * MICROS_PER_SEC as u128
626            + (self.nanos.as_inner() / NANOS_PER_MICRO) as u128
627    }
628
629    /// Returns the total number of nanoseconds contained by this `Duration`.
630    ///
631    /// # Examples
632    ///
633    /// ```
634    /// use std::time::Duration;
635    ///
636    /// let duration = Duration::new(5, 730_023_852);
637    /// assert_eq!(duration.as_nanos(), 5_730_023_852);
638    /// ```
639    #[stable(feature = "duration_as_u128", since = "1.33.0")]
640    #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
641    #[must_use]
642    #[inline]
643    pub const fn as_nanos(&self) -> u128 {
644        self.secs as u128 * NANOS_PER_SEC as u128 + self.nanos.as_inner() as u128
645    }
646
647    /// Computes the absolute difference between `self` and `other`.
648    ///
649    /// # Examples
650    ///
651    /// ```
652    /// use std::time::Duration;
653    ///
654    /// assert_eq!(Duration::new(100, 0).abs_diff(Duration::new(80, 0)), Duration::new(20, 0));
655    /// assert_eq!(Duration::new(100, 400_000_000).abs_diff(Duration::new(110, 0)), Duration::new(9, 600_000_000));
656    /// ```
657    #[stable(feature = "duration_abs_diff", since = "1.81.0")]
658    #[rustc_const_stable(feature = "duration_abs_diff", since = "1.81.0")]
659    #[must_use = "this returns the result of the operation, \
660                  without modifying the original"]
661    #[inline]
662    #[cfg(not(feature = "ferrocene_subset"))]
663    pub const fn abs_diff(self, other: Duration) -> Duration {
664        if let Some(res) = self.checked_sub(other) { res } else { other.checked_sub(self).unwrap() }
665    }
666
667    /// Checked `Duration` addition. Computes `self + other`, returning [`None`]
668    /// if overflow occurred.
669    ///
670    /// # Examples
671    ///
672    /// ```
673    /// use std::time::Duration;
674    ///
675    /// assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1)));
676    /// assert_eq!(Duration::new(1, 0).checked_add(Duration::new(u64::MAX, 0)), None);
677    /// ```
678    #[stable(feature = "duration_checked_ops", since = "1.16.0")]
679    #[must_use = "this returns the result of the operation, \
680                  without modifying the original"]
681    #[inline]
682    #[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
683    pub const fn checked_add(self, rhs: Duration) -> Option<Duration> {
684        if let Some(mut secs) = self.secs.checked_add(rhs.secs) {
685            let mut nanos = self.nanos.as_inner() + rhs.nanos.as_inner();
686            if nanos >= NANOS_PER_SEC {
687                nanos -= NANOS_PER_SEC;
688                let Some(new_secs) = secs.checked_add(1) else {
689                    return None;
690                };
691                secs = new_secs;
692            }
693            debug_assert!(nanos < NANOS_PER_SEC);
694            Some(Duration::new(secs, nanos))
695        } else {
696            None
697        }
698    }
699
700    /// Saturating `Duration` addition. Computes `self + other`, returning [`Duration::MAX`]
701    /// if overflow occurred.
702    ///
703    /// # Examples
704    ///
705    /// ```
706    /// #![feature(duration_constants)]
707    /// use std::time::Duration;
708    ///
709    /// assert_eq!(Duration::new(0, 0).saturating_add(Duration::new(0, 1)), Duration::new(0, 1));
710    /// assert_eq!(Duration::new(1, 0).saturating_add(Duration::new(u64::MAX, 0)), Duration::MAX);
711    /// ```
712    #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
713    #[must_use = "this returns the result of the operation, \
714                  without modifying the original"]
715    #[inline]
716    #[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
717    #[cfg(not(feature = "ferrocene_subset"))]
718    pub const fn saturating_add(self, rhs: Duration) -> Duration {
719        match self.checked_add(rhs) {
720            Some(res) => res,
721            None => Duration::MAX,
722        }
723    }
724
725    /// Checked `Duration` subtraction. Computes `self - other`, returning [`None`]
726    /// if the result would be negative or if overflow occurred.
727    ///
728    /// # Examples
729    ///
730    /// ```
731    /// use std::time::Duration;
732    ///
733    /// assert_eq!(Duration::new(0, 1).checked_sub(Duration::new(0, 0)), Some(Duration::new(0, 1)));
734    /// assert_eq!(Duration::new(0, 0).checked_sub(Duration::new(0, 1)), None);
735    /// ```
736    #[stable(feature = "duration_checked_ops", since = "1.16.0")]
737    #[must_use = "this returns the result of the operation, \
738                  without modifying the original"]
739    #[inline]
740    #[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
741    pub const fn checked_sub(self, rhs: Duration) -> Option<Duration> {
742        if let Some(mut secs) = self.secs.checked_sub(rhs.secs) {
743            let nanos = if self.nanos.as_inner() >= rhs.nanos.as_inner() {
744                self.nanos.as_inner() - rhs.nanos.as_inner()
745            } else if let Some(sub_secs) = secs.checked_sub(1) {
746                secs = sub_secs;
747                self.nanos.as_inner() + NANOS_PER_SEC - rhs.nanos.as_inner()
748            } else {
749                return None;
750            };
751            debug_assert!(nanos < NANOS_PER_SEC);
752            Some(Duration::new(secs, nanos))
753        } else {
754            None
755        }
756    }
757
758    /// Saturating `Duration` subtraction. Computes `self - other`, returning [`Duration::ZERO`]
759    /// if the result would be negative or if overflow occurred.
760    ///
761    /// # Examples
762    ///
763    /// ```
764    /// use std::time::Duration;
765    ///
766    /// assert_eq!(Duration::new(0, 1).saturating_sub(Duration::new(0, 0)), Duration::new(0, 1));
767    /// assert_eq!(Duration::new(0, 0).saturating_sub(Duration::new(0, 1)), Duration::ZERO);
768    /// ```
769    #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
770    #[must_use = "this returns the result of the operation, \
771                  without modifying the original"]
772    #[inline]
773    #[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
774    #[cfg(not(feature = "ferrocene_subset"))]
775    pub const fn saturating_sub(self, rhs: Duration) -> Duration {
776        match self.checked_sub(rhs) {
777            Some(res) => res,
778            None => Duration::ZERO,
779        }
780    }
781
782    /// Checked `Duration` multiplication. Computes `self * other`, returning
783    /// [`None`] if overflow occurred.
784    ///
785    /// # Examples
786    ///
787    /// ```
788    /// use std::time::Duration;
789    ///
790    /// assert_eq!(Duration::new(0, 500_000_001).checked_mul(2), Some(Duration::new(1, 2)));
791    /// assert_eq!(Duration::new(u64::MAX - 1, 0).checked_mul(2), None);
792    /// ```
793    #[stable(feature = "duration_checked_ops", since = "1.16.0")]
794    #[must_use = "this returns the result of the operation, \
795                  without modifying the original"]
796    #[inline]
797    #[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
798    #[cfg(not(feature = "ferrocene_subset"))]
799    pub const fn checked_mul(self, rhs: u32) -> Option<Duration> {
800        // Multiply nanoseconds as u64, because it cannot overflow that way.
801        let total_nanos = self.nanos.as_inner() as u64 * rhs as u64;
802        let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
803        let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
804        // FIXME(const-hack): use `and_then` once that is possible.
805        if let Some(s) = self.secs.checked_mul(rhs as u64) {
806            if let Some(secs) = s.checked_add(extra_secs) {
807                debug_assert!(nanos < NANOS_PER_SEC);
808                return Some(Duration::new(secs, nanos));
809            }
810        }
811        None
812    }
813
814    /// Saturating `Duration` multiplication. Computes `self * other`, returning
815    /// [`Duration::MAX`] if overflow occurred.
816    ///
817    /// # Examples
818    ///
819    /// ```
820    /// #![feature(duration_constants)]
821    /// use std::time::Duration;
822    ///
823    /// assert_eq!(Duration::new(0, 500_000_001).saturating_mul(2), Duration::new(1, 2));
824    /// assert_eq!(Duration::new(u64::MAX - 1, 0).saturating_mul(2), Duration::MAX);
825    /// ```
826    #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
827    #[must_use = "this returns the result of the operation, \
828                  without modifying the original"]
829    #[inline]
830    #[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
831    #[cfg(not(feature = "ferrocene_subset"))]
832    pub const fn saturating_mul(self, rhs: u32) -> Duration {
833        match self.checked_mul(rhs) {
834            Some(res) => res,
835            None => Duration::MAX,
836        }
837    }
838
839    /// Checked `Duration` division. Computes `self / other`, returning [`None`]
840    /// if `other == 0`.
841    ///
842    /// # Examples
843    ///
844    /// ```
845    /// use std::time::Duration;
846    ///
847    /// assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0)));
848    /// assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000)));
849    /// assert_eq!(Duration::new(2, 0).checked_div(0), None);
850    /// ```
851    #[stable(feature = "duration_checked_ops", since = "1.16.0")]
852    #[must_use = "this returns the result of the operation, \
853                  without modifying the original"]
854    #[inline]
855    #[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
856    pub const fn checked_div(self, rhs: u32) -> Option<Duration> {
857        if rhs != 0 {
858            let (secs, extra_secs) = (self.secs / (rhs as u64), self.secs % (rhs as u64));
859            let (mut nanos, extra_nanos) =
860                (self.nanos.as_inner() / rhs, self.nanos.as_inner() % rhs);
861            nanos +=
862                ((extra_secs * (NANOS_PER_SEC as u64) + extra_nanos as u64) / (rhs as u64)) as u32;
863            debug_assert!(nanos < NANOS_PER_SEC);
864            Some(Duration::new(secs, nanos))
865        } else {
866            None
867        }
868    }
869
870    /// Returns the number of seconds contained by this `Duration` as `f64`.
871    ///
872    /// The returned value includes the fractional (nanosecond) part of the duration.
873    ///
874    /// # Examples
875    /// ```
876    /// use std::time::Duration;
877    ///
878    /// let dur = Duration::new(2, 700_000_000);
879    /// assert_eq!(dur.as_secs_f64(), 2.7);
880    /// ```
881    #[stable(feature = "duration_float", since = "1.38.0")]
882    #[must_use]
883    #[inline]
884    #[rustc_const_stable(feature = "duration_consts_float", since = "1.83.0")]
885    pub const fn as_secs_f64(&self) -> f64 {
886        (self.secs as f64) + (self.nanos.as_inner() as f64) / (NANOS_PER_SEC as f64)
887    }
888
889    /// Returns the number of seconds contained by this `Duration` as `f32`.
890    ///
891    /// The returned value includes the fractional (nanosecond) part of the duration.
892    ///
893    /// # Examples
894    /// ```
895    /// use std::time::Duration;
896    ///
897    /// let dur = Duration::new(2, 700_000_000);
898    /// assert_eq!(dur.as_secs_f32(), 2.7);
899    /// ```
900    #[stable(feature = "duration_float", since = "1.38.0")]
901    #[must_use]
902    #[inline]
903    #[rustc_const_stable(feature = "duration_consts_float", since = "1.83.0")]
904    pub const fn as_secs_f32(&self) -> f32 {
905        (self.secs as f32) + (self.nanos.as_inner() as f32) / (NANOS_PER_SEC as f32)
906    }
907
908    /// Returns the number of milliseconds contained by this `Duration` as `f64`.
909    ///
910    /// The returned value includes the fractional (nanosecond) part of the duration.
911    ///
912    /// # Examples
913    /// ```
914    /// #![feature(duration_millis_float)]
915    /// use std::time::Duration;
916    ///
917    /// let dur = Duration::new(2, 345_678_000);
918    /// assert_eq!(dur.as_millis_f64(), 2_345.678);
919    /// ```
920    #[unstable(feature = "duration_millis_float", issue = "122451")]
921    #[must_use]
922    #[inline]
923    pub const fn as_millis_f64(&self) -> f64 {
924        (self.secs as f64) * (MILLIS_PER_SEC as f64)
925            + (self.nanos.as_inner() as f64) / (NANOS_PER_MILLI as f64)
926    }
927
928    /// Returns the number of milliseconds contained by this `Duration` as `f32`.
929    ///
930    /// The returned value includes the fractional (nanosecond) part of the duration.
931    ///
932    /// # Examples
933    /// ```
934    /// #![feature(duration_millis_float)]
935    /// use std::time::Duration;
936    ///
937    /// let dur = Duration::new(2, 345_678_000);
938    /// assert_eq!(dur.as_millis_f32(), 2_345.678);
939    /// ```
940    #[unstable(feature = "duration_millis_float", issue = "122451")]
941    #[must_use]
942    #[inline]
943    pub const fn as_millis_f32(&self) -> f32 {
944        (self.secs as f32) * (MILLIS_PER_SEC as f32)
945            + (self.nanos.as_inner() as f32) / (NANOS_PER_MILLI as f32)
946    }
947
948    /// Creates a new `Duration` from the specified number of seconds represented
949    /// as `f64`.
950    ///
951    /// # Panics
952    /// This constructor will panic if `secs` is negative, overflows `Duration` or not finite.
953    ///
954    /// # Examples
955    /// ```
956    /// use std::time::Duration;
957    ///
958    /// let res = Duration::from_secs_f64(0.0);
959    /// assert_eq!(res, Duration::new(0, 0));
960    /// let res = Duration::from_secs_f64(1e-20);
961    /// assert_eq!(res, Duration::new(0, 0));
962    /// let res = Duration::from_secs_f64(4.2e-7);
963    /// assert_eq!(res, Duration::new(0, 420));
964    /// let res = Duration::from_secs_f64(2.7);
965    /// assert_eq!(res, Duration::new(2, 700_000_000));
966    /// let res = Duration::from_secs_f64(3e10);
967    /// assert_eq!(res, Duration::new(30_000_000_000, 0));
968    /// // subnormal float
969    /// let res = Duration::from_secs_f64(f64::from_bits(1));
970    /// assert_eq!(res, Duration::new(0, 0));
971    /// // conversion uses rounding
972    /// let res = Duration::from_secs_f64(0.999e-9);
973    /// assert_eq!(res, Duration::new(0, 1));
974    /// ```
975    #[stable(feature = "duration_float", since = "1.38.0")]
976    #[must_use]
977    #[inline]
978    #[cfg(not(feature = "ferrocene_subset"))]
979    pub fn from_secs_f64(secs: f64) -> Duration {
980        match Duration::try_from_secs_f64(secs) {
981            Ok(v) => v,
982            Err(e) => panic!("{e}"),
983        }
984    }
985
986    /// Creates a new `Duration` from the specified number of seconds represented
987    /// as `f32`.
988    ///
989    /// # Panics
990    /// This constructor will panic if `secs` is negative, overflows `Duration` or not finite.
991    ///
992    /// # Examples
993    /// ```
994    /// use std::time::Duration;
995    ///
996    /// let res = Duration::from_secs_f32(0.0);
997    /// assert_eq!(res, Duration::new(0, 0));
998    /// let res = Duration::from_secs_f32(1e-20);
999    /// assert_eq!(res, Duration::new(0, 0));
1000    /// let res = Duration::from_secs_f32(4.2e-7);
1001    /// assert_eq!(res, Duration::new(0, 420));
1002    /// let res = Duration::from_secs_f32(2.7);
1003    /// assert_eq!(res, Duration::new(2, 700_000_048));
1004    /// let res = Duration::from_secs_f32(3e10);
1005    /// assert_eq!(res, Duration::new(30_000_001_024, 0));
1006    /// // subnormal float
1007    /// let res = Duration::from_secs_f32(f32::from_bits(1));
1008    /// assert_eq!(res, Duration::new(0, 0));
1009    /// // conversion uses rounding
1010    /// let res = Duration::from_secs_f32(0.999e-9);
1011    /// assert_eq!(res, Duration::new(0, 1));
1012    /// ```
1013    #[cfg_attr(feature = "ferrocene_certified_runtime", expect(unused_variables))]
1014    #[stable(feature = "duration_float", since = "1.38.0")]
1015    #[must_use]
1016    #[inline]
1017    pub fn from_secs_f32(secs: f32) -> Duration {
1018        match Duration::try_from_secs_f32(secs) {
1019            Ok(v) => v,
1020            Err(e) => panic!("{e}"),
1021        }
1022    }
1023
1024    /// Multiplies `Duration` by `f64`.
1025    ///
1026    /// # Panics
1027    /// This method will panic if result is negative, overflows `Duration` or not finite.
1028    ///
1029    /// # Examples
1030    /// ```
1031    /// use std::time::Duration;
1032    ///
1033    /// let dur = Duration::new(2, 700_000_000);
1034    /// assert_eq!(dur.mul_f64(3.14), Duration::new(8, 478_000_000));
1035    /// assert_eq!(dur.mul_f64(3.14e5), Duration::new(847_800, 0));
1036    /// ```
1037    #[stable(feature = "duration_float", since = "1.38.0")]
1038    #[must_use = "this returns the result of the operation, \
1039                  without modifying the original"]
1040    #[inline]
1041    #[cfg(not(feature = "ferrocene_subset"))]
1042    pub fn mul_f64(self, rhs: f64) -> Duration {
1043        Duration::from_secs_f64(rhs * self.as_secs_f64())
1044    }
1045
1046    /// Multiplies `Duration` by `f32`.
1047    ///
1048    /// # Panics
1049    /// This method will panic if result is negative, overflows `Duration` or not finite.
1050    ///
1051    /// # Examples
1052    /// ```
1053    /// use std::time::Duration;
1054    ///
1055    /// let dur = Duration::new(2, 700_000_000);
1056    /// assert_eq!(dur.mul_f32(3.14), Duration::new(8, 478_000_641));
1057    /// assert_eq!(dur.mul_f32(3.14e5), Duration::new(847_800, 0));
1058    /// ```
1059    #[stable(feature = "duration_float", since = "1.38.0")]
1060    #[must_use = "this returns the result of the operation, \
1061                  without modifying the original"]
1062    #[inline]
1063    #[cfg(not(feature = "ferrocene_subset"))]
1064    pub fn mul_f32(self, rhs: f32) -> Duration {
1065        Duration::from_secs_f32(rhs * self.as_secs_f32())
1066    }
1067
1068    /// Divides `Duration` by `f64`.
1069    ///
1070    /// # Panics
1071    /// This method will panic if result is negative, overflows `Duration` or not finite.
1072    ///
1073    /// # Examples
1074    /// ```
1075    /// use std::time::Duration;
1076    ///
1077    /// let dur = Duration::new(2, 700_000_000);
1078    /// assert_eq!(dur.div_f64(3.14), Duration::new(0, 859_872_611));
1079    /// assert_eq!(dur.div_f64(3.14e5), Duration::new(0, 8_599));
1080    /// ```
1081    #[stable(feature = "duration_float", since = "1.38.0")]
1082    #[must_use = "this returns the result of the operation, \
1083                  without modifying the original"]
1084    #[inline]
1085    #[cfg(not(feature = "ferrocene_subset"))]
1086    pub fn div_f64(self, rhs: f64) -> Duration {
1087        Duration::from_secs_f64(self.as_secs_f64() / rhs)
1088    }
1089
1090    /// Divides `Duration` by `f32`.
1091    ///
1092    /// # Panics
1093    /// This method will panic if result is negative, overflows `Duration` or not finite.
1094    ///
1095    /// # Examples
1096    /// ```
1097    /// use std::time::Duration;
1098    ///
1099    /// let dur = Duration::new(2, 700_000_000);
1100    /// // note that due to rounding errors result is slightly
1101    /// // different from 0.859_872_611
1102    /// assert_eq!(dur.div_f32(3.14), Duration::new(0, 859_872_580));
1103    /// assert_eq!(dur.div_f32(3.14e5), Duration::new(0, 8_599));
1104    /// ```
1105    #[stable(feature = "duration_float", since = "1.38.0")]
1106    #[must_use = "this returns the result of the operation, \
1107                  without modifying the original"]
1108    #[inline]
1109    #[cfg(not(feature = "ferrocene_subset"))]
1110    pub fn div_f32(self, rhs: f32) -> Duration {
1111        Duration::from_secs_f32(self.as_secs_f32() / rhs)
1112    }
1113
1114    /// Divides `Duration` by `Duration` and returns `f64`.
1115    ///
1116    /// # Examples
1117    /// ```
1118    /// use std::time::Duration;
1119    ///
1120    /// let dur1 = Duration::new(2, 700_000_000);
1121    /// let dur2 = Duration::new(5, 400_000_000);
1122    /// assert_eq!(dur1.div_duration_f64(dur2), 0.5);
1123    /// ```
1124    #[stable(feature = "div_duration", since = "1.80.0")]
1125    #[must_use = "this returns the result of the operation, \
1126                  without modifying the original"]
1127    #[inline]
1128    #[rustc_const_stable(feature = "duration_consts_float", since = "1.83.0")]
1129    pub const fn div_duration_f64(self, rhs: Duration) -> f64 {
1130        let self_nanos =
1131            (self.secs as f64) * (NANOS_PER_SEC as f64) + (self.nanos.as_inner() as f64);
1132        let rhs_nanos = (rhs.secs as f64) * (NANOS_PER_SEC as f64) + (rhs.nanos.as_inner() as f64);
1133        self_nanos / rhs_nanos
1134    }
1135
1136    /// Divides `Duration` by `Duration` and returns `f32`.
1137    ///
1138    /// # Examples
1139    /// ```
1140    /// use std::time::Duration;
1141    ///
1142    /// let dur1 = Duration::new(2, 700_000_000);
1143    /// let dur2 = Duration::new(5, 400_000_000);
1144    /// assert_eq!(dur1.div_duration_f32(dur2), 0.5);
1145    /// ```
1146    #[stable(feature = "div_duration", since = "1.80.0")]
1147    #[must_use = "this returns the result of the operation, \
1148                  without modifying the original"]
1149    #[inline]
1150    #[rustc_const_stable(feature = "duration_consts_float", since = "1.83.0")]
1151    pub const fn div_duration_f32(self, rhs: Duration) -> f32 {
1152        let self_nanos =
1153            (self.secs as f32) * (NANOS_PER_SEC as f32) + (self.nanos.as_inner() as f32);
1154        let rhs_nanos = (rhs.secs as f32) * (NANOS_PER_SEC as f32) + (rhs.nanos.as_inner() as f32);
1155        self_nanos / rhs_nanos
1156    }
1157}
1158
1159#[stable(feature = "duration", since = "1.3.0")]
1160#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
1161impl const Add for Duration {
1162    type Output = Duration;
1163
1164    #[inline]
1165    fn add(self, rhs: Duration) -> Duration {
1166        self.checked_add(rhs).expect("overflow when adding durations")
1167    }
1168}
1169
1170#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
1171#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
1172#[cfg(not(feature = "ferrocene_subset"))]
1173impl const AddAssign for Duration {
1174    #[inline]
1175    fn add_assign(&mut self, rhs: Duration) {
1176        *self = *self + rhs;
1177    }
1178}
1179
1180#[stable(feature = "duration", since = "1.3.0")]
1181#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
1182impl const Sub for Duration {
1183    type Output = Duration;
1184
1185    #[inline]
1186    fn sub(self, rhs: Duration) -> Duration {
1187        self.checked_sub(rhs).expect("overflow when subtracting durations")
1188    }
1189}
1190
1191#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
1192#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
1193#[cfg(not(feature = "ferrocene_subset"))]
1194impl const SubAssign for Duration {
1195    #[inline]
1196    fn sub_assign(&mut self, rhs: Duration) {
1197        *self = *self - rhs;
1198    }
1199}
1200
1201#[stable(feature = "duration", since = "1.3.0")]
1202#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
1203#[cfg(not(feature = "ferrocene_subset"))]
1204impl const Mul<u32> for Duration {
1205    type Output = Duration;
1206
1207    #[inline]
1208    fn mul(self, rhs: u32) -> Duration {
1209        self.checked_mul(rhs).expect("overflow when multiplying duration by scalar")
1210    }
1211}
1212
1213#[stable(feature = "symmetric_u32_duration_mul", since = "1.31.0")]
1214#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
1215#[cfg(not(feature = "ferrocene_subset"))]
1216impl const Mul<Duration> for u32 {
1217    type Output = Duration;
1218
1219    #[inline]
1220    fn mul(self, rhs: Duration) -> Duration {
1221        rhs * self
1222    }
1223}
1224
1225#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
1226#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
1227#[cfg(not(feature = "ferrocene_subset"))]
1228impl const MulAssign<u32> for Duration {
1229    #[inline]
1230    fn mul_assign(&mut self, rhs: u32) {
1231        *self = *self * rhs;
1232    }
1233}
1234
1235#[stable(feature = "duration", since = "1.3.0")]
1236#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
1237impl const Div<u32> for Duration {
1238    type Output = Duration;
1239
1240    #[inline]
1241    #[track_caller]
1242    fn div(self, rhs: u32) -> Duration {
1243        self.checked_div(rhs).expect("divide by zero error when dividing duration by scalar")
1244    }
1245}
1246
1247#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
1248#[rustc_const_unstable(feature = "const_ops", issue = "143802")]
1249#[cfg(not(feature = "ferrocene_subset"))]
1250impl const DivAssign<u32> for Duration {
1251    #[inline]
1252    #[track_caller]
1253    fn div_assign(&mut self, rhs: u32) {
1254        *self = *self / rhs;
1255    }
1256}
1257
1258#[cfg(not(feature = "ferrocene_subset"))]
1259macro_rules! sum_durations {
1260    ($iter:expr) => {{
1261        let mut total_secs: u64 = 0;
1262        let mut total_nanos: u64 = 0;
1263
1264        for entry in $iter {
1265            total_secs =
1266                total_secs.checked_add(entry.secs).expect("overflow in iter::sum over durations");
1267            total_nanos = match total_nanos.checked_add(entry.nanos.as_inner() as u64) {
1268                Some(n) => n,
1269                None => {
1270                    total_secs = total_secs
1271                        .checked_add(total_nanos / NANOS_PER_SEC as u64)
1272                        .expect("overflow in iter::sum over durations");
1273                    (total_nanos % NANOS_PER_SEC as u64) + entry.nanos.as_inner() as u64
1274                }
1275            };
1276        }
1277        total_secs = total_secs
1278            .checked_add(total_nanos / NANOS_PER_SEC as u64)
1279            .expect("overflow in iter::sum over durations");
1280        total_nanos = total_nanos % NANOS_PER_SEC as u64;
1281        Duration::new(total_secs, total_nanos as u32)
1282    }};
1283}
1284
1285#[stable(feature = "duration_sum", since = "1.16.0")]
1286#[cfg(not(feature = "ferrocene_subset"))]
1287impl Sum for Duration {
1288    fn sum<I: Iterator<Item = Duration>>(iter: I) -> Duration {
1289        sum_durations!(iter)
1290    }
1291}
1292
1293#[stable(feature = "duration_sum", since = "1.16.0")]
1294#[cfg(not(feature = "ferrocene_subset"))]
1295impl<'a> Sum<&'a Duration> for Duration {
1296    fn sum<I: Iterator<Item = &'a Duration>>(iter: I) -> Duration {
1297        sum_durations!(iter)
1298    }
1299}
1300
1301#[stable(feature = "duration_debug_impl", since = "1.27.0")]
1302#[cfg(not(feature = "ferrocene_subset"))]
1303impl fmt::Debug for Duration {
1304    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1305        /// Formats a floating point number in decimal notation.
1306        ///
1307        /// The number is given as the `integer_part` and a fractional part.
1308        /// The value of the fractional part is `fractional_part / divisor`. So
1309        /// `integer_part` = 3, `fractional_part` = 12 and `divisor` = 100
1310        /// represents the number `3.012`. Trailing zeros are omitted.
1311        ///
1312        /// `divisor` must not be above 100_000_000. It also should be a power
1313        /// of 10, everything else doesn't make sense. `fractional_part` has
1314        /// to be less than `10 * divisor`!
1315        ///
1316        /// A prefix and postfix may be added. The whole thing is padded
1317        /// to the formatter's `width`, if specified.
1318        fn fmt_decimal(
1319            f: &mut fmt::Formatter<'_>,
1320            integer_part: u64,
1321            mut fractional_part: u32,
1322            mut divisor: u32,
1323            prefix: &str,
1324            postfix: &str,
1325        ) -> fmt::Result {
1326            // Encode the fractional part into a temporary buffer. The buffer
1327            // only need to hold 9 elements, because `fractional_part` has to
1328            // be smaller than 10^9. The buffer is prefilled with '0' digits
1329            // to simplify the code below.
1330            let mut buf = [b'0'; 9];
1331
1332            // The next digit is written at this position
1333            let mut pos = 0;
1334
1335            // We keep writing digits into the buffer while there are non-zero
1336            // digits left and we haven't written enough digits yet.
1337            while fractional_part > 0 && pos < f.precision().unwrap_or(9) {
1338                // Write new digit into the buffer
1339                buf[pos] = b'0' + (fractional_part / divisor) as u8;
1340
1341                fractional_part %= divisor;
1342                divisor /= 10;
1343                pos += 1;
1344            }
1345
1346            // If a precision < 9 was specified, there may be some non-zero
1347            // digits left that weren't written into the buffer. In that case we
1348            // need to perform rounding to match the semantics of printing
1349            // normal floating point numbers. However, we only need to do work
1350            // when rounding up. This happens if the first digit of the
1351            // remaining ones is >= 5.
1352            let integer_part = if fractional_part > 0 && fractional_part >= divisor * 5 {
1353                // Round up the number contained in the buffer. We go through
1354                // the buffer backwards and keep track of the carry.
1355                let mut rev_pos = pos;
1356                let mut carry = true;
1357                while carry && rev_pos > 0 {
1358                    rev_pos -= 1;
1359
1360                    // If the digit in the buffer is not '9', we just need to
1361                    // increment it and can stop then (since we don't have a
1362                    // carry anymore). Otherwise, we set it to '0' (overflow)
1363                    // and continue.
1364                    if buf[rev_pos] < b'9' {
1365                        buf[rev_pos] += 1;
1366                        carry = false;
1367                    } else {
1368                        buf[rev_pos] = b'0';
1369                    }
1370                }
1371
1372                // If we still have the carry bit set, that means that we set
1373                // the whole buffer to '0's and need to increment the integer
1374                // part.
1375                if carry {
1376                    // If `integer_part == u64::MAX` and precision < 9, any
1377                    // carry of the overflow during rounding of the
1378                    // `fractional_part` into the `integer_part` will cause the
1379                    // `integer_part` itself to overflow. Avoid this by using an
1380                    // `Option<u64>`, with `None` representing `u64::MAX + 1`.
1381                    integer_part.checked_add(1)
1382                } else {
1383                    Some(integer_part)
1384                }
1385            } else {
1386                Some(integer_part)
1387            };
1388
1389            // Determine the end of the buffer: if precision is set, we just
1390            // use as many digits from the buffer (capped to 9). If it isn't
1391            // set, we only use all digits up to the last non-zero one.
1392            let end = f.precision().map(|p| crate::cmp::min(p, 9)).unwrap_or(pos);
1393
1394            // This closure emits the formatted duration without emitting any
1395            // padding (padding is calculated below).
1396            let emit_without_padding = |f: &mut fmt::Formatter<'_>| {
1397                if let Some(integer_part) = integer_part {
1398                    write!(f, "{}{}", prefix, integer_part)?;
1399                } else {
1400                    // u64::MAX + 1 == 18446744073709551616
1401                    write!(f, "{}18446744073709551616", prefix)?;
1402                }
1403
1404                // Write the decimal point and the fractional part (if any).
1405                if end > 0 {
1406                    // SAFETY: We are only writing ASCII digits into the buffer and
1407                    // it was initialized with '0's, so it contains valid UTF8.
1408                    let s = unsafe { crate::str::from_utf8_unchecked(&buf[..end]) };
1409
1410                    // If the user request a precision > 9, we pad '0's at the end.
1411                    let w = f.precision().unwrap_or(pos);
1412                    write!(f, ".{:0<width$}", s, width = w)?;
1413                }
1414
1415                write!(f, "{}", postfix)
1416            };
1417
1418            match f.width() {
1419                None => {
1420                    // No `width` specified. There's no need to calculate the
1421                    // length of the output in this case, just emit it.
1422                    emit_without_padding(f)
1423                }
1424                Some(requested_w) => {
1425                    // A `width` was specified. Calculate the actual width of
1426                    // the output in order to calculate the required padding.
1427                    // It consists of 4 parts:
1428                    // 1. The prefix: is either "+" or "", so we can just use len().
1429                    // 2. The postfix: can be "µs" so we have to count UTF8 characters.
1430                    let mut actual_w = prefix.len() + postfix.chars().count();
1431                    // 3. The integer part:
1432                    if let Some(integer_part) = integer_part {
1433                        if let Some(log) = integer_part.checked_ilog10() {
1434                            // integer_part is > 0, so has length log10(x)+1
1435                            actual_w += 1 + log as usize;
1436                        } else {
1437                            // integer_part is 0, so has length 1.
1438                            actual_w += 1;
1439                        }
1440                    } else {
1441                        // integer_part is u64::MAX + 1, so has length 20
1442                        actual_w += 20;
1443                    }
1444                    // 4. The fractional part (if any):
1445                    if end > 0 {
1446                        let frac_part_w = f.precision().unwrap_or(pos);
1447                        actual_w += 1 + frac_part_w;
1448                    }
1449
1450                    if requested_w <= actual_w {
1451                        // Output is already longer than `width`, so don't pad.
1452                        emit_without_padding(f)
1453                    } else {
1454                        // We need to add padding. Use the `Formatter::padding` helper function.
1455                        let default_align = fmt::Alignment::Left;
1456                        let post_padding =
1457                            f.padding((requested_w - actual_w) as u16, default_align)?;
1458                        emit_without_padding(f)?;
1459                        post_padding.write(f)
1460                    }
1461                }
1462            }
1463        }
1464
1465        // Print leading '+' sign if requested
1466        let prefix = if f.sign_plus() { "+" } else { "" };
1467
1468        if self.secs > 0 {
1469            fmt_decimal(f, self.secs, self.nanos.as_inner(), NANOS_PER_SEC / 10, prefix, "s")
1470        } else if self.nanos.as_inner() >= NANOS_PER_MILLI {
1471            fmt_decimal(
1472                f,
1473                (self.nanos.as_inner() / NANOS_PER_MILLI) as u64,
1474                self.nanos.as_inner() % NANOS_PER_MILLI,
1475                NANOS_PER_MILLI / 10,
1476                prefix,
1477                "ms",
1478            )
1479        } else if self.nanos.as_inner() >= NANOS_PER_MICRO {
1480            fmt_decimal(
1481                f,
1482                (self.nanos.as_inner() / NANOS_PER_MICRO) as u64,
1483                self.nanos.as_inner() % NANOS_PER_MICRO,
1484                NANOS_PER_MICRO / 10,
1485                prefix,
1486                "µs",
1487            )
1488        } else {
1489            fmt_decimal(f, self.nanos.as_inner() as u64, 0, 1, prefix, "ns")
1490        }
1491    }
1492}
1493
1494/// An error which can be returned when converting a floating-point value of seconds
1495/// into a [`Duration`].
1496///
1497/// This error is used as the error type for [`Duration::try_from_secs_f32`] and
1498/// [`Duration::try_from_secs_f64`].
1499///
1500/// # Example
1501///
1502/// ```
1503/// use std::time::Duration;
1504///
1505/// if let Err(e) = Duration::try_from_secs_f32(-1.0) {
1506///     println!("Failed conversion to Duration: {e}");
1507/// }
1508/// ```
1509#[cfg_attr(not(feature = "ferrocene_subset"), derive(Debug, Clone, PartialEq, Eq))]
1510#[stable(feature = "duration_checked_float", since = "1.66.0")]
1511pub struct TryFromFloatSecsError {
1512    kind: TryFromFloatSecsErrorKind,
1513}
1514
1515#[stable(feature = "duration_checked_float", since = "1.66.0")]
1516#[cfg(not(feature = "ferrocene_subset"))]
1517impl fmt::Display for TryFromFloatSecsError {
1518    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1519        match self.kind {
1520            TryFromFloatSecsErrorKind::Negative => {
1521                "cannot convert float seconds to Duration: value is negative"
1522            }
1523            TryFromFloatSecsErrorKind::OverflowOrNan => {
1524                "cannot convert float seconds to Duration: value is either too big or NaN"
1525            }
1526        }
1527        .fmt(f)
1528    }
1529}
1530
1531#[cfg_attr(not(feature = "ferrocene_subset"), derive(Debug, Clone, PartialEq, Eq))]
1532enum TryFromFloatSecsErrorKind {
1533    // Value is negative.
1534    Negative,
1535    // Value is either too big to be represented as `Duration` or `NaN`.
1536    OverflowOrNan,
1537}
1538
1539macro_rules! try_from_secs {
1540    (
1541        secs = $secs: expr,
1542        mantissa_bits = $mant_bits: literal,
1543        exponent_bits = $exp_bits: literal,
1544        offset = $offset: literal,
1545        bits_ty = $bits_ty:ty,
1546        double_ty = $double_ty:ty,
1547    ) => {{
1548        const MIN_EXP: i16 = 1 - (1i16 << $exp_bits) / 2;
1549        const MANT_MASK: $bits_ty = (1 << $mant_bits) - 1;
1550        const EXP_MASK: $bits_ty = (1 << $exp_bits) - 1;
1551
1552        if $secs < 0.0 {
1553            return Err(TryFromFloatSecsError { kind: TryFromFloatSecsErrorKind::Negative });
1554        }
1555
1556        let bits = $secs.to_bits();
1557        let mant = (bits & MANT_MASK) | (MANT_MASK + 1);
1558        let exp = ((bits >> $mant_bits) & EXP_MASK) as i16 + MIN_EXP;
1559
1560        let (secs, nanos) = if exp < -31 {
1561            // the input represents less than 1ns and can not be rounded to it
1562            (0u64, 0u32)
1563        } else if exp < 0 {
1564            // the input is less than 1 second
1565            let t = <$double_ty>::from(mant) << ($offset + exp);
1566            let nanos_offset = $mant_bits + $offset;
1567            let nanos_tmp = u128::from(NANOS_PER_SEC) * u128::from(t);
1568            let nanos = (nanos_tmp >> nanos_offset) as u32;
1569
1570            let rem_mask = (1 << nanos_offset) - 1;
1571            let rem_msb_mask = 1 << (nanos_offset - 1);
1572            let rem = nanos_tmp & rem_mask;
1573            let is_tie = rem == rem_msb_mask;
1574            let is_even = (nanos & 1) == 0;
1575            let rem_msb = nanos_tmp & rem_msb_mask == 0;
1576            let add_ns = !(rem_msb || (is_even && is_tie));
1577
1578            // f32 does not have enough precision to trigger the second branch
1579            // since it can not represent numbers between 0.999_999_940_395 and 1.0.
1580            let nanos = nanos + add_ns as u32;
1581            if ($mant_bits == 23) || (nanos != NANOS_PER_SEC) { (0, nanos) } else { (1, 0) }
1582        } else if exp < $mant_bits {
1583            let secs = u64::from(mant >> ($mant_bits - exp));
1584            let t = <$double_ty>::from((mant << exp) & MANT_MASK);
1585            let nanos_offset = $mant_bits;
1586            let nanos_tmp = <$double_ty>::from(NANOS_PER_SEC) * t;
1587            let nanos = (nanos_tmp >> nanos_offset) as u32;
1588
1589            let rem_mask = (1 << nanos_offset) - 1;
1590            let rem_msb_mask = 1 << (nanos_offset - 1);
1591            let rem = nanos_tmp & rem_mask;
1592            let is_tie = rem == rem_msb_mask;
1593            let is_even = (nanos & 1) == 0;
1594            let rem_msb = nanos_tmp & rem_msb_mask == 0;
1595            let add_ns = !(rem_msb || (is_even && is_tie));
1596
1597            // f32 does not have enough precision to trigger the second branch.
1598            // For example, it can not represent numbers between 1.999_999_880...
1599            // and 2.0. Bigger values result in even smaller precision of the
1600            // fractional part.
1601            let nanos = nanos + add_ns as u32;
1602            if ($mant_bits == 23) || (nanos != NANOS_PER_SEC) {
1603                (secs, nanos)
1604            } else {
1605                (secs + 1, 0)
1606            }
1607        } else if exp < 64 {
1608            // the input has no fractional part
1609            let secs = u64::from(mant) << (exp - $mant_bits);
1610            (secs, 0)
1611        } else {
1612            return Err(TryFromFloatSecsError { kind: TryFromFloatSecsErrorKind::OverflowOrNan });
1613        };
1614
1615        Ok(Duration::new(secs, nanos))
1616    }};
1617}
1618
1619impl Duration {
1620    /// The checked version of [`from_secs_f32`].
1621    ///
1622    /// [`from_secs_f32`]: Duration::from_secs_f32
1623    ///
1624    /// This constructor will return an `Err` if `secs` is negative, overflows `Duration` or not finite.
1625    ///
1626    /// # Examples
1627    /// ```
1628    /// use std::time::Duration;
1629    ///
1630    /// let res = Duration::try_from_secs_f32(0.0);
1631    /// assert_eq!(res, Ok(Duration::new(0, 0)));
1632    /// let res = Duration::try_from_secs_f32(1e-20);
1633    /// assert_eq!(res, Ok(Duration::new(0, 0)));
1634    /// let res = Duration::try_from_secs_f32(4.2e-7);
1635    /// assert_eq!(res, Ok(Duration::new(0, 420)));
1636    /// let res = Duration::try_from_secs_f32(2.7);
1637    /// assert_eq!(res, Ok(Duration::new(2, 700_000_048)));
1638    /// let res = Duration::try_from_secs_f32(3e10);
1639    /// assert_eq!(res, Ok(Duration::new(30_000_001_024, 0)));
1640    /// // subnormal float:
1641    /// let res = Duration::try_from_secs_f32(f32::from_bits(1));
1642    /// assert_eq!(res, Ok(Duration::new(0, 0)));
1643    ///
1644    /// let res = Duration::try_from_secs_f32(-5.0);
1645    /// assert!(res.is_err());
1646    /// let res = Duration::try_from_secs_f32(f32::NAN);
1647    /// assert!(res.is_err());
1648    /// let res = Duration::try_from_secs_f32(2e19);
1649    /// assert!(res.is_err());
1650    ///
1651    /// // the conversion uses rounding with tie resolution to even
1652    /// let res = Duration::try_from_secs_f32(0.999e-9);
1653    /// assert_eq!(res, Ok(Duration::new(0, 1)));
1654    ///
1655    /// // this float represents exactly 976562.5e-9
1656    /// let val = f32::from_bits(0x3A80_0000);
1657    /// let res = Duration::try_from_secs_f32(val);
1658    /// assert_eq!(res, Ok(Duration::new(0, 976_562)));
1659    ///
1660    /// // this float represents exactly 2929687.5e-9
1661    /// let val = f32::from_bits(0x3B40_0000);
1662    /// let res = Duration::try_from_secs_f32(val);
1663    /// assert_eq!(res, Ok(Duration::new(0, 2_929_688)));
1664    ///
1665    /// // this float represents exactly 1.000_976_562_5
1666    /// let val = f32::from_bits(0x3F802000);
1667    /// let res = Duration::try_from_secs_f32(val);
1668    /// assert_eq!(res, Ok(Duration::new(1, 976_562)));
1669    ///
1670    /// // this float represents exactly 1.002_929_687_5
1671    /// let val = f32::from_bits(0x3F806000);
1672    /// let res = Duration::try_from_secs_f32(val);
1673    /// assert_eq!(res, Ok(Duration::new(1, 2_929_688)));
1674    /// ```
1675    #[stable(feature = "duration_checked_float", since = "1.66.0")]
1676    #[inline]
1677    pub fn try_from_secs_f32(secs: f32) -> Result<Duration, TryFromFloatSecsError> {
1678        try_from_secs!(
1679            secs = secs,
1680            mantissa_bits = 23,
1681            exponent_bits = 8,
1682            offset = 41,
1683            bits_ty = u32,
1684            double_ty = u64,
1685        )
1686    }
1687
1688    /// The checked version of [`from_secs_f64`].
1689    ///
1690    /// [`from_secs_f64`]: Duration::from_secs_f64
1691    ///
1692    /// This constructor will return an `Err` if `secs` is negative, overflows `Duration` or not finite.
1693    ///
1694    /// # Examples
1695    /// ```
1696    /// use std::time::Duration;
1697    ///
1698    /// let res = Duration::try_from_secs_f64(0.0);
1699    /// assert_eq!(res, Ok(Duration::new(0, 0)));
1700    /// let res = Duration::try_from_secs_f64(1e-20);
1701    /// assert_eq!(res, Ok(Duration::new(0, 0)));
1702    /// let res = Duration::try_from_secs_f64(4.2e-7);
1703    /// assert_eq!(res, Ok(Duration::new(0, 420)));
1704    /// let res = Duration::try_from_secs_f64(2.7);
1705    /// assert_eq!(res, Ok(Duration::new(2, 700_000_000)));
1706    /// let res = Duration::try_from_secs_f64(3e10);
1707    /// assert_eq!(res, Ok(Duration::new(30_000_000_000, 0)));
1708    /// // subnormal float
1709    /// let res = Duration::try_from_secs_f64(f64::from_bits(1));
1710    /// assert_eq!(res, Ok(Duration::new(0, 0)));
1711    ///
1712    /// let res = Duration::try_from_secs_f64(-5.0);
1713    /// assert!(res.is_err());
1714    /// let res = Duration::try_from_secs_f64(f64::NAN);
1715    /// assert!(res.is_err());
1716    /// let res = Duration::try_from_secs_f64(2e19);
1717    /// assert!(res.is_err());
1718    ///
1719    /// // the conversion uses rounding with tie resolution to even
1720    /// let res = Duration::try_from_secs_f64(0.999e-9);
1721    /// assert_eq!(res, Ok(Duration::new(0, 1)));
1722    /// let res = Duration::try_from_secs_f64(0.999_999_999_499);
1723    /// assert_eq!(res, Ok(Duration::new(0, 999_999_999)));
1724    /// let res = Duration::try_from_secs_f64(0.999_999_999_501);
1725    /// assert_eq!(res, Ok(Duration::new(1, 0)));
1726    /// let res = Duration::try_from_secs_f64(42.999_999_999_499);
1727    /// assert_eq!(res, Ok(Duration::new(42, 999_999_999)));
1728    /// let res = Duration::try_from_secs_f64(42.999_999_999_501);
1729    /// assert_eq!(res, Ok(Duration::new(43, 0)));
1730    ///
1731    /// // this float represents exactly 976562.5e-9
1732    /// let val = f64::from_bits(0x3F50_0000_0000_0000);
1733    /// let res = Duration::try_from_secs_f64(val);
1734    /// assert_eq!(res, Ok(Duration::new(0, 976_562)));
1735    ///
1736    /// // this float represents exactly 2929687.5e-9
1737    /// let val = f64::from_bits(0x3F68_0000_0000_0000);
1738    /// let res = Duration::try_from_secs_f64(val);
1739    /// assert_eq!(res, Ok(Duration::new(0, 2_929_688)));
1740    ///
1741    /// // this float represents exactly 1.000_976_562_5
1742    /// let val = f64::from_bits(0x3FF0_0400_0000_0000);
1743    /// let res = Duration::try_from_secs_f64(val);
1744    /// assert_eq!(res, Ok(Duration::new(1, 976_562)));
1745    ///
1746    /// // this float represents exactly 1.002_929_687_5
1747    /// let val = f64::from_bits(0x3_FF00_C000_0000_000);
1748    /// let res = Duration::try_from_secs_f64(val);
1749    /// assert_eq!(res, Ok(Duration::new(1, 2_929_688)));
1750    /// ```
1751    #[stable(feature = "duration_checked_float", since = "1.66.0")]
1752    #[inline]
1753    #[cfg(not(feature = "ferrocene_subset"))]
1754    pub fn try_from_secs_f64(secs: f64) -> Result<Duration, TryFromFloatSecsError> {
1755        try_from_secs!(
1756            secs = secs,
1757            mantissa_bits = 52,
1758            exponent_bits = 11,
1759            offset = 44,
1760            bits_ty = u64,
1761            double_ty = u128,
1762        )
1763    }
1764}