]> git.proxmox.com Git - rustc.git/blob - library/core/src/time.rs
New upstream version 1.57.0+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 #[must_use]
185 pub const fn new(secs: u64, nanos: u32) -> Duration {
186 let secs = match secs.checked_add((nanos / NANOS_PER_SEC) as u64) {
187 Some(secs) => secs,
188 None => panic!("overflow in Duration::new"),
189 };
190 let nanos = nanos % NANOS_PER_SEC;
191 Duration { secs, nanos }
192 }
193
194 /// Creates a new `Duration` from the specified number of whole seconds.
195 ///
196 /// # Examples
197 ///
198 /// ```
199 /// use std::time::Duration;
200 ///
201 /// let duration = Duration::from_secs(5);
202 ///
203 /// assert_eq!(5, duration.as_secs());
204 /// assert_eq!(0, duration.subsec_nanos());
205 /// ```
206 #[stable(feature = "duration", since = "1.3.0")]
207 #[must_use]
208 #[inline]
209 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
210 pub const fn from_secs(secs: u64) -> Duration {
211 Duration { secs, nanos: 0 }
212 }
213
214 /// Creates a new `Duration` from the specified number of milliseconds.
215 ///
216 /// # Examples
217 ///
218 /// ```
219 /// use std::time::Duration;
220 ///
221 /// let duration = Duration::from_millis(2569);
222 ///
223 /// assert_eq!(2, duration.as_secs());
224 /// assert_eq!(569_000_000, duration.subsec_nanos());
225 /// ```
226 #[stable(feature = "duration", since = "1.3.0")]
227 #[must_use]
228 #[inline]
229 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
230 pub const fn from_millis(millis: u64) -> Duration {
231 Duration {
232 secs: millis / MILLIS_PER_SEC,
233 nanos: ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI,
234 }
235 }
236
237 /// Creates a new `Duration` from the specified number of microseconds.
238 ///
239 /// # Examples
240 ///
241 /// ```
242 /// use std::time::Duration;
243 ///
244 /// let duration = Duration::from_micros(1_000_002);
245 ///
246 /// assert_eq!(1, duration.as_secs());
247 /// assert_eq!(2000, duration.subsec_nanos());
248 /// ```
249 #[stable(feature = "duration_from_micros", since = "1.27.0")]
250 #[must_use]
251 #[inline]
252 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
253 pub const fn from_micros(micros: u64) -> Duration {
254 Duration {
255 secs: micros / MICROS_PER_SEC,
256 nanos: ((micros % MICROS_PER_SEC) as u32) * NANOS_PER_MICRO,
257 }
258 }
259
260 /// Creates a new `Duration` from the specified number of nanoseconds.
261 ///
262 /// # Examples
263 ///
264 /// ```
265 /// use std::time::Duration;
266 ///
267 /// let duration = Duration::from_nanos(1_000_000_123);
268 ///
269 /// assert_eq!(1, duration.as_secs());
270 /// assert_eq!(123, duration.subsec_nanos());
271 /// ```
272 #[stable(feature = "duration_extras", since = "1.27.0")]
273 #[must_use]
274 #[inline]
275 #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
276 pub const fn from_nanos(nanos: u64) -> Duration {
277 Duration {
278 secs: nanos / (NANOS_PER_SEC as u64),
279 nanos: (nanos % (NANOS_PER_SEC as u64)) as u32,
280 }
281 }
282
283 /// Returns true if this `Duration` spans no time.
284 ///
285 /// # Examples
286 ///
287 /// ```
288 /// use std::time::Duration;
289 ///
290 /// assert!(Duration::ZERO.is_zero());
291 /// assert!(Duration::new(0, 0).is_zero());
292 /// assert!(Duration::from_nanos(0).is_zero());
293 /// assert!(Duration::from_secs(0).is_zero());
294 ///
295 /// assert!(!Duration::new(1, 1).is_zero());
296 /// assert!(!Duration::from_nanos(1).is_zero());
297 /// assert!(!Duration::from_secs(1).is_zero());
298 /// ```
299 #[must_use]
300 #[stable(feature = "duration_zero", since = "1.53.0")]
301 #[rustc_const_stable(feature = "duration_zero", since = "1.53.0")]
302 #[inline]
303 pub const fn is_zero(&self) -> bool {
304 self.secs == 0 && self.nanos == 0
305 }
306
307 /// Returns the number of _whole_ seconds contained by this `Duration`.
308 ///
309 /// The returned value does not include the fractional (nanosecond) part of the
310 /// duration, which can be obtained using [`subsec_nanos`].
311 ///
312 /// # Examples
313 ///
314 /// ```
315 /// use std::time::Duration;
316 ///
317 /// let duration = Duration::new(5, 730023852);
318 /// assert_eq!(duration.as_secs(), 5);
319 /// ```
320 ///
321 /// To determine the total number of seconds represented by the `Duration`,
322 /// use `as_secs` in combination with [`subsec_nanos`]:
323 ///
324 /// ```
325 /// use std::time::Duration;
326 ///
327 /// let duration = Duration::new(5, 730023852);
328 ///
329 /// assert_eq!(5.730023852,
330 /// duration.as_secs() as f64
331 /// + duration.subsec_nanos() as f64 * 1e-9);
332 /// ```
333 ///
334 /// [`subsec_nanos`]: Duration::subsec_nanos
335 #[stable(feature = "duration", since = "1.3.0")]
336 #[rustc_const_stable(feature = "duration", since = "1.32.0")]
337 #[must_use]
338 #[inline]
339 pub const fn as_secs(&self) -> u64 {
340 self.secs
341 }
342
343 /// Returns the fractional part of this `Duration`, in whole milliseconds.
344 ///
345 /// This method does **not** return the length of the duration when
346 /// represented by milliseconds. The returned number always represents a
347 /// fractional portion of a second (i.e., it is less than one thousand).
348 ///
349 /// # Examples
350 ///
351 /// ```
352 /// use std::time::Duration;
353 ///
354 /// let duration = Duration::from_millis(5432);
355 /// assert_eq!(duration.as_secs(), 5);
356 /// assert_eq!(duration.subsec_millis(), 432);
357 /// ```
358 #[stable(feature = "duration_extras", since = "1.27.0")]
359 #[rustc_const_stable(feature = "duration_extras", since = "1.32.0")]
360 #[inline]
361 pub const fn subsec_millis(&self) -> u32 {
362 self.nanos / NANOS_PER_MILLI
363 }
364
365 /// Returns the fractional part of this `Duration`, in whole microseconds.
366 ///
367 /// This method does **not** return the length of the duration when
368 /// represented by microseconds. The returned number always represents a
369 /// fractional portion of a second (i.e., it is less than one million).
370 ///
371 /// # Examples
372 ///
373 /// ```
374 /// use std::time::Duration;
375 ///
376 /// let duration = Duration::from_micros(1_234_567);
377 /// assert_eq!(duration.as_secs(), 1);
378 /// assert_eq!(duration.subsec_micros(), 234_567);
379 /// ```
380 #[stable(feature = "duration_extras", since = "1.27.0")]
381 #[rustc_const_stable(feature = "duration_extras", since = "1.32.0")]
382 #[inline]
383 pub const fn subsec_micros(&self) -> u32 {
384 self.nanos / NANOS_PER_MICRO
385 }
386
387 /// Returns the fractional part of this `Duration`, in nanoseconds.
388 ///
389 /// This method does **not** return the length of the duration when
390 /// represented by nanoseconds. The returned number always represents a
391 /// fractional portion of a second (i.e., it is less than one billion).
392 ///
393 /// # Examples
394 ///
395 /// ```
396 /// use std::time::Duration;
397 ///
398 /// let duration = Duration::from_millis(5010);
399 /// assert_eq!(duration.as_secs(), 5);
400 /// assert_eq!(duration.subsec_nanos(), 10_000_000);
401 /// ```
402 #[stable(feature = "duration", since = "1.3.0")]
403 #[rustc_const_stable(feature = "duration", since = "1.32.0")]
404 #[inline]
405 pub const fn subsec_nanos(&self) -> u32 {
406 self.nanos
407 }
408
409 /// Returns the total number of whole milliseconds contained by this `Duration`.
410 ///
411 /// # Examples
412 ///
413 /// ```
414 /// use std::time::Duration;
415 ///
416 /// let duration = Duration::new(5, 730023852);
417 /// assert_eq!(duration.as_millis(), 5730);
418 /// ```
419 #[stable(feature = "duration_as_u128", since = "1.33.0")]
420 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
421 #[must_use]
422 #[inline]
423 pub const fn as_millis(&self) -> u128 {
424 self.secs as u128 * MILLIS_PER_SEC as u128 + (self.nanos / NANOS_PER_MILLI) as u128
425 }
426
427 /// Returns the total number of whole microseconds contained by this `Duration`.
428 ///
429 /// # Examples
430 ///
431 /// ```
432 /// use std::time::Duration;
433 ///
434 /// let duration = Duration::new(5, 730023852);
435 /// assert_eq!(duration.as_micros(), 5730023);
436 /// ```
437 #[stable(feature = "duration_as_u128", since = "1.33.0")]
438 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
439 #[must_use]
440 #[inline]
441 pub const fn as_micros(&self) -> u128 {
442 self.secs as u128 * MICROS_PER_SEC as u128 + (self.nanos / NANOS_PER_MICRO) as u128
443 }
444
445 /// Returns the total number of nanoseconds contained by this `Duration`.
446 ///
447 /// # Examples
448 ///
449 /// ```
450 /// use std::time::Duration;
451 ///
452 /// let duration = Duration::new(5, 730023852);
453 /// assert_eq!(duration.as_nanos(), 5730023852);
454 /// ```
455 #[stable(feature = "duration_as_u128", since = "1.33.0")]
456 #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
457 #[must_use]
458 #[inline]
459 pub const fn as_nanos(&self) -> u128 {
460 self.secs as u128 * NANOS_PER_SEC as u128 + self.nanos as u128
461 }
462
463 /// Checked `Duration` addition. Computes `self + other`, returning [`None`]
464 /// if overflow occurred.
465 ///
466 /// # Examples
467 ///
468 /// Basic usage:
469 ///
470 /// ```
471 /// use std::time::Duration;
472 ///
473 /// assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1)));
474 /// assert_eq!(Duration::new(1, 0).checked_add(Duration::new(u64::MAX, 0)), None);
475 /// ```
476 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
477 #[must_use = "this returns the result of the operation, \
478 without modifying the original"]
479 #[inline]
480 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
481 pub const fn checked_add(self, rhs: Duration) -> Option<Duration> {
482 if let Some(mut secs) = self.secs.checked_add(rhs.secs) {
483 let mut nanos = self.nanos + rhs.nanos;
484 if nanos >= NANOS_PER_SEC {
485 nanos -= NANOS_PER_SEC;
486 if let Some(new_secs) = secs.checked_add(1) {
487 secs = new_secs;
488 } else {
489 return None;
490 }
491 }
492 debug_assert!(nanos < NANOS_PER_SEC);
493 Some(Duration { secs, nanos })
494 } else {
495 None
496 }
497 }
498
499 /// Saturating `Duration` addition. Computes `self + other`, returning [`Duration::MAX`]
500 /// if overflow occurred.
501 ///
502 /// # Examples
503 ///
504 /// ```
505 /// #![feature(duration_constants)]
506 /// use std::time::Duration;
507 ///
508 /// assert_eq!(Duration::new(0, 0).saturating_add(Duration::new(0, 1)), Duration::new(0, 1));
509 /// assert_eq!(Duration::new(1, 0).saturating_add(Duration::new(u64::MAX, 0)), Duration::MAX);
510 /// ```
511 #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
512 #[must_use = "this returns the result of the operation, \
513 without modifying the original"]
514 #[inline]
515 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
516 pub const fn saturating_add(self, rhs: Duration) -> Duration {
517 match self.checked_add(rhs) {
518 Some(res) => res,
519 None => Duration::MAX,
520 }
521 }
522
523 /// Checked `Duration` subtraction. Computes `self - other`, returning [`None`]
524 /// if the result would be negative or if overflow occurred.
525 ///
526 /// # Examples
527 ///
528 /// Basic usage:
529 ///
530 /// ```
531 /// use std::time::Duration;
532 ///
533 /// assert_eq!(Duration::new(0, 1).checked_sub(Duration::new(0, 0)), Some(Duration::new(0, 1)));
534 /// assert_eq!(Duration::new(0, 0).checked_sub(Duration::new(0, 1)), None);
535 /// ```
536 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
537 #[must_use = "this returns the result of the operation, \
538 without modifying the original"]
539 #[inline]
540 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
541 pub const fn checked_sub(self, rhs: Duration) -> Option<Duration> {
542 if let Some(mut secs) = self.secs.checked_sub(rhs.secs) {
543 let nanos = if self.nanos >= rhs.nanos {
544 self.nanos - rhs.nanos
545 } else if let Some(sub_secs) = secs.checked_sub(1) {
546 secs = sub_secs;
547 self.nanos + NANOS_PER_SEC - rhs.nanos
548 } else {
549 return None;
550 };
551 debug_assert!(nanos < NANOS_PER_SEC);
552 Some(Duration { secs, nanos })
553 } else {
554 None
555 }
556 }
557
558 /// Saturating `Duration` subtraction. Computes `self - other`, returning [`Duration::ZERO`]
559 /// if the result would be negative or if overflow occurred.
560 ///
561 /// # Examples
562 ///
563 /// ```
564 /// use std::time::Duration;
565 ///
566 /// assert_eq!(Duration::new(0, 1).saturating_sub(Duration::new(0, 0)), Duration::new(0, 1));
567 /// assert_eq!(Duration::new(0, 0).saturating_sub(Duration::new(0, 1)), Duration::ZERO);
568 /// ```
569 #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
570 #[must_use = "this returns the result of the operation, \
571 without modifying the original"]
572 #[inline]
573 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
574 pub const fn saturating_sub(self, rhs: Duration) -> Duration {
575 match self.checked_sub(rhs) {
576 Some(res) => res,
577 None => Duration::ZERO,
578 }
579 }
580
581 /// Checked `Duration` multiplication. Computes `self * other`, returning
582 /// [`None`] if overflow occurred.
583 ///
584 /// # Examples
585 ///
586 /// Basic usage:
587 ///
588 /// ```
589 /// use std::time::Duration;
590 ///
591 /// assert_eq!(Duration::new(0, 500_000_001).checked_mul(2), Some(Duration::new(1, 2)));
592 /// assert_eq!(Duration::new(u64::MAX - 1, 0).checked_mul(2), None);
593 /// ```
594 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
595 #[must_use = "this returns the result of the operation, \
596 without modifying the original"]
597 #[inline]
598 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
599 pub const fn checked_mul(self, rhs: u32) -> Option<Duration> {
600 // Multiply nanoseconds as u64, because it cannot overflow that way.
601 let total_nanos = self.nanos as u64 * rhs as u64;
602 let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
603 let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
604 if let Some(s) = self.secs.checked_mul(rhs as u64) {
605 if let Some(secs) = s.checked_add(extra_secs) {
606 debug_assert!(nanos < NANOS_PER_SEC);
607 return Some(Duration { secs, nanos });
608 }
609 }
610 None
611 }
612
613 /// Saturating `Duration` multiplication. Computes `self * other`, returning
614 /// [`Duration::MAX`] if overflow occurred.
615 ///
616 /// # Examples
617 ///
618 /// ```
619 /// #![feature(duration_constants)]
620 /// use std::time::Duration;
621 ///
622 /// assert_eq!(Duration::new(0, 500_000_001).saturating_mul(2), Duration::new(1, 2));
623 /// assert_eq!(Duration::new(u64::MAX - 1, 0).saturating_mul(2), Duration::MAX);
624 /// ```
625 #[stable(feature = "duration_saturating_ops", since = "1.53.0")]
626 #[must_use = "this returns the result of the operation, \
627 without modifying the original"]
628 #[inline]
629 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
630 pub const fn saturating_mul(self, rhs: u32) -> Duration {
631 match self.checked_mul(rhs) {
632 Some(res) => res,
633 None => Duration::MAX,
634 }
635 }
636
637 /// Checked `Duration` division. Computes `self / other`, returning [`None`]
638 /// if `other == 0`.
639 ///
640 /// # Examples
641 ///
642 /// Basic usage:
643 ///
644 /// ```
645 /// use std::time::Duration;
646 ///
647 /// assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0)));
648 /// assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000)));
649 /// assert_eq!(Duration::new(2, 0).checked_div(0), None);
650 /// ```
651 #[stable(feature = "duration_checked_ops", since = "1.16.0")]
652 #[must_use = "this returns the result of the operation, \
653 without modifying the original"]
654 #[inline]
655 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
656 pub const fn checked_div(self, rhs: u32) -> Option<Duration> {
657 if rhs != 0 {
658 let secs = self.secs / (rhs as u64);
659 let carry = self.secs - secs * (rhs as u64);
660 let extra_nanos = carry * (NANOS_PER_SEC as u64) / (rhs as u64);
661 let nanos = self.nanos / rhs + (extra_nanos as u32);
662 debug_assert!(nanos < NANOS_PER_SEC);
663 Some(Duration { secs, nanos })
664 } else {
665 None
666 }
667 }
668
669 /// Returns the number of seconds contained by this `Duration` as `f64`.
670 ///
671 /// The returned value does include the fractional (nanosecond) part of the duration.
672 ///
673 /// # Examples
674 /// ```
675 /// use std::time::Duration;
676 ///
677 /// let dur = Duration::new(2, 700_000_000);
678 /// assert_eq!(dur.as_secs_f64(), 2.7);
679 /// ```
680 #[stable(feature = "duration_float", since = "1.38.0")]
681 #[must_use]
682 #[inline]
683 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
684 pub const fn as_secs_f64(&self) -> f64 {
685 (self.secs as f64) + (self.nanos as f64) / (NANOS_PER_SEC as f64)
686 }
687
688 /// Returns the number of seconds contained by this `Duration` as `f32`.
689 ///
690 /// The returned value does include the fractional (nanosecond) part of the duration.
691 ///
692 /// # Examples
693 /// ```
694 /// use std::time::Duration;
695 ///
696 /// let dur = Duration::new(2, 700_000_000);
697 /// assert_eq!(dur.as_secs_f32(), 2.7);
698 /// ```
699 #[stable(feature = "duration_float", since = "1.38.0")]
700 #[must_use]
701 #[inline]
702 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
703 pub const fn as_secs_f32(&self) -> f32 {
704 (self.secs as f32) + (self.nanos as f32) / (NANOS_PER_SEC as f32)
705 }
706
707 /// Creates a new `Duration` from the specified number of seconds represented
708 /// as `f64`.
709 ///
710 /// # Panics
711 /// This constructor will panic if `secs` is not finite, negative or overflows `Duration`.
712 ///
713 /// # Examples
714 /// ```
715 /// use std::time::Duration;
716 ///
717 /// let dur = Duration::from_secs_f64(2.7);
718 /// assert_eq!(dur, Duration::new(2, 700_000_000));
719 /// ```
720 #[stable(feature = "duration_float", since = "1.38.0")]
721 #[must_use]
722 #[inline]
723 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
724 pub const fn from_secs_f64(secs: f64) -> Duration {
725 match Duration::try_from_secs_f64(secs) {
726 Ok(v) => v,
727 Err(e) => crate::panicking::panic(e.description()),
728 }
729 }
730
731 /// The checked version of [`from_secs_f64`].
732 ///
733 /// [`from_secs_f64`]: Duration::from_secs_f64
734 ///
735 /// This constructor will return an `Err` if `secs` is not finite, negative or overflows `Duration`.
736 ///
737 /// # Examples
738 /// ```
739 /// #![feature(duration_checked_float)]
740 ///
741 /// use std::time::Duration;
742 ///
743 /// let dur = Duration::try_from_secs_f64(2.7);
744 /// assert_eq!(dur, Ok(Duration::new(2, 700_000_000)));
745 ///
746 /// let negative = Duration::try_from_secs_f64(-5.0);
747 /// assert!(negative.is_err());
748 /// ```
749 #[unstable(feature = "duration_checked_float", issue = "83400")]
750 #[inline]
751 pub const fn try_from_secs_f64(secs: f64) -> Result<Duration, FromSecsError> {
752 const MAX_NANOS_F64: f64 = ((u64::MAX as u128 + 1) * (NANOS_PER_SEC as u128)) as f64;
753 let nanos = secs * (NANOS_PER_SEC as f64);
754 if !nanos.is_finite() {
755 Err(FromSecsError { kind: FromSecsErrorKind::NonFinite })
756 } else if nanos >= MAX_NANOS_F64 {
757 Err(FromSecsError { kind: FromSecsErrorKind::Overflow })
758 } else if nanos < 0.0 {
759 Err(FromSecsError { kind: FromSecsErrorKind::Underflow })
760 } else {
761 let nanos = nanos as u128;
762 Ok(Duration {
763 secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
764 nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
765 })
766 }
767 }
768
769 /// Creates a new `Duration` from the specified number of seconds represented
770 /// as `f32`.
771 ///
772 /// # Panics
773 /// This constructor will panic if `secs` is not finite, negative or overflows `Duration`.
774 ///
775 /// # Examples
776 /// ```
777 /// use std::time::Duration;
778 ///
779 /// let dur = Duration::from_secs_f32(2.7);
780 /// assert_eq!(dur, Duration::new(2, 700_000_000));
781 /// ```
782 #[stable(feature = "duration_float", since = "1.38.0")]
783 #[must_use]
784 #[inline]
785 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
786 pub const fn from_secs_f32(secs: f32) -> Duration {
787 match Duration::try_from_secs_f32(secs) {
788 Ok(v) => v,
789 Err(e) => crate::panicking::panic(e.description()),
790 }
791 }
792
793 /// The checked version of [`from_secs_f32`].
794 ///
795 /// [`from_secs_f32`]: Duration::from_secs_f32
796 ///
797 /// This constructor will return an `Err` if `secs` is not finite, negative or overflows `Duration`.
798 ///
799 /// # Examples
800 /// ```
801 /// #![feature(duration_checked_float)]
802 ///
803 /// use std::time::Duration;
804 ///
805 /// let dur = Duration::try_from_secs_f32(2.7);
806 /// assert_eq!(dur, Ok(Duration::new(2, 700_000_000)));
807 ///
808 /// let negative = Duration::try_from_secs_f32(-5.0);
809 /// assert!(negative.is_err());
810 /// ```
811 #[unstable(feature = "duration_checked_float", issue = "83400")]
812 #[inline]
813 pub const fn try_from_secs_f32(secs: f32) -> Result<Duration, FromSecsError> {
814 const MAX_NANOS_F32: f32 = ((u64::MAX as u128 + 1) * (NANOS_PER_SEC as u128)) as f32;
815 let nanos = secs * (NANOS_PER_SEC as f32);
816 if !nanos.is_finite() {
817 Err(FromSecsError { kind: FromSecsErrorKind::NonFinite })
818 } else if nanos >= MAX_NANOS_F32 {
819 Err(FromSecsError { kind: FromSecsErrorKind::Overflow })
820 } else if nanos < 0.0 {
821 Err(FromSecsError { kind: FromSecsErrorKind::Underflow })
822 } else {
823 let nanos = nanos as u128;
824 Ok(Duration {
825 secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
826 nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
827 })
828 }
829 }
830
831 /// Multiplies `Duration` by `f64`.
832 ///
833 /// # Panics
834 /// This method will panic if result is not finite, negative or overflows `Duration`.
835 ///
836 /// # Examples
837 /// ```
838 /// use std::time::Duration;
839 ///
840 /// let dur = Duration::new(2, 700_000_000);
841 /// assert_eq!(dur.mul_f64(3.14), Duration::new(8, 478_000_000));
842 /// assert_eq!(dur.mul_f64(3.14e5), Duration::new(847_800, 0));
843 /// ```
844 #[stable(feature = "duration_float", since = "1.38.0")]
845 #[must_use = "this returns the result of the operation, \
846 without modifying the original"]
847 #[inline]
848 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
849 pub const fn mul_f64(self, rhs: f64) -> Duration {
850 Duration::from_secs_f64(rhs * self.as_secs_f64())
851 }
852
853 /// Multiplies `Duration` by `f32`.
854 ///
855 /// # Panics
856 /// This method will panic if result is not finite, negative or overflows `Duration`.
857 ///
858 /// # Examples
859 /// ```
860 /// use std::time::Duration;
861 ///
862 /// let dur = Duration::new(2, 700_000_000);
863 /// // note that due to rounding errors result is slightly different
864 /// // from 8.478 and 847800.0
865 /// assert_eq!(dur.mul_f32(3.14), Duration::new(8, 478_000_640));
866 /// assert_eq!(dur.mul_f32(3.14e5), Duration::new(847799, 969_120_256));
867 /// ```
868 #[stable(feature = "duration_float", since = "1.38.0")]
869 #[must_use = "this returns the result of the operation, \
870 without modifying the original"]
871 #[inline]
872 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
873 pub const fn mul_f32(self, rhs: f32) -> Duration {
874 Duration::from_secs_f32(rhs * self.as_secs_f32())
875 }
876
877 /// Divide `Duration` by `f64`.
878 ///
879 /// # Panics
880 /// This method will panic if result is not finite, negative or overflows `Duration`.
881 ///
882 /// # Examples
883 /// ```
884 /// use std::time::Duration;
885 ///
886 /// let dur = Duration::new(2, 700_000_000);
887 /// assert_eq!(dur.div_f64(3.14), Duration::new(0, 859_872_611));
888 /// // note that truncation is used, not rounding
889 /// assert_eq!(dur.div_f64(3.14e5), Duration::new(0, 8_598));
890 /// ```
891 #[stable(feature = "duration_float", since = "1.38.0")]
892 #[must_use = "this returns the result of the operation, \
893 without modifying the original"]
894 #[inline]
895 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
896 pub const fn div_f64(self, rhs: f64) -> Duration {
897 Duration::from_secs_f64(self.as_secs_f64() / rhs)
898 }
899
900 /// Divide `Duration` by `f32`.
901 ///
902 /// # Panics
903 /// This method will panic if result is not finite, negative or overflows `Duration`.
904 ///
905 /// # Examples
906 /// ```
907 /// use std::time::Duration;
908 ///
909 /// let dur = Duration::new(2, 700_000_000);
910 /// // note that due to rounding errors result is slightly
911 /// // different from 0.859_872_611
912 /// assert_eq!(dur.div_f32(3.14), Duration::new(0, 859_872_576));
913 /// // note that truncation is used, not rounding
914 /// assert_eq!(dur.div_f32(3.14e5), Duration::new(0, 8_598));
915 /// ```
916 #[stable(feature = "duration_float", since = "1.38.0")]
917 #[must_use = "this returns the result of the operation, \
918 without modifying the original"]
919 #[inline]
920 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
921 pub const fn div_f32(self, rhs: f32) -> Duration {
922 Duration::from_secs_f32(self.as_secs_f32() / rhs)
923 }
924
925 /// Divide `Duration` by `Duration` and return `f64`.
926 ///
927 /// # Examples
928 /// ```
929 /// #![feature(div_duration)]
930 /// use std::time::Duration;
931 ///
932 /// let dur1 = Duration::new(2, 700_000_000);
933 /// let dur2 = Duration::new(5, 400_000_000);
934 /// assert_eq!(dur1.div_duration_f64(dur2), 0.5);
935 /// ```
936 #[unstable(feature = "div_duration", issue = "63139")]
937 #[must_use = "this returns the result of the operation, \
938 without modifying the original"]
939 #[inline]
940 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
941 pub const fn div_duration_f64(self, rhs: Duration) -> f64 {
942 self.as_secs_f64() / rhs.as_secs_f64()
943 }
944
945 /// Divide `Duration` by `Duration` and return `f32`.
946 ///
947 /// # Examples
948 /// ```
949 /// #![feature(div_duration)]
950 /// use std::time::Duration;
951 ///
952 /// let dur1 = Duration::new(2, 700_000_000);
953 /// let dur2 = Duration::new(5, 400_000_000);
954 /// assert_eq!(dur1.div_duration_f32(dur2), 0.5);
955 /// ```
956 #[unstable(feature = "div_duration", issue = "63139")]
957 #[must_use = "this returns the result of the operation, \
958 without modifying the original"]
959 #[inline]
960 #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
961 pub const fn div_duration_f32(self, rhs: Duration) -> f32 {
962 self.as_secs_f32() / rhs.as_secs_f32()
963 }
964 }
965
966 #[stable(feature = "duration", since = "1.3.0")]
967 impl Add for Duration {
968 type Output = Duration;
969
970 fn add(self, rhs: Duration) -> Duration {
971 self.checked_add(rhs).expect("overflow when adding durations")
972 }
973 }
974
975 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
976 impl AddAssign for Duration {
977 fn add_assign(&mut self, rhs: Duration) {
978 *self = *self + rhs;
979 }
980 }
981
982 #[stable(feature = "duration", since = "1.3.0")]
983 impl Sub for Duration {
984 type Output = Duration;
985
986 fn sub(self, rhs: Duration) -> Duration {
987 self.checked_sub(rhs).expect("overflow when subtracting durations")
988 }
989 }
990
991 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
992 impl SubAssign for Duration {
993 fn sub_assign(&mut self, rhs: Duration) {
994 *self = *self - rhs;
995 }
996 }
997
998 #[stable(feature = "duration", since = "1.3.0")]
999 impl Mul<u32> for Duration {
1000 type Output = Duration;
1001
1002 fn mul(self, rhs: u32) -> Duration {
1003 self.checked_mul(rhs).expect("overflow when multiplying duration by scalar")
1004 }
1005 }
1006
1007 #[stable(feature = "symmetric_u32_duration_mul", since = "1.31.0")]
1008 impl Mul<Duration> for u32 {
1009 type Output = Duration;
1010
1011 fn mul(self, rhs: Duration) -> Duration {
1012 rhs * self
1013 }
1014 }
1015
1016 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
1017 impl MulAssign<u32> for Duration {
1018 fn mul_assign(&mut self, rhs: u32) {
1019 *self = *self * rhs;
1020 }
1021 }
1022
1023 #[stable(feature = "duration", since = "1.3.0")]
1024 impl Div<u32> for Duration {
1025 type Output = Duration;
1026
1027 fn div(self, rhs: u32) -> Duration {
1028 self.checked_div(rhs).expect("divide by zero error when dividing duration by scalar")
1029 }
1030 }
1031
1032 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
1033 impl DivAssign<u32> for Duration {
1034 fn div_assign(&mut self, rhs: u32) {
1035 *self = *self / rhs;
1036 }
1037 }
1038
1039 macro_rules! sum_durations {
1040 ($iter:expr) => {{
1041 let mut total_secs: u64 = 0;
1042 let mut total_nanos: u64 = 0;
1043
1044 for entry in $iter {
1045 total_secs =
1046 total_secs.checked_add(entry.secs).expect("overflow in iter::sum over durations");
1047 total_nanos = match total_nanos.checked_add(entry.nanos as u64) {
1048 Some(n) => n,
1049 None => {
1050 total_secs = total_secs
1051 .checked_add(total_nanos / NANOS_PER_SEC as u64)
1052 .expect("overflow in iter::sum over durations");
1053 (total_nanos % NANOS_PER_SEC as u64) + entry.nanos as u64
1054 }
1055 };
1056 }
1057 total_secs = total_secs
1058 .checked_add(total_nanos / NANOS_PER_SEC as u64)
1059 .expect("overflow in iter::sum over durations");
1060 total_nanos = total_nanos % NANOS_PER_SEC as u64;
1061 Duration { secs: total_secs, nanos: total_nanos as u32 }
1062 }};
1063 }
1064
1065 #[stable(feature = "duration_sum", since = "1.16.0")]
1066 impl Sum for Duration {
1067 fn sum<I: Iterator<Item = Duration>>(iter: I) -> Duration {
1068 sum_durations!(iter)
1069 }
1070 }
1071
1072 #[stable(feature = "duration_sum", since = "1.16.0")]
1073 impl<'a> Sum<&'a Duration> for Duration {
1074 fn sum<I: Iterator<Item = &'a Duration>>(iter: I) -> Duration {
1075 sum_durations!(iter)
1076 }
1077 }
1078
1079 #[stable(feature = "duration_debug_impl", since = "1.27.0")]
1080 impl fmt::Debug for Duration {
1081 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1082 /// Formats a floating point number in decimal notation.
1083 ///
1084 /// The number is given as the `integer_part` and a fractional part.
1085 /// The value of the fractional part is `fractional_part / divisor`. So
1086 /// `integer_part` = 3, `fractional_part` = 12 and `divisor` = 100
1087 /// represents the number `3.012`. Trailing zeros are omitted.
1088 ///
1089 /// `divisor` must not be above 100_000_000. It also should be a power
1090 /// of 10, everything else doesn't make sense. `fractional_part` has
1091 /// to be less than `10 * divisor`!
1092 ///
1093 /// A prefix and postfix may be added. The whole thing is padded
1094 /// to the formatter's `width`, if specified.
1095 fn fmt_decimal(
1096 f: &mut fmt::Formatter<'_>,
1097 mut integer_part: u64,
1098 mut fractional_part: u32,
1099 mut divisor: u32,
1100 prefix: &str,
1101 postfix: &str,
1102 ) -> fmt::Result {
1103 // Encode the fractional part into a temporary buffer. The buffer
1104 // only need to hold 9 elements, because `fractional_part` has to
1105 // be smaller than 10^9. The buffer is prefilled with '0' digits
1106 // to simplify the code below.
1107 let mut buf = [b'0'; 9];
1108
1109 // The next digit is written at this position
1110 let mut pos = 0;
1111
1112 // We keep writing digits into the buffer while there are non-zero
1113 // digits left and we haven't written enough digits yet.
1114 while fractional_part > 0 && pos < f.precision().unwrap_or(9) {
1115 // Write new digit into the buffer
1116 buf[pos] = b'0' + (fractional_part / divisor) as u8;
1117
1118 fractional_part %= divisor;
1119 divisor /= 10;
1120 pos += 1;
1121 }
1122
1123 // If a precision < 9 was specified, there may be some non-zero
1124 // digits left that weren't written into the buffer. In that case we
1125 // need to perform rounding to match the semantics of printing
1126 // normal floating point numbers. However, we only need to do work
1127 // when rounding up. This happens if the first digit of the
1128 // remaining ones is >= 5.
1129 if fractional_part > 0 && fractional_part >= divisor * 5 {
1130 // Round up the number contained in the buffer. We go through
1131 // the buffer backwards and keep track of the carry.
1132 let mut rev_pos = pos;
1133 let mut carry = true;
1134 while carry && rev_pos > 0 {
1135 rev_pos -= 1;
1136
1137 // If the digit in the buffer is not '9', we just need to
1138 // increment it and can stop then (since we don't have a
1139 // carry anymore). Otherwise, we set it to '0' (overflow)
1140 // and continue.
1141 if buf[rev_pos] < b'9' {
1142 buf[rev_pos] += 1;
1143 carry = false;
1144 } else {
1145 buf[rev_pos] = b'0';
1146 }
1147 }
1148
1149 // If we still have the carry bit set, that means that we set
1150 // the whole buffer to '0's and need to increment the integer
1151 // part.
1152 if carry {
1153 integer_part += 1;
1154 }
1155 }
1156
1157 // Determine the end of the buffer: if precision is set, we just
1158 // use as many digits from the buffer (capped to 9). If it isn't
1159 // set, we only use all digits up to the last non-zero one.
1160 let end = f.precision().map(|p| crate::cmp::min(p, 9)).unwrap_or(pos);
1161
1162 // This closure emits the formatted duration without emitting any
1163 // padding (padding is calculated below).
1164 let emit_without_padding = |f: &mut fmt::Formatter<'_>| {
1165 write!(f, "{}{}", prefix, integer_part)?;
1166
1167 // Write the decimal point and the fractional part (if any).
1168 if end > 0 {
1169 // SAFETY: We are only writing ASCII digits into the buffer and
1170 // it was initialized with '0's, so it contains valid UTF8.
1171 let s = unsafe { crate::str::from_utf8_unchecked(&buf[..end]) };
1172
1173 // If the user request a precision > 9, we pad '0's at the end.
1174 let w = f.precision().unwrap_or(pos);
1175 write!(f, ".{:0<width$}", s, width = w)?;
1176 }
1177
1178 write!(f, "{}", postfix)
1179 };
1180
1181 match f.width() {
1182 None => {
1183 // No `width` specified. There's no need to calculate the
1184 // length of the output in this case, just emit it.
1185 emit_without_padding(f)
1186 }
1187 Some(requested_w) => {
1188 // A `width` was specified. Calculate the actual width of
1189 // the output in order to calculate the required padding.
1190 // It consists of 4 parts:
1191 // 1. The prefix: is either "+" or "", so we can just use len().
1192 // 2. The postfix: can be "µs" so we have to count UTF8 characters.
1193 let mut actual_w = prefix.len() + postfix.chars().count();
1194 // 3. The integer part:
1195 if let Some(log) = integer_part.checked_log10() {
1196 // integer_part is > 0, so has length log10(x)+1
1197 actual_w += 1 + log as usize;
1198 } else {
1199 // integer_part is 0, so has length 1.
1200 actual_w += 1;
1201 }
1202 // 4. The fractional part (if any):
1203 if end > 0 {
1204 let frac_part_w = f.precision().unwrap_or(pos);
1205 actual_w += 1 + frac_part_w;
1206 }
1207
1208 if requested_w <= actual_w {
1209 // Output is already longer than `width`, so don't pad.
1210 emit_without_padding(f)
1211 } else {
1212 // We need to add padding. Use the `Formatter::padding` helper function.
1213 let default_align = crate::fmt::rt::v1::Alignment::Left;
1214 let post_padding = f.padding(requested_w - actual_w, default_align)?;
1215 emit_without_padding(f)?;
1216 post_padding.write(f)
1217 }
1218 }
1219 }
1220 }
1221
1222 // Print leading '+' sign if requested
1223 let prefix = if f.sign_plus() { "+" } else { "" };
1224
1225 if self.secs > 0 {
1226 fmt_decimal(f, self.secs, self.nanos, NANOS_PER_SEC / 10, prefix, "s")
1227 } else if self.nanos >= NANOS_PER_MILLI {
1228 fmt_decimal(
1229 f,
1230 (self.nanos / NANOS_PER_MILLI) as u64,
1231 self.nanos % NANOS_PER_MILLI,
1232 NANOS_PER_MILLI / 10,
1233 prefix,
1234 "ms",
1235 )
1236 } else if self.nanos >= NANOS_PER_MICRO {
1237 fmt_decimal(
1238 f,
1239 (self.nanos / NANOS_PER_MICRO) as u64,
1240 self.nanos % NANOS_PER_MICRO,
1241 NANOS_PER_MICRO / 10,
1242 prefix,
1243 "µs",
1244 )
1245 } else {
1246 fmt_decimal(f, self.nanos as u64, 0, 1, prefix, "ns")
1247 }
1248 }
1249 }
1250
1251 /// An error which can be returned when converting a floating-point value of seconds
1252 /// into a [`Duration`].
1253 ///
1254 /// This error is used as the error type for [`Duration::try_from_secs_f32`] and
1255 /// [`Duration::try_from_secs_f64`].
1256 ///
1257 /// # Example
1258 ///
1259 /// ```
1260 /// #![feature(duration_checked_float)]
1261 ///
1262 /// use std::time::Duration;
1263 ///
1264 /// if let Err(e) = Duration::try_from_secs_f32(-1.0) {
1265 /// println!("Failed conversion to Duration: {}", e);
1266 /// }
1267 /// ```
1268 #[derive(Debug, Clone, PartialEq, Eq)]
1269 #[unstable(feature = "duration_checked_float", issue = "83400")]
1270 pub struct FromSecsError {
1271 kind: FromSecsErrorKind,
1272 }
1273
1274 impl FromSecsError {
1275 const fn description(&self) -> &'static str {
1276 match self.kind {
1277 FromSecsErrorKind::NonFinite => {
1278 "got non-finite value when converting float to duration"
1279 }
1280 FromSecsErrorKind::Overflow => "overflow when converting float to duration",
1281 FromSecsErrorKind::Underflow => "underflow when converting float to duration",
1282 }
1283 }
1284 }
1285
1286 #[unstable(feature = "duration_checked_float", issue = "83400")]
1287 impl fmt::Display for FromSecsError {
1288 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1289 fmt::Display::fmt(self.description(), f)
1290 }
1291 }
1292
1293 #[derive(Debug, Clone, PartialEq, Eq)]
1294 enum FromSecsErrorKind {
1295 // Value is not a finite value (either infinity or NaN).
1296 NonFinite,
1297 // Value is too large to store in a `Duration`.
1298 Overflow,
1299 // Value is less than `0.0`.
1300 Underflow,
1301 }