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