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