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