]> git.proxmox.com Git - rustc.git/blob - library/core/src/time.rs
New upstream version 1.56.0~beta.4+dfsg1
[rustc.git] / library / core / src / time.rs
1 #![stable(feature = "duration_core", since = "1.25.0")]
2
3 //! Temporal quantification.
4 //!
5 //! # Examples:
6 //!
7 //! There are multiple ways to create a new [`Duration`]:
8 //!
9 //! ```
10 //! # use std::time::Duration;
11 //! let five_seconds = Duration::from_secs(5);
12 //! assert_eq!(five_seconds, Duration::from_millis(5_000));
13 //! assert_eq!(five_seconds, Duration::from_micros(5_000_000));
14 //! assert_eq!(five_seconds, Duration::from_nanos(5_000_000_000));
15 //!
16 //! let ten_seconds = Duration::from_secs(10);
17 //! let seven_nanos = Duration::from_nanos(7);
18 //! let total = ten_seconds + seven_nanos;
19 //! assert_eq!(total, Duration::new(10, 7));
20 //! ```
21
22 use crate::fmt;
23 use crate::iter::Sum;
24 use crate::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
25
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;
31
32 /// A `Duration` type to represent a span of time, typically used for system
33 /// timeouts.
34 ///
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.
39 ///
40 /// [`Duration`]s implement many common traits, including [`Add`], [`Sub`], and other
41 /// [`ops`] traits. It implements [`Default`] by returning a zero-length `Duration`.
42 ///
43 /// [`ops`]: crate::ops
44 ///
45 /// # Examples
46 ///
47 /// ```
48 /// use std::time::Duration;
49 ///
50 /// let five_seconds = Duration::new(5, 0);
51 /// let five_seconds_and_five_nanos = five_seconds + Duration::new(0, 5);
52 ///
53 /// assert_eq!(five_seconds_and_five_nanos.as_secs(), 5);
54 /// assert_eq!(five_seconds_and_five_nanos.subsec_nanos(), 5);
55 ///
56 /// let ten_millis = Duration::from_millis(10);
57 /// ```
58 ///
59 /// # Formatting `Duration` values
60 ///
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.
64 ///
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
68 /// crate to do so.
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")]
72 pub struct Duration {
73 secs: u64,
74 nanos: u32, // Always 0 <= nanos < NANOS_PER_SEC
75 }
76
77 impl Duration {
78 /// The duration of one second.
79 ///
80 /// # Examples
81 ///
82 /// ```
83 /// #![feature(duration_constants)]
84 /// use std::time::Duration;
85 ///
86 /// assert_eq!(Duration::SECOND, Duration::from_secs(1));
87 /// ```
88 #[unstable(feature = "duration_constants", issue = "57391")]
89 pub const SECOND: Duration = Duration::from_secs(1);
90
91 /// The duration of one millisecond.
92 ///
93 /// # Examples
94 ///
95 /// ```
96 /// #![feature(duration_constants)]
97 /// use std::time::Duration;
98 ///
99 /// assert_eq!(Duration::MILLISECOND, Duration::from_millis(1));
100 /// ```
101 #[unstable(feature = "duration_constants", issue = "57391")]
102 pub const MILLISECOND: Duration = Duration::from_millis(1);
103
104 /// The duration of one microsecond.
105 ///
106 /// # Examples
107 ///
108 /// ```
109 /// #![feature(duration_constants)]
110 /// use std::time::Duration;
111 ///
112 /// assert_eq!(Duration::MICROSECOND, Duration::from_micros(1));
113 /// ```
114 #[unstable(feature = "duration_constants", issue = "57391")]
115 pub const MICROSECOND: Duration = Duration::from_micros(1);
116
117 /// The duration of one nanosecond.
118 ///
119 /// # Examples
120 ///
121 /// ```
122 /// #![feature(duration_constants)]
123 /// use std::time::Duration;
124 ///
125 /// assert_eq!(Duration::NANOSECOND, Duration::from_nanos(1));
126 /// ```
127 #[unstable(feature = "duration_constants", issue = "57391")]
128 pub const NANOSECOND: Duration = Duration::from_nanos(1);
129
130 /// A duration of zero time.
131 ///
132 /// # Examples
133 ///
134 /// ```
135 /// use std::time::Duration;
136 ///
137 /// let duration = Duration::ZERO;
138 /// assert!(duration.is_zero());
139 /// assert_eq!(duration.as_nanos(), 0);
140 /// ```
141 #[stable(feature = "duration_zero", since = "1.53.0")]
142 pub const ZERO: Duration = Duration::from_nanos(0);
143
144 /// The maximum duration.
145 ///
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.
150 ///
151 /// # Examples
152 ///
153 /// ```
154 /// use std::time::Duration;
155 ///
156 /// assert_eq!(Duration::MAX, Duration::new(u64::MAX, 1_000_000_000 - 1));
157 /// ```
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);
162
163 /// Creates a new `Duration` from the specified number of whole seconds and
164 /// additional nanoseconds.
165 ///
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.
168 ///
169 /// # Panics
170 ///
171 /// This constructor will panic if the carry from the nanoseconds overflows
172 /// the seconds counter.
173 ///
174 /// # Examples
175 ///
176 /// ```
177 /// use std::time::Duration;
178 ///
179 /// let five_seconds = Duration::new(5, 0);
180 /// ```
181 #[stable(feature = "duration", since = "1.3.0")]
182 #[inline]
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) {
186 Some(secs) => secs,
187 None => panic!("overflow in Duration::new"),
188 };
189 let nanos = nanos % NANOS_PER_SEC;
190 Duration { secs, nanos }
191 }
192
193 /// Creates a new `Duration` from the specified number of whole seconds.
194 ///
195 /// # Examples
196 ///
197 /// ```
198 /// use std::time::Duration;
199 ///
200 /// let duration = Duration::from_secs(5);
201 ///
202 /// assert_eq!(5, duration.as_secs());
203 /// assert_eq!(0, duration.subsec_nanos());
204 /// ```
205 #[stable(feature = "duration", since = "1.3.0")]
206 #[inline]
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 }
210 }
211
212 /// Creates a new `Duration` from the specified number of milliseconds.
213 ///
214 /// # Examples
215 ///
216 /// ```
217 /// use std::time::Duration;
218 ///
219 /// let duration = Duration::from_millis(2569);
220 ///
221 /// assert_eq!(2, duration.as_secs());
222 /// assert_eq!(569_000_000, duration.subsec_nanos());
223 /// ```
224 #[stable(feature = "duration", since = "1.3.0")]
225 #[inline]
226 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
227 pub const fn from_millis(millis: u64) -> Duration {
228 Duration {
229 secs: millis / MILLIS_PER_SEC,
230 nanos: ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI,
231 }
232 }
233
234 /// Creates a new `Duration` from the specified number of microseconds.
235 ///
236 /// # Examples
237 ///
238 /// ```
239 /// use std::time::Duration;
240 ///
241 /// let duration = Duration::from_micros(1_000_002);
242 ///
243 /// assert_eq!(1, duration.as_secs());
244 /// assert_eq!(2000, duration.subsec_nanos());
245 /// ```
246 #[stable(feature = "duration_from_micros", since = "1.27.0")]
247 #[inline]
248 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
249 pub const fn from_micros(micros: u64) -> Duration {
250 Duration {
251 secs: micros / MICROS_PER_SEC,
252 nanos: ((micros % MICROS_PER_SEC) as u32) * NANOS_PER_MICRO,
253 }
254 }
255
256 /// Creates a new `Duration` from the specified number of nanoseconds.
257 ///
258 /// # Examples
259 ///
260 /// ```
261 /// use std::time::Duration;
262 ///
263 /// let duration = Duration::from_nanos(1_000_000_123);
264 ///
265 /// assert_eq!(1, duration.as_secs());
266 /// assert_eq!(123, duration.subsec_nanos());
267 /// ```
268 #[stable(feature = "duration_extras", since = "1.27.0")]
269 #[inline]
270 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
271 pub const fn from_nanos(nanos: u64) -> Duration {
272 Duration {
273 secs: nanos / (NANOS_PER_SEC as u64),
274 nanos: (nanos % (NANOS_PER_SEC as u64)) as u32,
275 }
276 }
277
278 /// Returns true if this `Duration` spans no time.
279 ///
280 /// # Examples
281 ///
282 /// ```
283 /// use std::time::Duration;
284 ///
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());
289 ///
290 /// assert!(!Duration::new(1, 1).is_zero());
291 /// assert!(!Duration::from_nanos(1).is_zero());
292 /// assert!(!Duration::from_secs(1).is_zero());
293 /// ```
294 #[stable(feature = "duration_zero", since = "1.53.0")]
295 #[rustc_const_stable(feature = "duration_zero", since = "1.53.0")]
296 #[inline]
297 pub const fn is_zero(&self) -> bool {
298 self.secs == 0 && self.nanos == 0
299 }
300
301 /// Returns the number of _whole_ seconds contained by this `Duration`.
302 ///
303 /// The returned value does not include the fractional (nanosecond) part of the
304 /// duration, which can be obtained using [`subsec_nanos`].
305 ///
306 /// # Examples
307 ///
308 /// ```
309 /// use std::time::Duration;
310 ///
311 /// let duration = Duration::new(5, 730023852);
312 /// assert_eq!(duration.as_secs(), 5);
313 /// ```
314 ///
315 /// To determine the total number of seconds represented by the `Duration`,
316 /// use `as_secs` in combination with [`subsec_nanos`]:
317 ///
318 /// ```
319 /// use std::time::Duration;
320 ///
321 /// let duration = Duration::new(5, 730023852);
322 ///
323 /// assert_eq!(5.730023852,
324 /// duration.as_secs() as f64
325 /// + duration.subsec_nanos() as f64 * 1e-9);
326 /// ```
327 ///
328 /// [`subsec_nanos`]: Duration::subsec_nanos
329 #[stable(feature = "duration", since = "1.3.0")]
330 #[rustc_const_stable(feature = "duration", since = "1.32.0")]
331 #[inline]
332 pub const fn as_secs(&self) -> u64 {
333 self.secs
334 }
335
336 /// Returns the fractional part of this `Duration`, in whole milliseconds.
337 ///
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).
341 ///
342 /// # Examples
343 ///
344 /// ```
345 /// use std::time::Duration;
346 ///
347 /// let duration = Duration::from_millis(5432);
348 /// assert_eq!(duration.as_secs(), 5);
349 /// assert_eq!(duration.subsec_millis(), 432);
350 /// ```
351 #[stable(feature = "duration_extras", since = "1.27.0")]
352 #[rustc_const_stable(feature = "duration_extras", since = "1.32.0")]
353 #[inline]
354 pub const fn subsec_millis(&self) -> u32 {
355 self.nanos / NANOS_PER_MILLI
356 }
357
358 /// Returns the fractional part of this `Duration`, in whole microseconds.
359 ///
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).
363 ///
364 /// # Examples
365 ///
366 /// ```
367 /// use std::time::Duration;
368 ///
369 /// let duration = Duration::from_micros(1_234_567);
370 /// assert_eq!(duration.as_secs(), 1);
371 /// assert_eq!(duration.subsec_micros(), 234_567);
372 /// ```
373 #[stable(feature = "duration_extras", since = "1.27.0")]
374 #[rustc_const_stable(feature = "duration_extras", since = "1.32.0")]
375 #[inline]
376 pub const fn subsec_micros(&self) -> u32 {
377 self.nanos / NANOS_PER_MICRO
378 }
379
380 /// Returns the fractional part of this `Duration`, in nanoseconds.
381 ///
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).
385 ///
386 /// # Examples
387 ///
388 /// ```
389 /// use std::time::Duration;
390 ///
391 /// let duration = Duration::from_millis(5010);
392 /// assert_eq!(duration.as_secs(), 5);
393 /// assert_eq!(duration.subsec_nanos(), 10_000_000);
394 /// ```
395 #[stable(feature = "duration", since = "1.3.0")]
396 #[rustc_const_stable(feature = "duration", since = "1.32.0")]
397 #[inline]
398 pub const fn subsec_nanos(&self) -> u32 {
399 self.nanos
400 }
401
402 /// Returns the total number of whole milliseconds contained by this `Duration`.
403 ///
404 /// # Examples
405 ///
406 /// ```
407 /// use std::time::Duration;
408 ///
409 /// let duration = Duration::new(5, 730023852);
410 /// assert_eq!(duration.as_millis(), 5730);
411 /// ```
412 #[stable(feature = "duration_as_u128", since = "1.33.0")]
413 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
414 #[inline]
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
417 }
418
419 /// Returns the total number of whole microseconds contained by this `Duration`.
420 ///
421 /// # Examples
422 ///
423 /// ```
424 /// use std::time::Duration;
425 ///
426 /// let duration = Duration::new(5, 730023852);
427 /// assert_eq!(duration.as_micros(), 5730023);
428 /// ```
429 #[stable(feature = "duration_as_u128", since = "1.33.0")]
430 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
431 #[inline]
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
434 }
435
436 /// Returns the total number of nanoseconds contained by this `Duration`.
437 ///
438 /// # Examples
439 ///
440 /// ```
441 /// use std::time::Duration;
442 ///
443 /// let duration = Duration::new(5, 730023852);
444 /// assert_eq!(duration.as_nanos(), 5730023852);
445 /// ```
446 #[stable(feature = "duration_as_u128", since = "1.33.0")]
447 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
448 #[inline]
449 pub const fn as_nanos(&self) -> u128 {
450 self.secs as u128 * NANOS_PER_SEC as u128 + self.nanos as u128
451 }
452
453 /// Checked `Duration` addition. Computes `self + other`, returning [`None`]
454 /// if overflow occurred.
455 ///
456 /// # Examples
457 ///
458 /// Basic usage:
459 ///
460 /// ```
461 /// use std::time::Duration;
462 ///
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);
465 /// ```
466 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
467 #[inline]
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) {
475 secs = new_secs;
476 } else {
477 return None;
478 }
479 }
480 debug_assert!(nanos < NANOS_PER_SEC);
481 Some(Duration { secs, nanos })
482 } else {
483 None
484 }
485 }
486
487 /// Saturating `Duration` addition. Computes `self + other`, returning [`Duration::MAX`]
488 /// if overflow occurred.
489 ///
490 /// # Examples
491 ///
492 /// ```
493 /// #![feature(duration_constants)]
494 /// use std::time::Duration;
495 ///
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);
498 /// ```
499 #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
500 #[inline]
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) {
504 Some(res) => res,
505 None => Duration::MAX,
506 }
507 }
508
509 /// Checked `Duration` subtraction. Computes `self - other`, returning [`None`]
510 /// if the result would be negative or if overflow occurred.
511 ///
512 /// # Examples
513 ///
514 /// Basic usage:
515 ///
516 /// ```
517 /// use std::time::Duration;
518 ///
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);
521 /// ```
522 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
523 #[inline]
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) {
530 secs = sub_secs;
531 self.nanos + NANOS_PER_SEC - rhs.nanos
532 } else {
533 return None;
534 };
535 debug_assert!(nanos < NANOS_PER_SEC);
536 Some(Duration { secs, nanos })
537 } else {
538 None
539 }
540 }
541
542 /// Saturating `Duration` subtraction. Computes `self - other`, returning [`Duration::ZERO`]
543 /// if the result would be negative or if overflow occurred.
544 ///
545 /// # Examples
546 ///
547 /// ```
548 /// use std::time::Duration;
549 ///
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);
552 /// ```
553 #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
554 #[inline]
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) {
558 Some(res) => res,
559 None => Duration::ZERO,
560 }
561 }
562
563 /// Checked `Duration` multiplication. Computes `self * other`, returning
564 /// [`None`] if overflow occurred.
565 ///
566 /// # Examples
567 ///
568 /// Basic usage:
569 ///
570 /// ```
571 /// use std::time::Duration;
572 ///
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);
575 /// ```
576 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
577 #[inline]
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 });
588 }
589 }
590 None
591 }
592
593 /// Saturating `Duration` multiplication. Computes `self * other`, returning
594 /// [`Duration::MAX`] if overflow occurred.
595 ///
596 /// # Examples
597 ///
598 /// ```
599 /// #![feature(duration_constants)]
600 /// use std::time::Duration;
601 ///
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);
604 /// ```
605 #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
606 #[inline]
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) {
610 Some(res) => res,
611 None => Duration::MAX,
612 }
613 }
614
615 /// Checked `Duration` division. Computes `self / other`, returning [`None`]
616 /// if `other == 0`.
617 ///
618 /// # Examples
619 ///
620 /// Basic usage:
621 ///
622 /// ```
623 /// use std::time::Duration;
624 ///
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);
628 /// ```
629 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
630 #[inline]
631 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
632 pub const fn checked_div(self, rhs: u32) -> Option<Duration> {
633 if rhs != 0 {
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 })
640 } else {
641 None
642 }
643 }
644
645 /// Returns the number of seconds contained by this `Duration` as `f64`.
646 ///
647 /// The returned value does include the fractional (nanosecond) part of the duration.
648 ///
649 /// # Examples
650 /// ```
651 /// use std::time::Duration;
652 ///
653 /// let dur = Duration::new(2, 700_000_000);
654 /// assert_eq!(dur.as_secs_f64(), 2.7);
655 /// ```
656 #[stable(feature = "duration_float", since = "1.38.0")]
657 #[inline]
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)
661 }
662
663 /// Returns the number of seconds contained by this `Duration` as `f32`.
664 ///
665 /// The returned value does include the fractional (nanosecond) part of the duration.
666 ///
667 /// # Examples
668 /// ```
669 /// use std::time::Duration;
670 ///
671 /// let dur = Duration::new(2, 700_000_000);
672 /// assert_eq!(dur.as_secs_f32(), 2.7);
673 /// ```
674 #[stable(feature = "duration_float", since = "1.38.0")]
675 #[inline]
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)
679 }
680
681 /// Creates a new `Duration` from the specified number of seconds represented
682 /// as `f64`.
683 ///
684 /// # Panics
685 /// This constructor will panic if `secs` is not finite, negative or overflows `Duration`.
686 ///
687 /// # Examples
688 /// ```
689 /// use std::time::Duration;
690 ///
691 /// let dur = Duration::from_secs_f64(2.7);
692 /// assert_eq!(dur, Duration::new(2, 700_000_000));
693 /// ```
694 #[stable(feature = "duration_float", since = "1.38.0")]
695 #[inline]
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) {
699 Ok(v) => v,
700 Err(e) => crate::panicking::panic(e.description()),
701 }
702 }
703
704 /// The checked version of [`from_secs_f64`].
705 ///
706 /// [`from_secs_f64`]: Duration::from_secs_f64
707 ///
708 /// This constructor will return an `Err` if `secs` is not finite, negative or overflows `Duration`.
709 ///
710 /// # Examples
711 /// ```
712 /// #![feature(duration_checked_float)]
713 ///
714 /// use std::time::Duration;
715 ///
716 /// let dur = Duration::try_from_secs_f64(2.7);
717 /// assert_eq!(dur, Ok(Duration::new(2, 700_000_000)));
718 ///
719 /// let negative = Duration::try_from_secs_f64(-5.0);
720 /// assert!(negative.is_err());
721 /// ```
722 #[unstable(feature = "duration_checked_float", issue = "83400")]
723 #[inline]
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 })
733 } else {
734 let nanos = nanos as u128;
735 Ok(Duration {
736 secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
737 nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
738 })
739 }
740 }
741
742 /// Creates a new `Duration` from the specified number of seconds represented
743 /// as `f32`.
744 ///
745 /// # Panics
746 /// This constructor will panic if `secs` is not finite, negative or overflows `Duration`.
747 ///
748 /// # Examples
749 /// ```
750 /// use std::time::Duration;
751 ///
752 /// let dur = Duration::from_secs_f32(2.7);
753 /// assert_eq!(dur, Duration::new(2, 700_000_000));
754 /// ```
755 #[stable(feature = "duration_float", since = "1.38.0")]
756 #[inline]
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) {
760 Ok(v) => v,
761 Err(e) => crate::panicking::panic(e.description()),
762 }
763 }
764
765 /// The checked version of [`from_secs_f32`].
766 ///
767 /// [`from_secs_f32`]: Duration::from_secs_f32
768 ///
769 /// This constructor will return an `Err` if `secs` is not finite, negative or overflows `Duration`.
770 ///
771 /// # Examples
772 /// ```
773 /// #![feature(duration_checked_float)]
774 ///
775 /// use std::time::Duration;
776 ///
777 /// let dur = Duration::try_from_secs_f32(2.7);
778 /// assert_eq!(dur, Ok(Duration::new(2, 700_000_000)));
779 ///
780 /// let negative = Duration::try_from_secs_f32(-5.0);
781 /// assert!(negative.is_err());
782 /// ```
783 #[unstable(feature = "duration_checked_float", issue = "83400")]
784 #[inline]
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 })
794 } else {
795 let nanos = nanos as u128;
796 Ok(Duration {
797 secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
798 nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
799 })
800 }
801 }
802
803 /// Multiplies `Duration` by `f64`.
804 ///
805 /// # Panics
806 /// This method will panic if result is not finite, negative or overflows `Duration`.
807 ///
808 /// # Examples
809 /// ```
810 /// use std::time::Duration;
811 ///
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));
815 /// ```
816 #[stable(feature = "duration_float", since = "1.38.0")]
817 #[inline]
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())
821 }
822
823 /// Multiplies `Duration` by `f32`.
824 ///
825 /// # Panics
826 /// This method will panic if result is not finite, negative or overflows `Duration`.
827 ///
828 /// # Examples
829 /// ```
830 /// use std::time::Duration;
831 ///
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));
837 /// ```
838 #[stable(feature = "duration_float", since = "1.38.0")]
839 #[inline]
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())
843 }
844
845 /// Divide `Duration` by `f64`.
846 ///
847 /// # Panics
848 /// This method will panic if result is not finite, negative or overflows `Duration`.
849 ///
850 /// # Examples
851 /// ```
852 /// use std::time::Duration;
853 ///
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));
858 /// ```
859 #[stable(feature = "duration_float", since = "1.38.0")]
860 #[inline]
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)
864 }
865
866 /// Divide `Duration` by `f32`.
867 ///
868 /// # Panics
869 /// This method will panic if result is not finite, negative or overflows `Duration`.
870 ///
871 /// # Examples
872 /// ```
873 /// use std::time::Duration;
874 ///
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));
881 /// ```
882 #[stable(feature = "duration_float", since = "1.38.0")]
883 #[inline]
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)
887 }
888
889 /// Divide `Duration` by `Duration` and return `f64`.
890 ///
891 /// # Examples
892 /// ```
893 /// #![feature(div_duration)]
894 /// use std::time::Duration;
895 ///
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);
899 /// ```
900 #[unstable(feature = "div_duration", issue = "63139")]
901 #[inline]
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()
905 }
906
907 /// Divide `Duration` by `Duration` and return `f32`.
908 ///
909 /// # Examples
910 /// ```
911 /// #![feature(div_duration)]
912 /// use std::time::Duration;
913 ///
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);
917 /// ```
918 #[unstable(feature = "div_duration", issue = "63139")]
919 #[inline]
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()
923 }
924 }
925
926 #[stable(feature = "duration", since = "1.3.0")]
927 impl Add for Duration {
928 type Output = Duration;
929
930 fn add(self, rhs: Duration) -> Duration {
931 self.checked_add(rhs).expect("overflow when adding durations")
932 }
933 }
934
935 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
936 impl AddAssign for Duration {
937 fn add_assign(&mut self, rhs: Duration) {
938 *self = *self + rhs;
939 }
940 }
941
942 #[stable(feature = "duration", since = "1.3.0")]
943 impl Sub for Duration {
944 type Output = Duration;
945
946 fn sub(self, rhs: Duration) -> Duration {
947 self.checked_sub(rhs).expect("overflow when subtracting durations")
948 }
949 }
950
951 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
952 impl SubAssign for Duration {
953 fn sub_assign(&mut self, rhs: Duration) {
954 *self = *self - rhs;
955 }
956 }
957
958 #[stable(feature = "duration", since = "1.3.0")]
959 impl Mul<u32> for Duration {
960 type Output = Duration;
961
962 fn mul(self, rhs: u32) -> Duration {
963 self.checked_mul(rhs).expect("overflow when multiplying duration by scalar")
964 }
965 }
966
967 #[stable(feature = "symmetric_u32_duration_mul", since = "1.31.0")]
968 impl Mul<Duration> for u32 {
969 type Output = Duration;
970
971 fn mul(self, rhs: Duration) -> Duration {
972 rhs * self
973 }
974 }
975
976 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
977 impl MulAssign<u32> for Duration {
978 fn mul_assign(&mut self, rhs: u32) {
979 *self = *self * rhs;
980 }
981 }
982
983 #[stable(feature = "duration", since = "1.3.0")]
984 impl Div<u32> for Duration {
985 type Output = Duration;
986
987 fn div(self, rhs: u32) -> Duration {
988 self.checked_div(rhs).expect("divide by zero error when dividing duration by scalar")
989 }
990 }
991
992 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
993 impl DivAssign<u32> for Duration {
994 fn div_assign(&mut self, rhs: u32) {
995 *self = *self / rhs;
996 }
997 }
998
999 macro_rules! sum_durations {
1000 ($iter:expr) => {{
1001 let mut total_secs: u64 = 0;
1002 let mut total_nanos: u64 = 0;
1003
1004 for entry in $iter {
1005 total_secs =
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) {
1008 Some(n) => n,
1009 None => {
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
1014 }
1015 };
1016 }
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 }
1022 }};
1023 }
1024
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)
1029 }
1030 }
1031
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)
1036 }
1037 }
1038
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.
1043 ///
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.
1048 ///
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`!
1052 fn fmt_decimal(
1053 f: &mut fmt::Formatter<'_>,
1054 mut integer_part: u64,
1055 mut fractional_part: u32,
1056 mut divisor: u32,
1057 ) -> fmt::Result {
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];
1063
1064 // The next digit is written at this position
1065 let mut pos = 0;
1066
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;
1072
1073 fractional_part %= divisor;
1074 divisor /= 10;
1075 pos += 1;
1076 }
1077
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 {
1090 rev_pos -= 1;
1091
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)
1095 // and continue.
1096 if buf[rev_pos] < b'9' {
1097 buf[rev_pos] += 1;
1098 carry = false;
1099 } else {
1100 buf[rev_pos] = b'0';
1101 }
1102 }
1103
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
1106 // part.
1107 if carry {
1108 integer_part += 1;
1109 }
1110 }
1111
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);
1116
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.
1119 if end == 0 {
1120 write!(f, "{}", integer_part)
1121 } else {
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]) };
1125
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)
1129 }
1130 }
1131
1132 // Print leading '+' sign if requested
1133 if f.sign_plus() {
1134 write!(f, "+")?;
1135 }
1136
1137 if self.secs > 0 {
1138 fmt_decimal(f, self.secs, self.nanos, NANOS_PER_SEC / 10)?;
1139 f.write_str("s")
1140 } else if self.nanos >= NANOS_PER_MILLI {
1141 fmt_decimal(
1142 f,
1143 (self.nanos / NANOS_PER_MILLI) as u64,
1144 self.nanos % NANOS_PER_MILLI,
1145 NANOS_PER_MILLI / 10,
1146 )?;
1147 f.write_str("ms")
1148 } else if self.nanos >= NANOS_PER_MICRO {
1149 fmt_decimal(
1150 f,
1151 (self.nanos / NANOS_PER_MICRO) as u64,
1152 self.nanos % NANOS_PER_MICRO,
1153 NANOS_PER_MICRO / 10,
1154 )?;
1155 f.write_str("µs")
1156 } else {
1157 fmt_decimal(f, self.nanos as u64, 0, 1)?;
1158 f.write_str("ns")
1159 }
1160 }
1161 }
1162
1163 /// An error which can be returned when converting a floating-point value of seconds
1164 /// into a [`Duration`].
1165 ///
1166 /// This error is used as the error type for [`Duration::try_from_secs_f32`] and
1167 /// [`Duration::try_from_secs_f64`].
1168 ///
1169 /// # Example
1170 ///
1171 /// ```
1172 /// #![feature(duration_checked_float)]
1173 ///
1174 /// use std::time::Duration;
1175 ///
1176 /// if let Err(e) = Duration::try_from_secs_f32(-1.0) {
1177 /// println!("Failed conversion to Duration: {}", e);
1178 /// }
1179 /// ```
1180 #[derive(Debug, Clone, PartialEq, Eq)]
1181 #[unstable(feature = "duration_checked_float", issue = "83400")]
1182 pub struct FromSecsError {
1183 kind: FromSecsErrorKind,
1184 }
1185
1186 impl FromSecsError {
1187 const fn description(&self) -> &'static str {
1188 match self.kind {
1189 FromSecsErrorKind::NonFinite => {
1190 "got non-finite value when converting float to duration"
1191 }
1192 FromSecsErrorKind::Overflow => "overflow when converting float to duration",
1193 FromSecsErrorKind::Underflow => "underflow when converting float to duration",
1194 }
1195 }
1196 }
1197
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)
1202 }
1203 }
1204
1205 #[derive(Debug, Clone, PartialEq, Eq)]
1206 enum FromSecsErrorKind {
1207 // Value is not a finite value (either infinity or NaN).
1208 NonFinite,
1209 // Value is too large to store in a `Duration`.
1210 Overflow,
1211 // Value is less than `0.0`.
1212 Underflow,
1213 }