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