Skip to main content

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