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