1 #![stable(feature = "duration_core", since = "1.25.0")]
3 //! Temporal quantification.
7 //! There are multiple ways to create a new [`Duration`]:
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));
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));
24 use crate::ops
::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign}
;
26 const NANOS_PER_SEC
: u32 = 1_000_000_000;
27 const NANOS_PER_MILLI
: u32 = 1_000_000;
28 const NANOS_PER_MICRO
: u32 = 1_000;
29 const MILLIS_PER_SEC
: u64 = 1_000;
30 const MICROS_PER_SEC
: u64 = 1_000_000;
32 /// A `Duration` type to represent a span of time, typically used for system
35 /// Each `Duration` is composed of a whole number of seconds and a fractional part
36 /// represented in nanoseconds. If the underlying system does not support
37 /// nanosecond-level precision, APIs binding a system timeout will typically round up
38 /// the number of nanoseconds.
40 /// [`Duration`]s implement many common traits, including [`Add`], [`Sub`], and other
41 /// [`ops`] traits. It implements [`Default`] by returning a zero-length `Duration`.
43 /// [`ops`]: crate::ops
48 /// use std::time::Duration;
50 /// let five_seconds = Duration::new(5, 0);
51 /// let five_seconds_and_five_nanos = five_seconds + Duration::new(0, 5);
53 /// assert_eq!(five_seconds_and_five_nanos.as_secs(), 5);
54 /// assert_eq!(five_seconds_and_five_nanos.subsec_nanos(), 5);
56 /// let ten_millis = Duration::from_millis(10);
59 /// # Formatting `Duration` values
61 /// `Duration` intentionally does not have a `Display` impl, as there are a
62 /// variety of ways to format spans of time for human readability. `Duration`
63 /// provides a `Debug` impl that shows the full precision of the value.
65 /// The `Debug` output uses the non-ASCII "µs" suffix for microseconds. If your
66 /// program output may appear in contexts that cannot rely on full Unicode
67 /// compatibility, you may wish to format `Duration` objects yourself or use a
69 #[stable(feature = "duration", since = "1.3.0")]
70 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
71 #[cfg_attr(not(test), rustc_diagnostic_item = "Duration")]
74 nanos
: u32, // Always 0 <= nanos < NANOS_PER_SEC
78 /// The duration of one second.
83 /// #![feature(duration_constants)]
84 /// use std::time::Duration;
86 /// assert_eq!(Duration::SECOND, Duration::from_secs(1));
88 #[unstable(feature = "duration_constants", issue = "57391")]
89 pub const SECOND
: Duration
= Duration
::from_secs(1);
91 /// The duration of one millisecond.
96 /// #![feature(duration_constants)]
97 /// use std::time::Duration;
99 /// assert_eq!(Duration::MILLISECOND, Duration::from_millis(1));
101 #[unstable(feature = "duration_constants", issue = "57391")]
102 pub const MILLISECOND
: Duration
= Duration
::from_millis(1);
104 /// The duration of one microsecond.
109 /// #![feature(duration_constants)]
110 /// use std::time::Duration;
112 /// assert_eq!(Duration::MICROSECOND, Duration::from_micros(1));
114 #[unstable(feature = "duration_constants", issue = "57391")]
115 pub const MICROSECOND
: Duration
= Duration
::from_micros(1);
117 /// The duration of one nanosecond.
122 /// #![feature(duration_constants)]
123 /// use std::time::Duration;
125 /// assert_eq!(Duration::NANOSECOND, Duration::from_nanos(1));
127 #[unstable(feature = "duration_constants", issue = "57391")]
128 pub const NANOSECOND
: Duration
= Duration
::from_nanos(1);
130 /// A duration of zero time.
135 /// use std::time::Duration;
137 /// let duration = Duration::ZERO;
138 /// assert!(duration.is_zero());
139 /// assert_eq!(duration.as_nanos(), 0);
141 #[stable(feature = "duration_zero", since = "1.53.0")]
142 pub const ZERO
: Duration
= Duration
::from_nanos(0);
144 /// The maximum duration.
146 /// May vary by platform as necessary. Must be able to contain the difference between
147 /// two instances of [`Instant`] or two instances of [`SystemTime`].
148 /// This constraint gives it a value of about 584,942,417,355 years in practice,
149 /// which is currently used on all platforms.
154 /// use std::time::Duration;
156 /// assert_eq!(Duration::MAX, Duration::new(u64::MAX, 1_000_000_000 - 1));
158 /// [`Instant`]: ../../std/time/struct.Instant.html
159 /// [`SystemTime`]: ../../std/time/struct.SystemTime.html
160 #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
161 pub const MAX
: Duration
= Duration
::new(u64::MAX
, NANOS_PER_SEC
- 1);
163 /// Creates a new `Duration` from the specified number of whole seconds and
164 /// additional nanoseconds.
166 /// If the number of nanoseconds is greater than 1 billion (the number of
167 /// nanoseconds in a second), then it will carry over into the seconds provided.
171 /// This constructor will panic if the carry from the nanoseconds overflows
172 /// the seconds counter.
177 /// use std::time::Duration;
179 /// let five_seconds = Duration::new(5, 0);
181 #[stable(feature = "duration", since = "1.3.0")]
183 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
184 pub const fn new(secs
: u64, nanos
: u32) -> Duration
{
185 let secs
= match secs
.checked_add((nanos
/ NANOS_PER_SEC
) as u64) {
187 None
=> panic
!("overflow in Duration::new"),
189 let nanos
= nanos
% NANOS_PER_SEC
;
190 Duration { secs, nanos }
193 /// Creates a new `Duration` from the specified number of whole seconds.
198 /// use std::time::Duration;
200 /// let duration = Duration::from_secs(5);
202 /// assert_eq!(5, duration.as_secs());
203 /// assert_eq!(0, duration.subsec_nanos());
205 #[stable(feature = "duration", since = "1.3.0")]
207 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
208 pub const fn from_secs(secs
: u64) -> Duration
{
209 Duration { secs, nanos: 0 }
212 /// Creates a new `Duration` from the specified number of milliseconds.
217 /// use std::time::Duration;
219 /// let duration = Duration::from_millis(2569);
221 /// assert_eq!(2, duration.as_secs());
222 /// assert_eq!(569_000_000, duration.subsec_nanos());
224 #[stable(feature = "duration", since = "1.3.0")]
226 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
227 pub const fn from_millis(millis
: u64) -> Duration
{
229 secs
: millis
/ MILLIS_PER_SEC
,
230 nanos
: ((millis
% MILLIS_PER_SEC
) as u32) * NANOS_PER_MILLI
,
234 /// Creates a new `Duration` from the specified number of microseconds.
239 /// use std::time::Duration;
241 /// let duration = Duration::from_micros(1_000_002);
243 /// assert_eq!(1, duration.as_secs());
244 /// assert_eq!(2000, duration.subsec_nanos());
246 #[stable(feature = "duration_from_micros", since = "1.27.0")]
248 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
249 pub const fn from_micros(micros
: u64) -> Duration
{
251 secs
: micros
/ MICROS_PER_SEC
,
252 nanos
: ((micros
% MICROS_PER_SEC
) as u32) * NANOS_PER_MICRO
,
256 /// Creates a new `Duration` from the specified number of nanoseconds.
261 /// use std::time::Duration;
263 /// let duration = Duration::from_nanos(1_000_000_123);
265 /// assert_eq!(1, duration.as_secs());
266 /// assert_eq!(123, duration.subsec_nanos());
268 #[stable(feature = "duration_extras", since = "1.27.0")]
270 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
271 pub const fn from_nanos(nanos
: u64) -> Duration
{
273 secs
: nanos
/ (NANOS_PER_SEC
as u64),
274 nanos
: (nanos
% (NANOS_PER_SEC
as u64)) as u32,
278 /// Returns true if this `Duration` spans no time.
283 /// use std::time::Duration;
285 /// assert!(Duration::ZERO.is_zero());
286 /// assert!(Duration::new(0, 0).is_zero());
287 /// assert!(Duration::from_nanos(0).is_zero());
288 /// assert!(Duration::from_secs(0).is_zero());
290 /// assert!(!Duration::new(1, 1).is_zero());
291 /// assert!(!Duration::from_nanos(1).is_zero());
292 /// assert!(!Duration::from_secs(1).is_zero());
294 #[stable(feature = "duration_zero", since = "1.53.0")]
295 #[rustc_const_stable(feature = "duration_zero", since = "1.53.0")]
297 pub const fn is_zero(&self) -> bool
{
298 self.secs
== 0 && self.nanos
== 0
301 /// Returns the number of _whole_ seconds contained by this `Duration`.
303 /// The returned value does not include the fractional (nanosecond) part of the
304 /// duration, which can be obtained using [`subsec_nanos`].
309 /// use std::time::Duration;
311 /// let duration = Duration::new(5, 730023852);
312 /// assert_eq!(duration.as_secs(), 5);
315 /// To determine the total number of seconds represented by the `Duration`,
316 /// use `as_secs` in combination with [`subsec_nanos`]:
319 /// use std::time::Duration;
321 /// let duration = Duration::new(5, 730023852);
323 /// assert_eq!(5.730023852,
324 /// duration.as_secs() as f64
325 /// + duration.subsec_nanos() as f64 * 1e-9);
328 /// [`subsec_nanos`]: Duration::subsec_nanos
329 #[stable(feature = "duration", since = "1.3.0")]
330 #[rustc_const_stable(feature = "duration", since = "1.32.0")]
332 pub const fn as_secs(&self) -> u64 {
336 /// Returns the fractional part of this `Duration`, in whole milliseconds.
338 /// This method does **not** return the length of the duration when
339 /// represented by milliseconds. The returned number always represents a
340 /// fractional portion of a second (i.e., it is less than one thousand).
345 /// use std::time::Duration;
347 /// let duration = Duration::from_millis(5432);
348 /// assert_eq!(duration.as_secs(), 5);
349 /// assert_eq!(duration.subsec_millis(), 432);
351 #[stable(feature = "duration_extras", since = "1.27.0")]
352 #[rustc_const_stable(feature = "duration_extras", since = "1.32.0")]
354 pub const fn subsec_millis(&self) -> u32 {
355 self.nanos
/ NANOS_PER_MILLI
358 /// Returns the fractional part of this `Duration`, in whole microseconds.
360 /// This method does **not** return the length of the duration when
361 /// represented by microseconds. The returned number always represents a
362 /// fractional portion of a second (i.e., it is less than one million).
367 /// use std::time::Duration;
369 /// let duration = Duration::from_micros(1_234_567);
370 /// assert_eq!(duration.as_secs(), 1);
371 /// assert_eq!(duration.subsec_micros(), 234_567);
373 #[stable(feature = "duration_extras", since = "1.27.0")]
374 #[rustc_const_stable(feature = "duration_extras", since = "1.32.0")]
376 pub const fn subsec_micros(&self) -> u32 {
377 self.nanos
/ NANOS_PER_MICRO
380 /// Returns the fractional part of this `Duration`, in nanoseconds.
382 /// This method does **not** return the length of the duration when
383 /// represented by nanoseconds. The returned number always represents a
384 /// fractional portion of a second (i.e., it is less than one billion).
389 /// use std::time::Duration;
391 /// let duration = Duration::from_millis(5010);
392 /// assert_eq!(duration.as_secs(), 5);
393 /// assert_eq!(duration.subsec_nanos(), 10_000_000);
395 #[stable(feature = "duration", since = "1.3.0")]
396 #[rustc_const_stable(feature = "duration", since = "1.32.0")]
398 pub const fn subsec_nanos(&self) -> u32 {
402 /// Returns the total number of whole milliseconds contained by this `Duration`.
407 /// use std::time::Duration;
409 /// let duration = Duration::new(5, 730023852);
410 /// assert_eq!(duration.as_millis(), 5730);
412 #[stable(feature = "duration_as_u128", since = "1.33.0")]
413 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
415 pub const fn as_millis(&self) -> u128
{
416 self.secs
as u128
* MILLIS_PER_SEC
as u128
+ (self.nanos
/ NANOS_PER_MILLI
) as u128
419 /// Returns the total number of whole microseconds contained by this `Duration`.
424 /// use std::time::Duration;
426 /// let duration = Duration::new(5, 730023852);
427 /// assert_eq!(duration.as_micros(), 5730023);
429 #[stable(feature = "duration_as_u128", since = "1.33.0")]
430 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
432 pub const fn as_micros(&self) -> u128
{
433 self.secs
as u128
* MICROS_PER_SEC
as u128
+ (self.nanos
/ NANOS_PER_MICRO
) as u128
436 /// Returns the total number of nanoseconds contained by this `Duration`.
441 /// use std::time::Duration;
443 /// let duration = Duration::new(5, 730023852);
444 /// assert_eq!(duration.as_nanos(), 5730023852);
446 #[stable(feature = "duration_as_u128", since = "1.33.0")]
447 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
449 pub const fn as_nanos(&self) -> u128
{
450 self.secs
as u128
* NANOS_PER_SEC
as u128
+ self.nanos
as u128
453 /// Checked `Duration` addition. Computes `self + other`, returning [`None`]
454 /// if overflow occurred.
461 /// use std::time::Duration;
463 /// assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1)));
464 /// assert_eq!(Duration::new(1, 0).checked_add(Duration::new(u64::MAX, 0)), None);
466 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
468 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
469 pub const fn checked_add(self, rhs
: Duration
) -> Option
<Duration
> {
470 if let Some(mut secs
) = self.secs
.checked_add(rhs
.secs
) {
471 let mut nanos
= self.nanos
+ rhs
.nanos
;
472 if nanos
>= NANOS_PER_SEC
{
473 nanos
-= NANOS_PER_SEC
;
474 if let Some(new_secs
) = secs
.checked_add(1) {
480 debug_assert
!(nanos
< NANOS_PER_SEC
);
481 Some(Duration { secs, nanos }
)
487 /// Saturating `Duration` addition. Computes `self + other`, returning [`Duration::MAX`]
488 /// if overflow occurred.
493 /// #![feature(duration_constants)]
494 /// use std::time::Duration;
496 /// assert_eq!(Duration::new(0, 0).saturating_add(Duration::new(0, 1)), Duration::new(0, 1));
497 /// assert_eq!(Duration::new(1, 0).saturating_add(Duration::new(u64::MAX, 0)), Duration::MAX);
499 #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
501 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
502 pub const fn saturating_add(self, rhs
: Duration
) -> Duration
{
503 match self.checked_add(rhs
) {
505 None
=> Duration
::MAX
,
509 /// Checked `Duration` subtraction. Computes `self - other`, returning [`None`]
510 /// if the result would be negative or if overflow occurred.
517 /// use std::time::Duration;
519 /// assert_eq!(Duration::new(0, 1).checked_sub(Duration::new(0, 0)), Some(Duration::new(0, 1)));
520 /// assert_eq!(Duration::new(0, 0).checked_sub(Duration::new(0, 1)), None);
522 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
524 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
525 pub const fn checked_sub(self, rhs
: Duration
) -> Option
<Duration
> {
526 if let Some(mut secs
) = self.secs
.checked_sub(rhs
.secs
) {
527 let nanos
= if self.nanos
>= rhs
.nanos
{
528 self.nanos
- rhs
.nanos
529 } else if let Some(sub_secs
) = secs
.checked_sub(1) {
531 self.nanos
+ NANOS_PER_SEC
- rhs
.nanos
535 debug_assert
!(nanos
< NANOS_PER_SEC
);
536 Some(Duration { secs, nanos }
)
542 /// Saturating `Duration` subtraction. Computes `self - other`, returning [`Duration::ZERO`]
543 /// if the result would be negative or if overflow occurred.
548 /// use std::time::Duration;
550 /// assert_eq!(Duration::new(0, 1).saturating_sub(Duration::new(0, 0)), Duration::new(0, 1));
551 /// assert_eq!(Duration::new(0, 0).saturating_sub(Duration::new(0, 1)), Duration::ZERO);
553 #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
555 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
556 pub const fn saturating_sub(self, rhs
: Duration
) -> Duration
{
557 match self.checked_sub(rhs
) {
559 None
=> Duration
::ZERO
,
563 /// Checked `Duration` multiplication. Computes `self * other`, returning
564 /// [`None`] if overflow occurred.
571 /// use std::time::Duration;
573 /// assert_eq!(Duration::new(0, 500_000_001).checked_mul(2), Some(Duration::new(1, 2)));
574 /// assert_eq!(Duration::new(u64::MAX - 1, 0).checked_mul(2), None);
576 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
578 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
579 pub const fn checked_mul(self, rhs
: u32) -> Option
<Duration
> {
580 // Multiply nanoseconds as u64, because it cannot overflow that way.
581 let total_nanos
= self.nanos
as u64 * rhs
as u64;
582 let extra_secs
= total_nanos
/ (NANOS_PER_SEC
as u64);
583 let nanos
= (total_nanos
% (NANOS_PER_SEC
as u64)) as u32;
584 if let Some(s
) = self.secs
.checked_mul(rhs
as u64) {
585 if let Some(secs
) = s
.checked_add(extra_secs
) {
586 debug_assert
!(nanos
< NANOS_PER_SEC
);
587 return Some(Duration { secs, nanos }
);
593 /// Saturating `Duration` multiplication. Computes `self * other`, returning
594 /// [`Duration::MAX`] if overflow occurred.
599 /// #![feature(duration_constants)]
600 /// use std::time::Duration;
602 /// assert_eq!(Duration::new(0, 500_000_001).saturating_mul(2), Duration::new(1, 2));
603 /// assert_eq!(Duration::new(u64::MAX - 1, 0).saturating_mul(2), Duration::MAX);
605 #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
607 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
608 pub const fn saturating_mul(self, rhs
: u32) -> Duration
{
609 match self.checked_mul(rhs
) {
611 None
=> Duration
::MAX
,
615 /// Checked `Duration` division. Computes `self / other`, returning [`None`]
623 /// use std::time::Duration;
625 /// assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0)));
626 /// assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000)));
627 /// assert_eq!(Duration::new(2, 0).checked_div(0), None);
629 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
631 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
632 pub const fn checked_div(self, rhs
: u32) -> Option
<Duration
> {
634 let secs
= self.secs
/ (rhs
as u64);
635 let carry
= self.secs
- secs
* (rhs
as u64);
636 let extra_nanos
= carry
* (NANOS_PER_SEC
as u64) / (rhs
as u64);
637 let nanos
= self.nanos
/ rhs
+ (extra_nanos
as u32);
638 debug_assert
!(nanos
< NANOS_PER_SEC
);
639 Some(Duration { secs, nanos }
)
645 /// Returns the number of seconds contained by this `Duration` as `f64`.
647 /// The returned value does include the fractional (nanosecond) part of the duration.
651 /// use std::time::Duration;
653 /// let dur = Duration::new(2, 700_000_000);
654 /// assert_eq!(dur.as_secs_f64(), 2.7);
656 #[stable(feature = "duration_float", since = "1.38.0")]
658 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
659 pub const fn as_secs_f64(&self) -> f64 {
660 (self.secs
as f64) + (self.nanos
as f64) / (NANOS_PER_SEC
as f64)
663 /// Returns the number of seconds contained by this `Duration` as `f32`.
665 /// The returned value does include the fractional (nanosecond) part of the duration.
669 /// use std::time::Duration;
671 /// let dur = Duration::new(2, 700_000_000);
672 /// assert_eq!(dur.as_secs_f32(), 2.7);
674 #[stable(feature = "duration_float", since = "1.38.0")]
676 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
677 pub const fn as_secs_f32(&self) -> f32 {
678 (self.secs
as f32) + (self.nanos
as f32) / (NANOS_PER_SEC
as f32)
681 /// Creates a new `Duration` from the specified number of seconds represented
685 /// This constructor will panic if `secs` is not finite, negative or overflows `Duration`.
689 /// use std::time::Duration;
691 /// let dur = Duration::from_secs_f64(2.7);
692 /// assert_eq!(dur, Duration::new(2, 700_000_000));
694 #[stable(feature = "duration_float", since = "1.38.0")]
696 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
697 pub const fn from_secs_f64(secs
: f64) -> Duration
{
698 match Duration
::try_from_secs_f64(secs
) {
700 Err(e
) => crate::panicking
::panic(e
.description()),
704 /// The checked version of [`from_secs_f64`].
706 /// [`from_secs_f64`]: Duration::from_secs_f64
708 /// This constructor will return an `Err` if `secs` is not finite, negative or overflows `Duration`.
712 /// #![feature(duration_checked_float)]
714 /// use std::time::Duration;
716 /// let dur = Duration::try_from_secs_f64(2.7);
717 /// assert_eq!(dur, Ok(Duration::new(2, 700_000_000)));
719 /// let negative = Duration::try_from_secs_f64(-5.0);
720 /// assert!(negative.is_err());
722 #[unstable(feature = "duration_checked_float", issue = "83400")]
724 pub const fn try_from_secs_f64(secs
: f64) -> Result
<Duration
, FromSecsError
> {
725 const MAX_NANOS_F64
: f64 = ((u64::MAX
as u128
+ 1) * (NANOS_PER_SEC
as u128
)) as f64;
726 let nanos
= secs
* (NANOS_PER_SEC
as f64);
727 if !nanos
.is_finite() {
728 Err(FromSecsError { kind: FromSecsErrorKind::NonFinite }
)
729 } else if nanos
>= MAX_NANOS_F64
{
730 Err(FromSecsError { kind: FromSecsErrorKind::Overflow }
)
731 } else if nanos
< 0.0 {
732 Err(FromSecsError { kind: FromSecsErrorKind::Underflow }
)
734 let nanos
= nanos
as u128
;
736 secs
: (nanos
/ (NANOS_PER_SEC
as u128
)) as u64,
737 nanos
: (nanos
% (NANOS_PER_SEC
as u128
)) as u32,
742 /// Creates a new `Duration` from the specified number of seconds represented
746 /// This constructor will panic if `secs` is not finite, negative or overflows `Duration`.
750 /// use std::time::Duration;
752 /// let dur = Duration::from_secs_f32(2.7);
753 /// assert_eq!(dur, Duration::new(2, 700_000_000));
755 #[stable(feature = "duration_float", since = "1.38.0")]
757 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
758 pub const fn from_secs_f32(secs
: f32) -> Duration
{
759 match Duration
::try_from_secs_f32(secs
) {
761 Err(e
) => crate::panicking
::panic(e
.description()),
765 /// The checked version of [`from_secs_f32`].
767 /// [`from_secs_f32`]: Duration::from_secs_f32
769 /// This constructor will return an `Err` if `secs` is not finite, negative or overflows `Duration`.
773 /// #![feature(duration_checked_float)]
775 /// use std::time::Duration;
777 /// let dur = Duration::try_from_secs_f32(2.7);
778 /// assert_eq!(dur, Ok(Duration::new(2, 700_000_000)));
780 /// let negative = Duration::try_from_secs_f32(-5.0);
781 /// assert!(negative.is_err());
783 #[unstable(feature = "duration_checked_float", issue = "83400")]
785 pub const fn try_from_secs_f32(secs
: f32) -> Result
<Duration
, FromSecsError
> {
786 const MAX_NANOS_F32
: f32 = ((u64::MAX
as u128
+ 1) * (NANOS_PER_SEC
as u128
)) as f32;
787 let nanos
= secs
* (NANOS_PER_SEC
as f32);
788 if !nanos
.is_finite() {
789 Err(FromSecsError { kind: FromSecsErrorKind::NonFinite }
)
790 } else if nanos
>= MAX_NANOS_F32
{
791 Err(FromSecsError { kind: FromSecsErrorKind::Overflow }
)
792 } else if nanos
< 0.0 {
793 Err(FromSecsError { kind: FromSecsErrorKind::Underflow }
)
795 let nanos
= nanos
as u128
;
797 secs
: (nanos
/ (NANOS_PER_SEC
as u128
)) as u64,
798 nanos
: (nanos
% (NANOS_PER_SEC
as u128
)) as u32,
803 /// Multiplies `Duration` by `f64`.
806 /// This method will panic if result is not finite, negative or overflows `Duration`.
810 /// use std::time::Duration;
812 /// let dur = Duration::new(2, 700_000_000);
813 /// assert_eq!(dur.mul_f64(3.14), Duration::new(8, 478_000_000));
814 /// assert_eq!(dur.mul_f64(3.14e5), Duration::new(847_800, 0));
816 #[stable(feature = "duration_float", since = "1.38.0")]
818 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
819 pub const fn mul_f64(self, rhs
: f64) -> Duration
{
820 Duration
::from_secs_f64(rhs
* self.as_secs_f64())
823 /// Multiplies `Duration` by `f32`.
826 /// This method will panic if result is not finite, negative or overflows `Duration`.
830 /// use std::time::Duration;
832 /// let dur = Duration::new(2, 700_000_000);
833 /// // note that due to rounding errors result is slightly different
834 /// // from 8.478 and 847800.0
835 /// assert_eq!(dur.mul_f32(3.14), Duration::new(8, 478_000_640));
836 /// assert_eq!(dur.mul_f32(3.14e5), Duration::new(847799, 969_120_256));
838 #[stable(feature = "duration_float", since = "1.38.0")]
840 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
841 pub const fn mul_f32(self, rhs
: f32) -> Duration
{
842 Duration
::from_secs_f32(rhs
* self.as_secs_f32())
845 /// Divide `Duration` by `f64`.
848 /// This method will panic if result is not finite, negative or overflows `Duration`.
852 /// use std::time::Duration;
854 /// let dur = Duration::new(2, 700_000_000);
855 /// assert_eq!(dur.div_f64(3.14), Duration::new(0, 859_872_611));
856 /// // note that truncation is used, not rounding
857 /// assert_eq!(dur.div_f64(3.14e5), Duration::new(0, 8_598));
859 #[stable(feature = "duration_float", since = "1.38.0")]
861 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
862 pub const fn div_f64(self, rhs
: f64) -> Duration
{
863 Duration
::from_secs_f64(self.as_secs_f64() / rhs
)
866 /// Divide `Duration` by `f32`.
869 /// This method will panic if result is not finite, negative or overflows `Duration`.
873 /// use std::time::Duration;
875 /// let dur = Duration::new(2, 700_000_000);
876 /// // note that due to rounding errors result is slightly
877 /// // different from 0.859_872_611
878 /// assert_eq!(dur.div_f32(3.14), Duration::new(0, 859_872_576));
879 /// // note that truncation is used, not rounding
880 /// assert_eq!(dur.div_f32(3.14e5), Duration::new(0, 8_598));
882 #[stable(feature = "duration_float", since = "1.38.0")]
884 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
885 pub const fn div_f32(self, rhs
: f32) -> Duration
{
886 Duration
::from_secs_f32(self.as_secs_f32() / rhs
)
889 /// Divide `Duration` by `Duration` and return `f64`.
893 /// #![feature(div_duration)]
894 /// use std::time::Duration;
896 /// let dur1 = Duration::new(2, 700_000_000);
897 /// let dur2 = Duration::new(5, 400_000_000);
898 /// assert_eq!(dur1.div_duration_f64(dur2), 0.5);
900 #[unstable(feature = "div_duration", issue = "63139")]
902 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
903 pub const fn div_duration_f64(self, rhs
: Duration
) -> f64 {
904 self.as_secs_f64() / rhs
.as_secs_f64()
907 /// Divide `Duration` by `Duration` and return `f32`.
911 /// #![feature(div_duration)]
912 /// use std::time::Duration;
914 /// let dur1 = Duration::new(2, 700_000_000);
915 /// let dur2 = Duration::new(5, 400_000_000);
916 /// assert_eq!(dur1.div_duration_f32(dur2), 0.5);
918 #[unstable(feature = "div_duration", issue = "63139")]
920 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
921 pub const fn div_duration_f32(self, rhs
: Duration
) -> f32 {
922 self.as_secs_f32() / rhs
.as_secs_f32()
926 #[stable(feature = "duration", since = "1.3.0")]
927 impl Add
for Duration
{
928 type Output
= Duration
;
930 fn add(self, rhs
: Duration
) -> Duration
{
931 self.checked_add(rhs
).expect("overflow when adding durations")
935 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
936 impl AddAssign
for Duration
{
937 fn add_assign(&mut self, rhs
: Duration
) {
942 #[stable(feature = "duration", since = "1.3.0")]
943 impl Sub
for Duration
{
944 type Output
= Duration
;
946 fn sub(self, rhs
: Duration
) -> Duration
{
947 self.checked_sub(rhs
).expect("overflow when subtracting durations")
951 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
952 impl SubAssign
for Duration
{
953 fn sub_assign(&mut self, rhs
: Duration
) {
958 #[stable(feature = "duration", since = "1.3.0")]
959 impl Mul
<u32> for Duration
{
960 type Output
= Duration
;
962 fn mul(self, rhs
: u32) -> Duration
{
963 self.checked_mul(rhs
).expect("overflow when multiplying duration by scalar")
967 #[stable(feature = "symmetric_u32_duration_mul", since = "1.31.0")]
968 impl Mul
<Duration
> for u32 {
969 type Output
= Duration
;
971 fn mul(self, rhs
: Duration
) -> Duration
{
976 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
977 impl MulAssign
<u32> for Duration
{
978 fn mul_assign(&mut self, rhs
: u32) {
983 #[stable(feature = "duration", since = "1.3.0")]
984 impl Div
<u32> for Duration
{
985 type Output
= Duration
;
987 fn div(self, rhs
: u32) -> Duration
{
988 self.checked_div(rhs
).expect("divide by zero error when dividing duration by scalar")
992 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
993 impl DivAssign
<u32> for Duration
{
994 fn div_assign(&mut self, rhs
: u32) {
999 macro_rules
! sum_durations
{
1001 let mut total_secs
: u64 = 0;
1002 let mut total_nanos
: u64 = 0;
1004 for entry
in $iter
{
1006 total_secs
.checked_add(entry
.secs
).expect("overflow in iter::sum over durations");
1007 total_nanos
= match total_nanos
.checked_add(entry
.nanos
as u64) {
1010 total_secs
= total_secs
1011 .checked_add(total_nanos
/ NANOS_PER_SEC
as u64)
1012 .expect("overflow in iter::sum over durations");
1013 (total_nanos
% NANOS_PER_SEC
as u64) + entry
.nanos
as u64
1017 total_secs
= total_secs
1018 .checked_add(total_nanos
/ NANOS_PER_SEC
as u64)
1019 .expect("overflow in iter::sum over durations");
1020 total_nanos
= total_nanos
% NANOS_PER_SEC
as u64;
1021 Duration { secs: total_secs, nanos: total_nanos as u32 }
1025 #[stable(feature = "duration_sum", since = "1.16.0")]
1026 impl Sum
for Duration
{
1027 fn sum
<I
: Iterator
<Item
= Duration
>>(iter
: I
) -> Duration
{
1028 sum_durations
!(iter
)
1032 #[stable(feature = "duration_sum", since = "1.16.0")]
1033 impl<'a
> Sum
<&'a Duration
> for Duration
{
1034 fn sum
<I
: Iterator
<Item
= &'a Duration
>>(iter
: I
) -> Duration
{
1035 sum_durations
!(iter
)
1039 #[stable(feature = "duration_debug_impl", since = "1.27.0")]
1040 impl fmt
::Debug
for Duration
{
1041 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1042 /// Formats a floating point number in decimal notation.
1044 /// The number is given as the `integer_part` and a fractional part.
1045 /// The value of the fractional part is `fractional_part / divisor`. So
1046 /// `integer_part` = 3, `fractional_part` = 12 and `divisor` = 100
1047 /// represents the number `3.012`. Trailing zeros are omitted.
1049 /// `divisor` must not be above 100_000_000. It also should be a power
1050 /// of 10, everything else doesn't make sense. `fractional_part` has
1051 /// to be less than `10 * divisor`!
1053 f
: &mut fmt
::Formatter
<'_
>,
1054 mut integer_part
: u64,
1055 mut fractional_part
: u32,
1058 // Encode the fractional part into a temporary buffer. The buffer
1059 // only need to hold 9 elements, because `fractional_part` has to
1060 // be smaller than 10^9. The buffer is prefilled with '0' digits
1061 // to simplify the code below.
1062 let mut buf
= [b'
0'
; 9];
1064 // The next digit is written at this position
1067 // We keep writing digits into the buffer while there are non-zero
1068 // digits left and we haven't written enough digits yet.
1069 while fractional_part
> 0 && pos
< f
.precision().unwrap_or(9) {
1070 // Write new digit into the buffer
1071 buf
[pos
] = b'
0'
+ (fractional_part
/ divisor
) as u8;
1073 fractional_part
%= divisor
;
1078 // If a precision < 9 was specified, there may be some non-zero
1079 // digits left that weren't written into the buffer. In that case we
1080 // need to perform rounding to match the semantics of printing
1081 // normal floating point numbers. However, we only need to do work
1082 // when rounding up. This happens if the first digit of the
1083 // remaining ones is >= 5.
1084 if fractional_part
> 0 && fractional_part
>= divisor
* 5 {
1085 // Round up the number contained in the buffer. We go through
1086 // the buffer backwards and keep track of the carry.
1087 let mut rev_pos
= pos
;
1088 let mut carry
= true;
1089 while carry
&& rev_pos
> 0 {
1092 // If the digit in the buffer is not '9', we just need to
1093 // increment it and can stop then (since we don't have a
1094 // carry anymore). Otherwise, we set it to '0' (overflow)
1096 if buf
[rev_pos
] < b'
9'
{
1100 buf
[rev_pos
] = b'
0'
;
1104 // If we still have the carry bit set, that means that we set
1105 // the whole buffer to '0's and need to increment the integer
1112 // Determine the end of the buffer: if precision is set, we just
1113 // use as many digits from the buffer (capped to 9). If it isn't
1114 // set, we only use all digits up to the last non-zero one.
1115 let end
= f
.precision().map(|p
| crate::cmp
::min(p
, 9)).unwrap_or(pos
);
1117 // If we haven't emitted a single fractional digit and the precision
1118 // wasn't set to a non-zero value, we don't print the decimal point.
1120 write
!(f
, "{}", integer_part
)
1122 // SAFETY: We are only writing ASCII digits into the buffer and it was
1123 // initialized with '0's, so it contains valid UTF8.
1124 let s
= unsafe { crate::str::from_utf8_unchecked(&buf[..end]) }
;
1126 // If the user request a precision > 9, we pad '0's at the end.
1127 let w
= f
.precision().unwrap_or(pos
);
1128 write
!(f
, "{}.{:0<width$}", integer_part
, s
, width
= w
)
1132 // Print leading '+' sign if requested
1138 fmt_decimal(f
, self.secs
, self.nanos
, NANOS_PER_SEC
/ 10)?
;
1140 } else if self.nanos
>= NANOS_PER_MILLI
{
1143 (self.nanos
/ NANOS_PER_MILLI
) as u64,
1144 self.nanos
% NANOS_PER_MILLI
,
1145 NANOS_PER_MILLI
/ 10,
1148 } else if self.nanos
>= NANOS_PER_MICRO
{
1151 (self.nanos
/ NANOS_PER_MICRO
) as u64,
1152 self.nanos
% NANOS_PER_MICRO
,
1153 NANOS_PER_MICRO
/ 10,
1157 fmt_decimal(f
, self.nanos
as u64, 0, 1)?
;
1163 /// An error which can be returned when converting a floating-point value of seconds
1164 /// into a [`Duration`].
1166 /// This error is used as the error type for [`Duration::try_from_secs_f32`] and
1167 /// [`Duration::try_from_secs_f64`].
1172 /// #![feature(duration_checked_float)]
1174 /// use std::time::Duration;
1176 /// if let Err(e) = Duration::try_from_secs_f32(-1.0) {
1177 /// println!("Failed conversion to Duration: {}", e);
1180 #[derive(Debug, Clone, PartialEq, Eq)]
1181 #[unstable(feature = "duration_checked_float", issue = "83400")]
1182 pub struct FromSecsError
{
1183 kind
: FromSecsErrorKind
,
1186 impl FromSecsError
{
1187 const fn description(&self) -> &'
static str {
1189 FromSecsErrorKind
::NonFinite
=> {
1190 "got non-finite value when converting float to duration"
1192 FromSecsErrorKind
::Overflow
=> "overflow when converting float to duration",
1193 FromSecsErrorKind
::Underflow
=> "underflow when converting float to duration",
1198 #[unstable(feature = "duration_checked_float", issue = "83400")]
1199 impl fmt
::Display
for FromSecsError
{
1200 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1201 fmt
::Display
::fmt(self.description(), f
)
1205 #[derive(Debug, Clone, PartialEq, Eq)]
1206 enum FromSecsErrorKind
{
1207 // Value is not a finite value (either infinity or NaN).
1209 // Value is too large to store in a `Duration`.
1211 // Value is less than `0.0`.