]> git.proxmox.com Git - rustc.git/blob - library/core/src/time.rs
New upstream version 1.48.0~beta.8+dfsg1
[rustc.git] / library / core / src / time.rs
1 #![stable(feature = "duration_core", since = "1.25.0")]
2
3 //! Temporal quantification.
4 //!
5 //! Example:
6 //!
7 //! ```
8 //! use std::time::Duration;
9 //!
10 //! let five_seconds = Duration::new(5, 0);
11 //! // both declarations are equivalent
12 //! assert_eq!(Duration::new(5, 0), Duration::from_secs(5));
13 //! ```
14
15 use crate::fmt;
16 use crate::iter::Sum;
17 use crate::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
18
19 const NANOS_PER_SEC: u32 = 1_000_000_000;
20 const NANOS_PER_MILLI: u32 = 1_000_000;
21 const NANOS_PER_MICRO: u32 = 1_000;
22 const MILLIS_PER_SEC: u64 = 1_000;
23 const MICROS_PER_SEC: u64 = 1_000_000;
24
25 /// A `Duration` type to represent a span of time, typically used for system
26 /// timeouts.
27 ///
28 /// Each `Duration` is composed of a whole number of seconds and a fractional part
29 /// represented in nanoseconds. If the underlying system does not support
30 /// nanosecond-level precision, APIs binding a system timeout will typically round up
31 /// the number of nanoseconds.
32 ///
33 /// [`Duration`]s implement many common traits, including [`Add`], [`Sub`], and other
34 /// [`ops`] traits. It implements [`Default`] by returning a zero-length `Duration`.
35 ///
36 /// [`ops`]: crate::ops
37 ///
38 /// # Examples
39 ///
40 /// ```
41 /// use std::time::Duration;
42 ///
43 /// let five_seconds = Duration::new(5, 0);
44 /// let five_seconds_and_five_nanos = five_seconds + Duration::new(0, 5);
45 ///
46 /// assert_eq!(five_seconds_and_five_nanos.as_secs(), 5);
47 /// assert_eq!(five_seconds_and_five_nanos.subsec_nanos(), 5);
48 ///
49 /// let ten_millis = Duration::from_millis(10);
50 /// ```
51 #[stable(feature = "duration", since = "1.3.0")]
52 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
53 pub struct Duration {
54 secs: u64,
55 nanos: u32, // Always 0 <= nanos < NANOS_PER_SEC
56 }
57
58 impl Duration {
59 /// The duration of one second.
60 ///
61 /// # Examples
62 ///
63 /// ```
64 /// #![feature(duration_constants)]
65 /// use std::time::Duration;
66 ///
67 /// assert_eq!(Duration::SECOND, Duration::from_secs(1));
68 /// ```
69 #[unstable(feature = "duration_constants", issue = "57391")]
70 pub const SECOND: Duration = Duration::from_secs(1);
71
72 /// The duration of one millisecond.
73 ///
74 /// # Examples
75 ///
76 /// ```
77 /// #![feature(duration_constants)]
78 /// use std::time::Duration;
79 ///
80 /// assert_eq!(Duration::MILLISECOND, Duration::from_millis(1));
81 /// ```
82 #[unstable(feature = "duration_constants", issue = "57391")]
83 pub const MILLISECOND: Duration = Duration::from_millis(1);
84
85 /// The duration of one microsecond.
86 ///
87 /// # Examples
88 ///
89 /// ```
90 /// #![feature(duration_constants)]
91 /// use std::time::Duration;
92 ///
93 /// assert_eq!(Duration::MICROSECOND, Duration::from_micros(1));
94 /// ```
95 #[unstable(feature = "duration_constants", issue = "57391")]
96 pub const MICROSECOND: Duration = Duration::from_micros(1);
97
98 /// The duration of one nanosecond.
99 ///
100 /// # Examples
101 ///
102 /// ```
103 /// #![feature(duration_constants)]
104 /// use std::time::Duration;
105 ///
106 /// assert_eq!(Duration::NANOSECOND, Duration::from_nanos(1));
107 /// ```
108 #[unstable(feature = "duration_constants", issue = "57391")]
109 pub const NANOSECOND: Duration = Duration::from_nanos(1);
110
111 /// The minimum duration.
112 ///
113 /// # Examples
114 ///
115 /// ```
116 /// #![feature(duration_constants)]
117 /// use std::time::Duration;
118 ///
119 /// assert_eq!(Duration::MIN, Duration::new(0, 0));
120 /// ```
121 #[unstable(feature = "duration_constants", issue = "57391")]
122 pub const MIN: Duration = Duration::from_nanos(0);
123
124 /// The maximum duration.
125 ///
126 /// It is roughly equal to a duration of 584,942,417,355 years.
127 ///
128 /// # Examples
129 ///
130 /// ```
131 /// #![feature(duration_constants)]
132 /// use std::time::Duration;
133 ///
134 /// assert_eq!(Duration::MAX, Duration::new(u64::MAX, 1_000_000_000 - 1));
135 /// ```
136 #[unstable(feature = "duration_constants", issue = "57391")]
137 pub const MAX: Duration = Duration::new(u64::MAX, NANOS_PER_SEC - 1);
138
139 /// Creates a new `Duration` from the specified number of whole seconds and
140 /// additional nanoseconds.
141 ///
142 /// If the number of nanoseconds is greater than 1 billion (the number of
143 /// nanoseconds in a second), then it will carry over into the seconds provided.
144 ///
145 /// # Panics
146 ///
147 /// This constructor will panic if the carry from the nanoseconds overflows
148 /// the seconds counter.
149 ///
150 /// # Examples
151 ///
152 /// ```
153 /// use std::time::Duration;
154 ///
155 /// let five_seconds = Duration::new(5, 0);
156 /// ```
157 #[stable(feature = "duration", since = "1.3.0")]
158 #[inline]
159 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
160 pub const fn new(secs: u64, nanos: u32) -> Duration {
161 let secs = match secs.checked_add((nanos / NANOS_PER_SEC) as u64) {
162 Some(secs) => secs,
163 None => panic!("overflow in Duration::new"),
164 };
165 let nanos = nanos % NANOS_PER_SEC;
166 Duration { secs, nanos }
167 }
168
169 /// Creates a new `Duration` that spans no time.
170 ///
171 /// # Examples
172 ///
173 /// ```
174 /// #![feature(duration_zero)]
175 /// use std::time::Duration;
176 ///
177 /// let duration = Duration::zero();
178 /// assert!(duration.is_zero());
179 /// assert_eq!(duration.as_nanos(), 0);
180 /// ```
181 #[unstable(feature = "duration_zero", issue = "73544")]
182 #[inline]
183 pub const fn zero() -> Duration {
184 Duration { secs: 0, nanos: 0 }
185 }
186
187 /// Creates a new `Duration` from the specified number of whole seconds.
188 ///
189 /// # Examples
190 ///
191 /// ```
192 /// use std::time::Duration;
193 ///
194 /// let duration = Duration::from_secs(5);
195 ///
196 /// assert_eq!(5, duration.as_secs());
197 /// assert_eq!(0, duration.subsec_nanos());
198 /// ```
199 #[stable(feature = "duration", since = "1.3.0")]
200 #[inline]
201 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
202 pub const fn from_secs(secs: u64) -> Duration {
203 Duration { secs, nanos: 0 }
204 }
205
206 /// Creates a new `Duration` from the specified number of milliseconds.
207 ///
208 /// # Examples
209 ///
210 /// ```
211 /// use std::time::Duration;
212 ///
213 /// let duration = Duration::from_millis(2569);
214 ///
215 /// assert_eq!(2, duration.as_secs());
216 /// assert_eq!(569_000_000, duration.subsec_nanos());
217 /// ```
218 #[stable(feature = "duration", since = "1.3.0")]
219 #[inline]
220 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
221 pub const fn from_millis(millis: u64) -> Duration {
222 Duration {
223 secs: millis / MILLIS_PER_SEC,
224 nanos: ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI,
225 }
226 }
227
228 /// Creates a new `Duration` from the specified number of microseconds.
229 ///
230 /// # Examples
231 ///
232 /// ```
233 /// use std::time::Duration;
234 ///
235 /// let duration = Duration::from_micros(1_000_002);
236 ///
237 /// assert_eq!(1, duration.as_secs());
238 /// assert_eq!(2000, duration.subsec_nanos());
239 /// ```
240 #[stable(feature = "duration_from_micros", since = "1.27.0")]
241 #[inline]
242 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
243 pub const fn from_micros(micros: u64) -> Duration {
244 Duration {
245 secs: micros / MICROS_PER_SEC,
246 nanos: ((micros % MICROS_PER_SEC) as u32) * NANOS_PER_MICRO,
247 }
248 }
249
250 /// Creates a new `Duration` from the specified number of nanoseconds.
251 ///
252 /// # Examples
253 ///
254 /// ```
255 /// use std::time::Duration;
256 ///
257 /// let duration = Duration::from_nanos(1_000_000_123);
258 ///
259 /// assert_eq!(1, duration.as_secs());
260 /// assert_eq!(123, duration.subsec_nanos());
261 /// ```
262 #[stable(feature = "duration_extras", since = "1.27.0")]
263 #[inline]
264 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
265 pub const fn from_nanos(nanos: u64) -> Duration {
266 Duration {
267 secs: nanos / (NANOS_PER_SEC as u64),
268 nanos: (nanos % (NANOS_PER_SEC as u64)) as u32,
269 }
270 }
271
272 /// Returns true if this `Duration` spans no time.
273 ///
274 /// # Examples
275 ///
276 /// ```
277 /// #![feature(duration_zero)]
278 /// use std::time::Duration;
279 ///
280 /// assert!(Duration::zero().is_zero());
281 /// assert!(Duration::new(0, 0).is_zero());
282 /// assert!(Duration::from_nanos(0).is_zero());
283 /// assert!(Duration::from_secs(0).is_zero());
284 ///
285 /// assert!(!Duration::new(1, 1).is_zero());
286 /// assert!(!Duration::from_nanos(1).is_zero());
287 /// assert!(!Duration::from_secs(1).is_zero());
288 /// ```
289 #[unstable(feature = "duration_zero", issue = "73544")]
290 #[inline]
291 pub const fn is_zero(&self) -> bool {
292 self.secs == 0 && self.nanos == 0
293 }
294
295 /// Returns the number of _whole_ seconds contained by this `Duration`.
296 ///
297 /// The returned value does not include the fractional (nanosecond) part of the
298 /// duration, which can be obtained using [`subsec_nanos`].
299 ///
300 /// # Examples
301 ///
302 /// ```
303 /// use std::time::Duration;
304 ///
305 /// let duration = Duration::new(5, 730023852);
306 /// assert_eq!(duration.as_secs(), 5);
307 /// ```
308 ///
309 /// To determine the total number of seconds represented by the `Duration`,
310 /// use `as_secs` in combination with [`subsec_nanos`]:
311 ///
312 /// ```
313 /// use std::time::Duration;
314 ///
315 /// let duration = Duration::new(5, 730023852);
316 ///
317 /// assert_eq!(5.730023852,
318 /// duration.as_secs() as f64
319 /// + duration.subsec_nanos() as f64 * 1e-9);
320 /// ```
321 ///
322 /// [`subsec_nanos`]: Duration::subsec_nanos
323 #[stable(feature = "duration", since = "1.3.0")]
324 #[rustc_const_stable(feature = "duration", since = "1.32.0")]
325 #[inline]
326 pub const fn as_secs(&self) -> u64 {
327 self.secs
328 }
329
330 /// Returns the fractional part of this `Duration`, in whole milliseconds.
331 ///
332 /// This method does **not** return the length of the duration when
333 /// represented by milliseconds. The returned number always represents a
334 /// fractional portion of a second (i.e., it is less than one thousand).
335 ///
336 /// # Examples
337 ///
338 /// ```
339 /// use std::time::Duration;
340 ///
341 /// let duration = Duration::from_millis(5432);
342 /// assert_eq!(duration.as_secs(), 5);
343 /// assert_eq!(duration.subsec_millis(), 432);
344 /// ```
345 #[stable(feature = "duration_extras", since = "1.27.0")]
346 #[rustc_const_stable(feature = "duration_extras", since = "1.32.0")]
347 #[inline]
348 pub const fn subsec_millis(&self) -> u32 {
349 self.nanos / NANOS_PER_MILLI
350 }
351
352 /// Returns the fractional part of this `Duration`, in whole microseconds.
353 ///
354 /// This method does **not** return the length of the duration when
355 /// represented by microseconds. The returned number always represents a
356 /// fractional portion of a second (i.e., it is less than one million).
357 ///
358 /// # Examples
359 ///
360 /// ```
361 /// use std::time::Duration;
362 ///
363 /// let duration = Duration::from_micros(1_234_567);
364 /// assert_eq!(duration.as_secs(), 1);
365 /// assert_eq!(duration.subsec_micros(), 234_567);
366 /// ```
367 #[stable(feature = "duration_extras", since = "1.27.0")]
368 #[rustc_const_stable(feature = "duration_extras", since = "1.32.0")]
369 #[inline]
370 pub const fn subsec_micros(&self) -> u32 {
371 self.nanos / NANOS_PER_MICRO
372 }
373
374 /// Returns the fractional part of this `Duration`, in nanoseconds.
375 ///
376 /// This method does **not** return the length of the duration when
377 /// represented by nanoseconds. The returned number always represents a
378 /// fractional portion of a second (i.e., it is less than one billion).
379 ///
380 /// # Examples
381 ///
382 /// ```
383 /// use std::time::Duration;
384 ///
385 /// let duration = Duration::from_millis(5010);
386 /// assert_eq!(duration.as_secs(), 5);
387 /// assert_eq!(duration.subsec_nanos(), 10_000_000);
388 /// ```
389 #[stable(feature = "duration", since = "1.3.0")]
390 #[rustc_const_stable(feature = "duration", since = "1.32.0")]
391 #[inline]
392 pub const fn subsec_nanos(&self) -> u32 {
393 self.nanos
394 }
395
396 /// Returns the total number of whole milliseconds contained by this `Duration`.
397 ///
398 /// # Examples
399 ///
400 /// ```
401 /// use std::time::Duration;
402 ///
403 /// let duration = Duration::new(5, 730023852);
404 /// assert_eq!(duration.as_millis(), 5730);
405 /// ```
406 #[stable(feature = "duration_as_u128", since = "1.33.0")]
407 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
408 #[inline]
409 pub const fn as_millis(&self) -> u128 {
410 self.secs as u128 * MILLIS_PER_SEC as u128 + (self.nanos / NANOS_PER_MILLI) as u128
411 }
412
413 /// Returns the total number of whole microseconds contained by this `Duration`.
414 ///
415 /// # Examples
416 ///
417 /// ```
418 /// use std::time::Duration;
419 ///
420 /// let duration = Duration::new(5, 730023852);
421 /// assert_eq!(duration.as_micros(), 5730023);
422 /// ```
423 #[stable(feature = "duration_as_u128", since = "1.33.0")]
424 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
425 #[inline]
426 pub const fn as_micros(&self) -> u128 {
427 self.secs as u128 * MICROS_PER_SEC as u128 + (self.nanos / NANOS_PER_MICRO) as u128
428 }
429
430 /// Returns the total number of nanoseconds contained by this `Duration`.
431 ///
432 /// # Examples
433 ///
434 /// ```
435 /// use std::time::Duration;
436 ///
437 /// let duration = Duration::new(5, 730023852);
438 /// assert_eq!(duration.as_nanos(), 5730023852);
439 /// ```
440 #[stable(feature = "duration_as_u128", since = "1.33.0")]
441 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
442 #[inline]
443 pub const fn as_nanos(&self) -> u128 {
444 self.secs as u128 * NANOS_PER_SEC as u128 + self.nanos as u128
445 }
446
447 /// Checked `Duration` addition. Computes `self + other`, returning [`None`]
448 /// if overflow occurred.
449 ///
450 /// # Examples
451 ///
452 /// Basic usage:
453 ///
454 /// ```
455 /// use std::time::Duration;
456 ///
457 /// assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1)));
458 /// assert_eq!(Duration::new(1, 0).checked_add(Duration::new(u64::MAX, 0)), None);
459 /// ```
460 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
461 #[inline]
462 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
463 pub const fn checked_add(self, rhs: Duration) -> Option<Duration> {
464 if let Some(mut secs) = self.secs.checked_add(rhs.secs) {
465 let mut nanos = self.nanos + rhs.nanos;
466 if nanos >= NANOS_PER_SEC {
467 nanos -= NANOS_PER_SEC;
468 if let Some(new_secs) = secs.checked_add(1) {
469 secs = new_secs;
470 } else {
471 return None;
472 }
473 }
474 debug_assert!(nanos < NANOS_PER_SEC);
475 Some(Duration { secs, nanos })
476 } else {
477 None
478 }
479 }
480
481 /// Saturating `Duration` addition. Computes `self + other`, returning [`Duration::MAX`]
482 /// if overflow occurred.
483 ///
484 /// # Examples
485 ///
486 /// ```
487 /// #![feature(duration_saturating_ops)]
488 /// #![feature(duration_constants)]
489 /// use std::time::Duration;
490 ///
491 /// assert_eq!(Duration::new(0, 0).saturating_add(Duration::new(0, 1)), Duration::new(0, 1));
492 /// assert_eq!(Duration::new(1, 0).saturating_add(Duration::new(u64::MAX, 0)), Duration::MAX);
493 /// ```
494 #[unstable(feature = "duration_saturating_ops", issue = "76416")]
495 #[inline]
496 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
497 pub const fn saturating_add(self, rhs: Duration) -> Duration {
498 match self.checked_add(rhs) {
499 Some(res) => res,
500 None => Duration::MAX,
501 }
502 }
503
504 /// Checked `Duration` subtraction. Computes `self - other`, returning [`None`]
505 /// if the result would be negative or if overflow occurred.
506 ///
507 /// # Examples
508 ///
509 /// Basic usage:
510 ///
511 /// ```
512 /// use std::time::Duration;
513 ///
514 /// assert_eq!(Duration::new(0, 1).checked_sub(Duration::new(0, 0)), Some(Duration::new(0, 1)));
515 /// assert_eq!(Duration::new(0, 0).checked_sub(Duration::new(0, 1)), None);
516 /// ```
517 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
518 #[inline]
519 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
520 pub const fn checked_sub(self, rhs: Duration) -> Option<Duration> {
521 if let Some(mut secs) = self.secs.checked_sub(rhs.secs) {
522 let nanos = if self.nanos >= rhs.nanos {
523 self.nanos - rhs.nanos
524 } else {
525 if let Some(sub_secs) = secs.checked_sub(1) {
526 secs = sub_secs;
527 self.nanos + NANOS_PER_SEC - rhs.nanos
528 } else {
529 return None;
530 }
531 };
532 debug_assert!(nanos < NANOS_PER_SEC);
533 Some(Duration { secs, nanos })
534 } else {
535 None
536 }
537 }
538
539 /// Saturating `Duration` subtraction. Computes `self - other`, returning [`Duration::MIN`]
540 /// if the result would be negative or if overflow occurred.
541 ///
542 /// # Examples
543 ///
544 /// ```
545 /// #![feature(duration_saturating_ops)]
546 /// #![feature(duration_constants)]
547 /// use std::time::Duration;
548 ///
549 /// assert_eq!(Duration::new(0, 1).saturating_sub(Duration::new(0, 0)), Duration::new(0, 1));
550 /// assert_eq!(Duration::new(0, 0).saturating_sub(Duration::new(0, 1)), Duration::MIN);
551 /// ```
552 #[unstable(feature = "duration_saturating_ops", issue = "76416")]
553 #[inline]
554 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
555 pub const fn saturating_sub(self, rhs: Duration) -> Duration {
556 match self.checked_sub(rhs) {
557 Some(res) => res,
558 None => Duration::MIN,
559 }
560 }
561
562 /// Checked `Duration` multiplication. Computes `self * other`, returning
563 /// [`None`] if overflow occurred.
564 ///
565 /// # Examples
566 ///
567 /// Basic usage:
568 ///
569 /// ```
570 /// use std::time::Duration;
571 ///
572 /// assert_eq!(Duration::new(0, 500_000_001).checked_mul(2), Some(Duration::new(1, 2)));
573 /// assert_eq!(Duration::new(u64::MAX - 1, 0).checked_mul(2), None);
574 /// ```
575 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
576 #[inline]
577 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
578 pub const fn checked_mul(self, rhs: u32) -> Option<Duration> {
579 // Multiply nanoseconds as u64, because it cannot overflow that way.
580 let total_nanos = self.nanos as u64 * rhs as u64;
581 let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
582 let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
583 if let Some(s) = self.secs.checked_mul(rhs as u64) {
584 if let Some(secs) = s.checked_add(extra_secs) {
585 debug_assert!(nanos < NANOS_PER_SEC);
586 return Some(Duration { secs, nanos });
587 }
588 }
589 None
590 }
591
592 /// Saturating `Duration` multiplication. Computes `self * other`, returning
593 /// [`Duration::MAX`] if overflow occurred.
594 ///
595 /// # Examples
596 ///
597 /// ```
598 /// #![feature(duration_saturating_ops)]
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 #[unstable(feature = "duration_saturating_ops", issue = "76416")]
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 const MAX_NANOS_F64: f64 = ((u64::MAX as u128 + 1) * (NANOS_PER_SEC as u128)) as f64;
699 let nanos = secs * (NANOS_PER_SEC as f64);
700 if !nanos.is_finite() {
701 panic!("got non-finite value when converting float to duration");
702 }
703 if nanos >= MAX_NANOS_F64 {
704 panic!("overflow when converting float to duration");
705 }
706 if nanos < 0.0 {
707 panic!("underflow when converting float to duration");
708 }
709 let nanos = nanos as u128;
710 Duration {
711 secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
712 nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
713 }
714 }
715
716 /// Creates a new `Duration` from the specified number of seconds represented
717 /// as `f32`.
718 ///
719 /// # Panics
720 /// This constructor will panic if `secs` is not finite, negative or overflows `Duration`.
721 ///
722 /// # Examples
723 /// ```
724 /// use std::time::Duration;
725 ///
726 /// let dur = Duration::from_secs_f32(2.7);
727 /// assert_eq!(dur, Duration::new(2, 700_000_000));
728 /// ```
729 #[stable(feature = "duration_float", since = "1.38.0")]
730 #[inline]
731 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
732 pub const fn from_secs_f32(secs: f32) -> Duration {
733 const MAX_NANOS_F32: f32 = ((u64::MAX as u128 + 1) * (NANOS_PER_SEC as u128)) as f32;
734 let nanos = secs * (NANOS_PER_SEC as f32);
735 if !nanos.is_finite() {
736 panic!("got non-finite value when converting float to duration");
737 }
738 if nanos >= MAX_NANOS_F32 {
739 panic!("overflow when converting float to duration");
740 }
741 if nanos < 0.0 {
742 panic!("underflow when converting float to duration");
743 }
744 let nanos = nanos as u128;
745 Duration {
746 secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
747 nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
748 }
749 }
750
751 /// Multiplies `Duration` by `f64`.
752 ///
753 /// # Panics
754 /// This method will panic if result is not finite, negative or overflows `Duration`.
755 ///
756 /// # Examples
757 /// ```
758 /// use std::time::Duration;
759 ///
760 /// let dur = Duration::new(2, 700_000_000);
761 /// assert_eq!(dur.mul_f64(3.14), Duration::new(8, 478_000_000));
762 /// assert_eq!(dur.mul_f64(3.14e5), Duration::new(847_800, 0));
763 /// ```
764 #[stable(feature = "duration_float", since = "1.38.0")]
765 #[inline]
766 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
767 pub const fn mul_f64(self, rhs: f64) -> Duration {
768 Duration::from_secs_f64(rhs * self.as_secs_f64())
769 }
770
771 /// Multiplies `Duration` by `f32`.
772 ///
773 /// # Panics
774 /// This method will panic if result is not finite, negative or overflows `Duration`.
775 ///
776 /// # Examples
777 /// ```
778 /// use std::time::Duration;
779 ///
780 /// let dur = Duration::new(2, 700_000_000);
781 /// // note that due to rounding errors result is slightly different
782 /// // from 8.478 and 847800.0
783 /// assert_eq!(dur.mul_f32(3.14), Duration::new(8, 478_000_640));
784 /// assert_eq!(dur.mul_f32(3.14e5), Duration::new(847799, 969_120_256));
785 /// ```
786 #[stable(feature = "duration_float", since = "1.38.0")]
787 #[inline]
788 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
789 pub const fn mul_f32(self, rhs: f32) -> Duration {
790 Duration::from_secs_f32(rhs * self.as_secs_f32())
791 }
792
793 /// Divide `Duration` by `f64`.
794 ///
795 /// # Panics
796 /// This method will panic if result is not finite, negative or overflows `Duration`.
797 ///
798 /// # Examples
799 /// ```
800 /// use std::time::Duration;
801 ///
802 /// let dur = Duration::new(2, 700_000_000);
803 /// assert_eq!(dur.div_f64(3.14), Duration::new(0, 859_872_611));
804 /// // note that truncation is used, not rounding
805 /// assert_eq!(dur.div_f64(3.14e5), Duration::new(0, 8_598));
806 /// ```
807 #[stable(feature = "duration_float", since = "1.38.0")]
808 #[inline]
809 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
810 pub const fn div_f64(self, rhs: f64) -> Duration {
811 Duration::from_secs_f64(self.as_secs_f64() / rhs)
812 }
813
814 /// Divide `Duration` by `f32`.
815 ///
816 /// # Panics
817 /// This method will panic if result is not finite, negative or overflows `Duration`.
818 ///
819 /// # Examples
820 /// ```
821 /// use std::time::Duration;
822 ///
823 /// let dur = Duration::new(2, 700_000_000);
824 /// // note that due to rounding errors result is slightly
825 /// // different from 0.859_872_611
826 /// assert_eq!(dur.div_f32(3.14), Duration::new(0, 859_872_576));
827 /// // note that truncation is used, not rounding
828 /// assert_eq!(dur.div_f32(3.14e5), Duration::new(0, 8_598));
829 /// ```
830 #[stable(feature = "duration_float", since = "1.38.0")]
831 #[inline]
832 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
833 pub const fn div_f32(self, rhs: f32) -> Duration {
834 Duration::from_secs_f32(self.as_secs_f32() / rhs)
835 }
836
837 /// Divide `Duration` by `Duration` and return `f64`.
838 ///
839 /// # Examples
840 /// ```
841 /// #![feature(div_duration)]
842 /// use std::time::Duration;
843 ///
844 /// let dur1 = Duration::new(2, 700_000_000);
845 /// let dur2 = Duration::new(5, 400_000_000);
846 /// assert_eq!(dur1.div_duration_f64(dur2), 0.5);
847 /// ```
848 #[unstable(feature = "div_duration", issue = "63139")]
849 #[inline]
850 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
851 pub const fn div_duration_f64(self, rhs: Duration) -> f64 {
852 self.as_secs_f64() / rhs.as_secs_f64()
853 }
854
855 /// Divide `Duration` by `Duration` and return `f32`.
856 ///
857 /// # Examples
858 /// ```
859 /// #![feature(div_duration)]
860 /// use std::time::Duration;
861 ///
862 /// let dur1 = Duration::new(2, 700_000_000);
863 /// let dur2 = Duration::new(5, 400_000_000);
864 /// assert_eq!(dur1.div_duration_f32(dur2), 0.5);
865 /// ```
866 #[unstable(feature = "div_duration", issue = "63139")]
867 #[inline]
868 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
869 pub const fn div_duration_f32(self, rhs: Duration) -> f32 {
870 self.as_secs_f32() / rhs.as_secs_f32()
871 }
872 }
873
874 #[stable(feature = "duration", since = "1.3.0")]
875 impl Add for Duration {
876 type Output = Duration;
877
878 fn add(self, rhs: Duration) -> Duration {
879 self.checked_add(rhs).expect("overflow when adding durations")
880 }
881 }
882
883 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
884 impl AddAssign for Duration {
885 fn add_assign(&mut self, rhs: Duration) {
886 *self = *self + rhs;
887 }
888 }
889
890 #[stable(feature = "duration", since = "1.3.0")]
891 impl Sub for Duration {
892 type Output = Duration;
893
894 fn sub(self, rhs: Duration) -> Duration {
895 self.checked_sub(rhs).expect("overflow when subtracting durations")
896 }
897 }
898
899 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
900 impl SubAssign for Duration {
901 fn sub_assign(&mut self, rhs: Duration) {
902 *self = *self - rhs;
903 }
904 }
905
906 #[stable(feature = "duration", since = "1.3.0")]
907 impl Mul<u32> for Duration {
908 type Output = Duration;
909
910 fn mul(self, rhs: u32) -> Duration {
911 self.checked_mul(rhs).expect("overflow when multiplying duration by scalar")
912 }
913 }
914
915 #[stable(feature = "symmetric_u32_duration_mul", since = "1.31.0")]
916 impl Mul<Duration> for u32 {
917 type Output = Duration;
918
919 fn mul(self, rhs: Duration) -> Duration {
920 rhs * self
921 }
922 }
923
924 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
925 impl MulAssign<u32> for Duration {
926 fn mul_assign(&mut self, rhs: u32) {
927 *self = *self * rhs;
928 }
929 }
930
931 #[stable(feature = "duration", since = "1.3.0")]
932 impl Div<u32> for Duration {
933 type Output = Duration;
934
935 fn div(self, rhs: u32) -> Duration {
936 self.checked_div(rhs).expect("divide by zero error when dividing duration by scalar")
937 }
938 }
939
940 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
941 impl DivAssign<u32> for Duration {
942 fn div_assign(&mut self, rhs: u32) {
943 *self = *self / rhs;
944 }
945 }
946
947 macro_rules! sum_durations {
948 ($iter:expr) => {{
949 let mut total_secs: u64 = 0;
950 let mut total_nanos: u64 = 0;
951
952 for entry in $iter {
953 total_secs =
954 total_secs.checked_add(entry.secs).expect("overflow in iter::sum over durations");
955 total_nanos = match total_nanos.checked_add(entry.nanos as u64) {
956 Some(n) => n,
957 None => {
958 total_secs = total_secs
959 .checked_add(total_nanos / NANOS_PER_SEC as u64)
960 .expect("overflow in iter::sum over durations");
961 (total_nanos % NANOS_PER_SEC as u64) + entry.nanos as u64
962 }
963 };
964 }
965 total_secs = total_secs
966 .checked_add(total_nanos / NANOS_PER_SEC as u64)
967 .expect("overflow in iter::sum over durations");
968 total_nanos = total_nanos % NANOS_PER_SEC as u64;
969 Duration { secs: total_secs, nanos: total_nanos as u32 }
970 }};
971 }
972
973 #[stable(feature = "duration_sum", since = "1.16.0")]
974 impl Sum for Duration {
975 fn sum<I: Iterator<Item = Duration>>(iter: I) -> Duration {
976 sum_durations!(iter)
977 }
978 }
979
980 #[stable(feature = "duration_sum", since = "1.16.0")]
981 impl<'a> Sum<&'a Duration> for Duration {
982 fn sum<I: Iterator<Item = &'a Duration>>(iter: I) -> Duration {
983 sum_durations!(iter)
984 }
985 }
986
987 #[stable(feature = "duration_debug_impl", since = "1.27.0")]
988 impl fmt::Debug for Duration {
989 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
990 /// Formats a floating point number in decimal notation.
991 ///
992 /// The number is given as the `integer_part` and a fractional part.
993 /// The value of the fractional part is `fractional_part / divisor`. So
994 /// `integer_part` = 3, `fractional_part` = 12 and `divisor` = 100
995 /// represents the number `3.012`. Trailing zeros are omitted.
996 ///
997 /// `divisor` must not be above 100_000_000. It also should be a power
998 /// of 10, everything else doesn't make sense. `fractional_part` has
999 /// to be less than `10 * divisor`!
1000 fn fmt_decimal(
1001 f: &mut fmt::Formatter<'_>,
1002 mut integer_part: u64,
1003 mut fractional_part: u32,
1004 mut divisor: u32,
1005 ) -> fmt::Result {
1006 // Encode the fractional part into a temporary buffer. The buffer
1007 // only need to hold 9 elements, because `fractional_part` has to
1008 // be smaller than 10^9. The buffer is prefilled with '0' digits
1009 // to simplify the code below.
1010 let mut buf = [b'0'; 9];
1011
1012 // The next digit is written at this position
1013 let mut pos = 0;
1014
1015 // We keep writing digits into the buffer while there are non-zero
1016 // digits left and we haven't written enough digits yet.
1017 while fractional_part > 0 && pos < f.precision().unwrap_or(9) {
1018 // Write new digit into the buffer
1019 buf[pos] = b'0' + (fractional_part / divisor) as u8;
1020
1021 fractional_part %= divisor;
1022 divisor /= 10;
1023 pos += 1;
1024 }
1025
1026 // If a precision < 9 was specified, there may be some non-zero
1027 // digits left that weren't written into the buffer. In that case we
1028 // need to perform rounding to match the semantics of printing
1029 // normal floating point numbers. However, we only need to do work
1030 // when rounding up. This happens if the first digit of the
1031 // remaining ones is >= 5.
1032 if fractional_part > 0 && fractional_part >= divisor * 5 {
1033 // Round up the number contained in the buffer. We go through
1034 // the buffer backwards and keep track of the carry.
1035 let mut rev_pos = pos;
1036 let mut carry = true;
1037 while carry && rev_pos > 0 {
1038 rev_pos -= 1;
1039
1040 // If the digit in the buffer is not '9', we just need to
1041 // increment it and can stop then (since we don't have a
1042 // carry anymore). Otherwise, we set it to '0' (overflow)
1043 // and continue.
1044 if buf[rev_pos] < b'9' {
1045 buf[rev_pos] += 1;
1046 carry = false;
1047 } else {
1048 buf[rev_pos] = b'0';
1049 }
1050 }
1051
1052 // If we still have the carry bit set, that means that we set
1053 // the whole buffer to '0's and need to increment the integer
1054 // part.
1055 if carry {
1056 integer_part += 1;
1057 }
1058 }
1059
1060 // Determine the end of the buffer: if precision is set, we just
1061 // use as many digits from the buffer (capped to 9). If it isn't
1062 // set, we only use all digits up to the last non-zero one.
1063 let end = f.precision().map(|p| crate::cmp::min(p, 9)).unwrap_or(pos);
1064
1065 // If we haven't emitted a single fractional digit and the precision
1066 // wasn't set to a non-zero value, we don't print the decimal point.
1067 if end == 0 {
1068 write!(f, "{}", integer_part)
1069 } else {
1070 // SAFETY: We are only writing ASCII digits into the buffer and it was
1071 // initialized with '0's, so it contains valid UTF8.
1072 let s = unsafe { crate::str::from_utf8_unchecked(&buf[..end]) };
1073
1074 // If the user request a precision > 9, we pad '0's at the end.
1075 let w = f.precision().unwrap_or(pos);
1076 write!(f, "{}.{:0<width$}", integer_part, s, width = w)
1077 }
1078 }
1079
1080 // Print leading '+' sign if requested
1081 if f.sign_plus() {
1082 write!(f, "+")?;
1083 }
1084
1085 if self.secs > 0 {
1086 fmt_decimal(f, self.secs, self.nanos, 100_000_000)?;
1087 f.write_str("s")
1088 } else if self.nanos >= 1_000_000 {
1089 fmt_decimal(f, self.nanos as u64 / 1_000_000, self.nanos % 1_000_000, 100_000)?;
1090 f.write_str("ms")
1091 } else if self.nanos >= 1_000 {
1092 fmt_decimal(f, self.nanos as u64 / 1_000, self.nanos % 1_000, 100)?;
1093 f.write_str("µs")
1094 } else {
1095 fmt_decimal(f, self.nanos as u64, 0, 1)?;
1096 f.write_str("ns")
1097 }
1098 }
1099 }