time.rs 41.0 KB
Newer Older
1
#![stable(feature = "duration_core", since = "1.25.0")]
C
Clar Charr 已提交
2 3 4 5 6 7 8 9 10 11 12 13

//! Temporal quantification.
//!
//! Example:
//!
//! ```
//! use std::time::Duration;
//!
//! let five_seconds = Duration::new(5, 0);
//! // both declarations are equivalent
//! assert_eq!(Duration::new(5, 0), Duration::from_secs(5));
//! ```
B
Brian Anderson 已提交
14

15
use crate::fmt;
T
Taiki Endo 已提交
16
use crate::iter::Sum;
D
David Tolnay 已提交
17
use crate::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
18 19 20

const NANOS_PER_SEC: u32 = 1_000_000_000;
const NANOS_PER_MILLI: u32 = 1_000_000;
21
const NANOS_PER_MICRO: u32 = 1_000;
22
const MILLIS_PER_SEC: u64 = 1_000;
R
Romain Porte 已提交
23
const MICROS_PER_SEC: u64 = 1_000_000;
24

G
Guillaume Gomez 已提交
25
/// A `Duration` type to represent a span of time, typically used for system
26 27
/// timeouts.
///
28
/// Each `Duration` is composed of a whole number of seconds and a fractional part
A
Alexander Regueiro 已提交
29
/// represented in nanoseconds. If the underlying system does not support
30 31
/// nanosecond-level precision, APIs binding a system timeout will typically round up
/// the number of nanoseconds.
32
///
D
Denis Vasilik 已提交
33 34
/// [`Duration`]s implement many common traits, including [`Add`], [`Sub`], and other
/// [`ops`] traits. It implements [`Default`] by returning a zero-length `Duration`.
G
Guillaume Gomez 已提交
35
///
D
Denis Vasilik 已提交
36
/// [`ops`]: crate::ops
37 38 39 40 41 42 43 44 45
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let five_seconds = Duration::new(5, 0);
/// let five_seconds_and_five_nanos = five_seconds + Duration::new(0, 5);
///
S
Steven Fackler 已提交
46 47
/// assert_eq!(five_seconds_and_five_nanos.as_secs(), 5);
/// assert_eq!(five_seconds_and_five_nanos.subsec_nanos(), 5);
48 49 50
///
/// let ten_millis = Duration::from_millis(10);
/// ```
51
#[stable(feature = "duration", since = "1.3.0")]
52
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
B
Brian Anderson 已提交
53
pub struct Duration {
54 55
    secs: u64,
    nanos: u32, // Always 0 <= nanos < NANOS_PER_SEC
B
Brian Anderson 已提交
56 57 58
}

impl Duration {
59
    /// The duration of one second.
60 61 62 63
    ///
    /// # Examples
    ///
    /// ```
64
    /// #![feature(duration_constants)]
65 66 67 68
    /// use std::time::Duration;
    ///
    /// assert_eq!(Duration::SECOND, Duration::from_secs(1));
    /// ```
69 70 71 72
    #[unstable(feature = "duration_constants", issue = "57391")]
    pub const SECOND: Duration = Duration::from_secs(1);

    /// The duration of one millisecond.
73 74 75 76
    ///
    /// # Examples
    ///
    /// ```
77
    /// #![feature(duration_constants)]
78 79 80 81
    /// use std::time::Duration;
    ///
    /// assert_eq!(Duration::MILLISECOND, Duration::from_millis(1));
    /// ```
82 83 84 85
    #[unstable(feature = "duration_constants", issue = "57391")]
    pub const MILLISECOND: Duration = Duration::from_millis(1);

    /// The duration of one microsecond.
86 87 88 89
    ///
    /// # Examples
    ///
    /// ```
90
    /// #![feature(duration_constants)]
91 92 93 94
    /// use std::time::Duration;
    ///
    /// assert_eq!(Duration::MICROSECOND, Duration::from_micros(1));
    /// ```
95 96 97 98
    #[unstable(feature = "duration_constants", issue = "57391")]
    pub const MICROSECOND: Duration = Duration::from_micros(1);

    /// The duration of one nanosecond.
99 100 101 102
    ///
    /// # Examples
    ///
    /// ```
103
    /// #![feature(duration_constants)]
104 105 106 107
    /// use std::time::Duration;
    ///
    /// assert_eq!(Duration::NANOSECOND, Duration::from_nanos(1));
    /// ```
108 109 110
    #[unstable(feature = "duration_constants", issue = "57391")]
    pub const NANOSECOND: Duration = Duration::from_nanos(1);

J
Jubilee Young 已提交
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
    /// A duration of zero time.
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(duration_zero)]
    /// use std::time::Duration;
    ///
    /// let duration = Duration::ZERO;
    /// assert!(duration.is_zero());
    /// assert_eq!(duration.as_nanos(), 0);
    /// ```
    #[unstable(feature = "duration_zero", issue = "73544")]
    pub const ZERO: Duration = Duration::from_nanos(0);

126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
    /// The maximum duration.
    ///
    /// It is roughly equal to a duration of 584,942,417,355 years.
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(duration_constants)]
    /// use std::time::Duration;
    ///
    /// assert_eq!(Duration::MAX, Duration::new(u64::MAX, 1_000_000_000 - 1));
    /// ```
    #[unstable(feature = "duration_constants", issue = "57391")]
    pub const MAX: Duration = Duration::new(u64::MAX, NANOS_PER_SEC - 1);

141 142
    /// Creates a new `Duration` from the specified number of whole seconds and
    /// additional nanoseconds.
143
    ///
144 145
    /// If the number of nanoseconds is greater than 1 billion (the number of
    /// nanoseconds in a second), then it will carry over into the seconds provided.
146 147 148 149 150
    ///
    /// # Panics
    ///
    /// This constructor will panic if the carry from the nanoseconds overflows
    /// the seconds counter.
G
Guillaume Gomez 已提交
151 152 153 154 155 156 157 158
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// let five_seconds = Duration::new(5, 0);
    /// ```
S
Steven Fackler 已提交
159
    #[stable(feature = "duration", since = "1.3.0")]
160
    #[inline]
161 162 163 164 165 166
    #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
    pub const fn new(secs: u64, nanos: u32) -> Duration {
        let secs = match secs.checked_add((nanos / NANOS_PER_SEC) as u64) {
            Some(secs) => secs,
            None => panic!("overflow in Duration::new"),
        };
167
        let nanos = nanos % NANOS_PER_SEC;
L
ljedrz 已提交
168
        Duration { secs, nanos }
B
Brian Anderson 已提交
169 170
    }

171
    /// Creates a new `Duration` from the specified number of whole seconds.
G
Guillaume Gomez 已提交
172 173 174 175 176 177
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    ///
178 179 180 181
    /// let duration = Duration::from_secs(5);
    ///
    /// assert_eq!(5, duration.as_secs());
    /// assert_eq!(0, duration.subsec_nanos());
G
Guillaume Gomez 已提交
182
    /// ```
S
Steven Fackler 已提交
183
    #[stable(feature = "duration", since = "1.3.0")]
184
    #[inline]
M
Mark Rousskov 已提交
185
    #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
186
    pub const fn from_secs(secs: u64) -> Duration {
L
ljedrz 已提交
187
        Duration { secs, nanos: 0 }
B
Brian Anderson 已提交
188 189
    }

190
    /// Creates a new `Duration` from the specified number of milliseconds.
G
Guillaume Gomez 已提交
191 192 193 194 195 196
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    ///
197 198 199
    /// let duration = Duration::from_millis(2569);
    ///
    /// assert_eq!(2, duration.as_secs());
200
    /// assert_eq!(569_000_000, duration.subsec_nanos());
G
Guillaume Gomez 已提交
201
    /// ```
S
Steven Fackler 已提交
202
    #[stable(feature = "duration", since = "1.3.0")]
203
    #[inline]
M
Mark Rousskov 已提交
204
    #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
205
    pub const fn from_millis(millis: u64) -> Duration {
206
        Duration {
N
Nathaniel Ringo 已提交
207 208 209
            secs: millis / MILLIS_PER_SEC,
            nanos: ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI,
        }
R
Romain Porte 已提交
210
    }
R
Romain Porte 已提交
211 212 213 214 215 216 217 218 219 220 221 222 223

    /// Creates a new `Duration` from the specified number of microseconds.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// let duration = Duration::from_micros(1_000_002);
    ///
    /// assert_eq!(1, duration.as_secs());
    /// assert_eq!(2000, duration.subsec_nanos());
    /// ```
224
    #[stable(feature = "duration_from_micros", since = "1.27.0")]
R
Romain Porte 已提交
225
    #[inline]
M
Mark Rousskov 已提交
226
    #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
227
    pub const fn from_micros(micros: u64) -> Duration {
228
        Duration {
N
Nathaniel Ringo 已提交
229 230 231
            secs: micros / MICROS_PER_SEC,
            nanos: ((micros % MICROS_PER_SEC) as u32) * NANOS_PER_MICRO,
        }
B
Brian Anderson 已提交
232 233
    }

234 235 236 237 238 239 240 241 242 243 244 245
    /// Creates a new `Duration` from the specified number of nanoseconds.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// let duration = Duration::from_nanos(1_000_000_123);
    ///
    /// assert_eq!(1, duration.as_secs());
    /// assert_eq!(123, duration.subsec_nanos());
    /// ```
T
tinaun 已提交
246
    #[stable(feature = "duration_extras", since = "1.27.0")]
247
    #[inline]
M
Mark Rousskov 已提交
248
    #[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
249
    pub const fn from_nanos(nanos: u64) -> Duration {
250
        Duration {
N
Nathaniel Ringo 已提交
251 252 253
            secs: nanos / (NANOS_PER_SEC as u64),
            nanos: (nanos % (NANOS_PER_SEC as u64)) as u32,
        }
254 255
    }

256 257 258 259 260
    /// Returns true if this `Duration` spans no time.
    ///
    /// # Examples
    ///
    /// ```
J
Jon Gjengset 已提交
261
    /// #![feature(duration_zero)]
262 263
    /// use std::time::Duration;
    ///
J
Jubilee Young 已提交
264
    /// assert!(Duration::ZERO.is_zero());
265 266 267 268 269 270 271 272
    /// assert!(Duration::new(0, 0).is_zero());
    /// assert!(Duration::from_nanos(0).is_zero());
    /// assert!(Duration::from_secs(0).is_zero());
    ///
    /// assert!(!Duration::new(1, 1).is_zero());
    /// assert!(!Duration::from_nanos(1).is_zero());
    /// assert!(!Duration::from_secs(1).is_zero());
    /// ```
J
Jon Gjengset 已提交
273
    #[unstable(feature = "duration_zero", issue = "73544")]
274 275 276 277 278
    #[inline]
    pub const fn is_zero(&self) -> bool {
        self.secs == 0 && self.nanos == 0
    }

279
    /// Returns the number of _whole_ seconds contained by this `Duration`.
280
    ///
281 282
    /// The returned value does not include the fractional (nanosecond) part of the
    /// duration, which can be obtained using [`subsec_nanos`].
G
Guillaume Gomez 已提交
283 284 285 286 287 288
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    ///
289 290
    /// let duration = Duration::new(5, 730023852);
    /// assert_eq!(duration.as_secs(), 5);
G
Guillaume Gomez 已提交
291
    /// ```
292 293 294 295 296 297 298 299 300 301 302 303 304 305
    ///
    /// To determine the total number of seconds represented by the `Duration`,
    /// use `as_secs` in combination with [`subsec_nanos`]:
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// let duration = Duration::new(5, 730023852);
    ///
    /// assert_eq!(5.730023852,
    ///            duration.as_secs() as f64
    ///            + duration.subsec_nanos() as f64 * 1e-9);
    /// ```
    ///
D
Denis Vasilik 已提交
306
    /// [`subsec_nanos`]: Duration::subsec_nanos
S
Steven Fackler 已提交
307
    #[stable(feature = "duration", since = "1.3.0")]
M
Mark Rousskov 已提交
308
    #[rustc_const_stable(feature = "duration", since = "1.32.0")]
309
    #[inline]
D
David Tolnay 已提交
310 311 312
    pub const fn as_secs(&self) -> u64 {
        self.secs
    }
J
Jorge Aparicio 已提交
313

314
    /// Returns the fractional part of this `Duration`, in whole milliseconds.
315 316 317
    ///
    /// This method does **not** return the length of the duration when
    /// represented by milliseconds. The returned number always represents a
318
    /// fractional portion of a second (i.e., it is less than one thousand).
319 320 321 322 323 324 325 326
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// let duration = Duration::from_millis(5432);
    /// assert_eq!(duration.as_secs(), 5);
327
    /// assert_eq!(duration.subsec_millis(), 432);
328
    /// ```
T
tinaun 已提交
329
    #[stable(feature = "duration_extras", since = "1.27.0")]
M
Mark Rousskov 已提交
330
    #[rustc_const_stable(feature = "duration_extras", since = "1.32.0")]
331
    #[inline]
D
David Tolnay 已提交
332 333 334
    pub const fn subsec_millis(&self) -> u32 {
        self.nanos / NANOS_PER_MILLI
    }
335

336
    /// Returns the fractional part of this `Duration`, in whole microseconds.
337 338 339
    ///
    /// This method does **not** return the length of the duration when
    /// represented by microseconds. The returned number always represents a
340
    /// fractional portion of a second (i.e., it is less than one million).
341 342 343 344 345 346 347 348
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// let duration = Duration::from_micros(1_234_567);
    /// assert_eq!(duration.as_secs(), 1);
349
    /// assert_eq!(duration.subsec_micros(), 234_567);
350
    /// ```
T
tinaun 已提交
351
    #[stable(feature = "duration_extras", since = "1.27.0")]
M
Mark Rousskov 已提交
352
    #[rustc_const_stable(feature = "duration_extras", since = "1.32.0")]
353
    #[inline]
D
David Tolnay 已提交
354 355 356
    pub const fn subsec_micros(&self) -> u32 {
        self.nanos / NANOS_PER_MICRO
    }
357

358
    /// Returns the fractional part of this `Duration`, in nanoseconds.
359 360 361
    ///
    /// This method does **not** return the length of the duration when
    /// represented by nanoseconds. The returned number always represents a
362
    /// fractional portion of a second (i.e., it is less than one billion).
G
Guillaume Gomez 已提交
363 364 365 366 367 368 369
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// let duration = Duration::from_millis(5010);
370 371
    /// assert_eq!(duration.as_secs(), 5);
    /// assert_eq!(duration.subsec_nanos(), 10_000_000);
G
Guillaume Gomez 已提交
372
    /// ```
S
Steven Fackler 已提交
373
    #[stable(feature = "duration", since = "1.3.0")]
M
Mark Rousskov 已提交
374
    #[rustc_const_stable(feature = "duration", since = "1.32.0")]
375
    #[inline]
D
David Tolnay 已提交
376 377 378
    pub const fn subsec_nanos(&self) -> u32 {
        self.nanos
    }
379

380
    /// Returns the total number of whole milliseconds contained by this `Duration`.
381 382 383 384 385 386 387 388 389
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// let duration = Duration::new(5, 730023852);
    /// assert_eq!(duration.as_millis(), 5730);
    /// ```
S
Sunjay Varma 已提交
390
    #[stable(feature = "duration_as_u128", since = "1.33.0")]
M
Mark Rousskov 已提交
391
    #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
392
    #[inline]
M
Mazdak Farrokhzad 已提交
393
    pub const fn as_millis(&self) -> u128 {
394
        self.secs as u128 * MILLIS_PER_SEC as u128 + (self.nanos / NANOS_PER_MILLI) as u128
395 396
    }

397
    /// Returns the total number of whole microseconds contained by this `Duration`.
398 399 400 401 402 403 404 405 406
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// let duration = Duration::new(5, 730023852);
    /// assert_eq!(duration.as_micros(), 5730023);
    /// ```
S
Sunjay Varma 已提交
407
    #[stable(feature = "duration_as_u128", since = "1.33.0")]
M
Mark Rousskov 已提交
408
    #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
409
    #[inline]
M
Mazdak Farrokhzad 已提交
410
    pub const fn as_micros(&self) -> u128 {
411
        self.secs as u128 * MICROS_PER_SEC as u128 + (self.nanos / NANOS_PER_MICRO) as u128
412 413
    }

414 415 416 417 418 419 420 421 422 423
    /// Returns the total number of nanoseconds contained by this `Duration`.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// let duration = Duration::new(5, 730023852);
    /// assert_eq!(duration.as_nanos(), 5730023852);
    /// ```
S
Sunjay Varma 已提交
424
    #[stable(feature = "duration_as_u128", since = "1.33.0")]
M
Mark Rousskov 已提交
425
    #[rustc_const_stable(feature = "duration_as_u128", since = "1.33.0")]
426
    #[inline]
M
Mazdak Farrokhzad 已提交
427
    pub const fn as_nanos(&self) -> u128 {
J
Jonathan Behrens 已提交
428
        self.secs as u128 * NANOS_PER_SEC as u128 + self.nanos as u128
429 430
    }

G
Guillaume Gomez 已提交
431
    /// Checked `Duration` addition. Computes `self + other`, returning [`None`]
432 433 434 435 436 437 438
    /// if overflow occurred.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
E
Eugene Bulkin 已提交
439 440
    /// use std::time::Duration;
    ///
441
    /// assert_eq!(Duration::new(0, 0).checked_add(Duration::new(0, 1)), Some(Duration::new(0, 1)));
442
    /// assert_eq!(Duration::new(1, 0).checked_add(Duration::new(u64::MAX, 0)), None);
443
    /// ```
444
    #[stable(feature = "duration_checked_ops", since = "1.16.0")]
445
    #[inline]
446 447
    #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
    pub const fn checked_add(self, rhs: Duration) -> Option<Duration> {
448 449 450 451 452 453 454 455 456 457 458
        if let Some(mut secs) = self.secs.checked_add(rhs.secs) {
            let mut nanos = self.nanos + rhs.nanos;
            if nanos >= NANOS_PER_SEC {
                nanos -= NANOS_PER_SEC;
                if let Some(new_secs) = secs.checked_add(1) {
                    secs = new_secs;
                } else {
                    return None;
                }
            }
            debug_assert!(nanos < NANOS_PER_SEC);
D
David Tolnay 已提交
459
            Some(Duration { secs, nanos })
460 461 462 463 464
        } else {
            None
        }
    }

465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
    /// Saturating `Duration` addition. Computes `self + other`, returning [`Duration::MAX`]
    /// if overflow occurred.
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(duration_saturating_ops)]
    /// #![feature(duration_constants)]
    /// use std::time::Duration;
    ///
    /// assert_eq!(Duration::new(0, 0).saturating_add(Duration::new(0, 1)), Duration::new(0, 1));
    /// assert_eq!(Duration::new(1, 0).saturating_add(Duration::new(u64::MAX, 0)), Duration::MAX);
    /// ```
    #[unstable(feature = "duration_saturating_ops", issue = "76416")]
    #[inline]
    #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
    pub const fn saturating_add(self, rhs: Duration) -> Duration {
        match self.checked_add(rhs) {
            Some(res) => res,
            None => Duration::MAX,
        }
    }

G
Guillaume Gomez 已提交
488
    /// Checked `Duration` subtraction. Computes `self - other`, returning [`None`]
489
    /// if the result would be negative or if overflow occurred.
490 491 492 493 494 495
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
E
Eugene Bulkin 已提交
496 497
    /// use std::time::Duration;
    ///
498 499 500
    /// assert_eq!(Duration::new(0, 1).checked_sub(Duration::new(0, 0)), Some(Duration::new(0, 1)));
    /// assert_eq!(Duration::new(0, 0).checked_sub(Duration::new(0, 1)), None);
    /// ```
501
    #[stable(feature = "duration_checked_ops", since = "1.16.0")]
502
    #[inline]
503 504
    #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
    pub const fn checked_sub(self, rhs: Duration) -> Option<Duration> {
505 506 507 508 509 510 511 512 513 514 515 516
        if let Some(mut secs) = self.secs.checked_sub(rhs.secs) {
            let nanos = if self.nanos >= rhs.nanos {
                self.nanos - rhs.nanos
            } else {
                if let Some(sub_secs) = secs.checked_sub(1) {
                    secs = sub_secs;
                    self.nanos + NANOS_PER_SEC - rhs.nanos
                } else {
                    return None;
                }
            };
            debug_assert!(nanos < NANOS_PER_SEC);
L
ljedrz 已提交
517
            Some(Duration { secs, nanos })
518 519 520 521 522
        } else {
            None
        }
    }

J
Jubilee Young 已提交
523
    /// Saturating `Duration` subtraction. Computes `self - other`, returning [`Duration::ZERO`]
524 525 526 527 528 529
    /// if the result would be negative or if overflow occurred.
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(duration_saturating_ops)]
J
Jubilee Young 已提交
530
    /// #![feature(duration_zero)]
531 532 533
    /// use std::time::Duration;
    ///
    /// assert_eq!(Duration::new(0, 1).saturating_sub(Duration::new(0, 0)), Duration::new(0, 1));
J
Jubilee Young 已提交
534
    /// assert_eq!(Duration::new(0, 0).saturating_sub(Duration::new(0, 1)), Duration::ZERO);
535 536 537 538 539 540 541
    /// ```
    #[unstable(feature = "duration_saturating_ops", issue = "76416")]
    #[inline]
    #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
    pub const fn saturating_sub(self, rhs: Duration) -> Duration {
        match self.checked_sub(rhs) {
            Some(res) => res,
J
Jubilee Young 已提交
542
            None => Duration::ZERO,
543 544 545
        }
    }

G
Guillaume Gomez 已提交
546 547 548
    /// Checked `Duration` multiplication. Computes `self * other`, returning
    /// [`None`] if overflow occurred.
    ///
549 550 551 552 553
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
E
Eugene Bulkin 已提交
554 555
    /// use std::time::Duration;
    ///
556
    /// assert_eq!(Duration::new(0, 500_000_001).checked_mul(2), Some(Duration::new(1, 2)));
557
    /// assert_eq!(Duration::new(u64::MAX - 1, 0).checked_mul(2), None);
558
    /// ```
559
    #[stable(feature = "duration_checked_ops", since = "1.16.0")]
560
    #[inline]
561 562
    #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
    pub const fn checked_mul(self, rhs: u32) -> Option<Duration> {
563 564 565 566
        // Multiply nanoseconds as u64, because it cannot overflow that way.
        let total_nanos = self.nanos as u64 * rhs as u64;
        let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
        let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
567 568 569 570 571
        if let Some(s) = self.secs.checked_mul(rhs as u64) {
            if let Some(secs) = s.checked_add(extra_secs) {
                debug_assert!(nanos < NANOS_PER_SEC);
                return Some(Duration { secs, nanos });
            }
572
        }
573
        None
574 575
    }

576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
    /// Saturating `Duration` multiplication. Computes `self * other`, returning
    /// [`Duration::MAX`] if overflow occurred.
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(duration_saturating_ops)]
    /// #![feature(duration_constants)]
    /// use std::time::Duration;
    ///
    /// assert_eq!(Duration::new(0, 500_000_001).saturating_mul(2), Duration::new(1, 2));
    /// assert_eq!(Duration::new(u64::MAX - 1, 0).saturating_mul(2), Duration::MAX);
    /// ```
    #[unstable(feature = "duration_saturating_ops", issue = "76416")]
    #[inline]
    #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
    pub const fn saturating_mul(self, rhs: u32) -> Duration {
        match self.checked_mul(rhs) {
            Some(res) => res,
            None => Duration::MAX,
        }
    }

G
Guillaume Gomez 已提交
599 600 601
    /// Checked `Duration` division. Computes `self / other`, returning [`None`]
    /// if `other == 0`.
    ///
602 603 604 605 606
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
E
Eugene Bulkin 已提交
607 608
    /// use std::time::Duration;
    ///
609 610 611 612
    /// assert_eq!(Duration::new(2, 0).checked_div(2), Some(Duration::new(1, 0)));
    /// assert_eq!(Duration::new(1, 0).checked_div(2), Some(Duration::new(0, 500_000_000)));
    /// assert_eq!(Duration::new(2, 0).checked_div(0), None);
    /// ```
613
    #[stable(feature = "duration_checked_ops", since = "1.16.0")]
614
    #[inline]
615 616
    #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
    pub const fn checked_div(self, rhs: u32) -> Option<Duration> {
617 618 619 620 621 622
        if rhs != 0 {
            let secs = self.secs / (rhs as u64);
            let carry = self.secs - secs * (rhs as u64);
            let extra_nanos = carry * (NANOS_PER_SEC as u64) / (rhs as u64);
            let nanos = self.nanos / rhs + (extra_nanos as u32);
            debug_assert!(nanos < NANOS_PER_SEC);
L
ljedrz 已提交
623
            Some(Duration { secs, nanos })
624 625 626 627
        } else {
            None
        }
    }
A
Artyom Pavlov 已提交
628

629 630 631 632 633 634 635 636 637
    /// Returns the number of seconds contained by this `Duration` as `f64`.
    ///
    /// The returned value does include the fractional (nanosecond) part of the duration.
    ///
    /// # Examples
    /// ```
    /// use std::time::Duration;
    ///
    /// let dur = Duration::new(2, 700_000_000);
638
    /// assert_eq!(dur.as_secs_f64(), 2.7);
639
    /// ```
N
newpavlov 已提交
640
    #[stable(feature = "duration_float", since = "1.38.0")]
641
    #[inline]
642 643
    #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
    pub const fn as_secs_f64(&self) -> f64 {
644 645
        (self.secs as f64) + (self.nanos as f64) / (NANOS_PER_SEC as f64)
    }
646

647 648 649 650 651 652 653 654 655 656 657
    /// Returns the number of seconds contained by this `Duration` as `f32`.
    ///
    /// The returned value does include the fractional (nanosecond) part of the duration.
    ///
    /// # Examples
    /// ```
    /// use std::time::Duration;
    ///
    /// let dur = Duration::new(2, 700_000_000);
    /// assert_eq!(dur.as_secs_f32(), 2.7);
    /// ```
N
newpavlov 已提交
658
    #[stable(feature = "duration_float", since = "1.38.0")]
659
    #[inline]
660 661
    #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
    pub const fn as_secs_f32(&self) -> f32 {
662 663 664 665 666
        (self.secs as f32) + (self.nanos as f32) / (NANOS_PER_SEC as f32)
    }

    /// Creates a new `Duration` from the specified number of seconds represented
    /// as `f64`.
667
    ///
668 669 670
    /// # Panics
    /// This constructor will panic if `secs` is not finite, negative or overflows `Duration`.
    ///
671 672 673 674
    /// # Examples
    /// ```
    /// use std::time::Duration;
    ///
675
    /// let dur = Duration::from_secs_f64(2.7);
676 677
    /// assert_eq!(dur, Duration::new(2, 700_000_000));
    /// ```
N
newpavlov 已提交
678
    #[stable(feature = "duration_float", since = "1.38.0")]
679
    #[inline]
680 681
    #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
    pub const fn from_secs_f64(secs: f64) -> Duration {
D
David Tolnay 已提交
682 683
        const MAX_NANOS_F64: f64 = ((u64::MAX as u128 + 1) * (NANOS_PER_SEC as u128)) as f64;
        let nanos = secs * (NANOS_PER_SEC as f64);
A
Artyom Pavlov 已提交
684 685 686
        if !nanos.is_finite() {
            panic!("got non-finite value when converting float to duration");
        }
687
        if nanos >= MAX_NANOS_F64 {
A
Artyom Pavlov 已提交
688 689 690 691 692
            panic!("overflow when converting float to duration");
        }
        if nanos < 0.0 {
            panic!("underflow when converting float to duration");
        }
D
David Tolnay 已提交
693
        let nanos = nanos as u128;
694 695 696 697 698
        Duration {
            secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
            nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
        }
    }
A
Artyom Pavlov 已提交
699

700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
    /// The checked version of [`from_secs_f64`].
    ///
    /// [`from_secs_f64`]: Duration::from_secs_f64
    ///
    /// This constructor will return an `Err` if `secs` is not finite, negative or overflows `Duration`.
    ///
    /// # Examples
    /// ```
    /// #![feature(duration_checked_float)]
    ///
    /// use std::time::Duration;
    ///
    /// let dur = Duration::try_from_secs_f64(2.7);
    /// assert_eq!(dur, Ok(Duration::new(2, 700_000_000)));
    ///
    /// let negative = Duration::try_from_secs_f64(-5.0);
    /// assert!(negative.is_err());
    /// ```
    #[unstable(feature = "duration_checked_float", issue = "83400")]
    #[inline]
    pub const fn try_from_secs_f64(secs: f64) -> Result<Duration, FromSecsError> {
        const MAX_NANOS_F64: f64 = ((u64::MAX as u128 + 1) * (NANOS_PER_SEC as u128)) as f64;
        let nanos = secs * (NANOS_PER_SEC as f64);
        if !nanos.is_finite() {
            Err(FromSecsError { kind: FromSecsErrorKind::NonFinite })
        } else if nanos >= MAX_NANOS_F64 {
            Err(FromSecsError { kind: FromSecsErrorKind::Overflow })
        } else if nanos < 0.0 {
            Err(FromSecsError { kind: FromSecsErrorKind::Underflow })
        } else {
            let nanos = nanos as u128;
            Ok(Duration {
                secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
                nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
            })
        }
    }

738 739 740 741 742 743 744 745 746 747 748 749 750
    /// Creates a new `Duration` from the specified number of seconds represented
    /// as `f32`.
    ///
    /// # Panics
    /// This constructor will panic if `secs` is not finite, negative or overflows `Duration`.
    ///
    /// # Examples
    /// ```
    /// use std::time::Duration;
    ///
    /// let dur = Duration::from_secs_f32(2.7);
    /// assert_eq!(dur, Duration::new(2, 700_000_000));
    /// ```
N
newpavlov 已提交
751
    #[stable(feature = "duration_float", since = "1.38.0")]
752
    #[inline]
753 754
    #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
    pub const fn from_secs_f32(secs: f32) -> Duration {
D
David Tolnay 已提交
755 756
        const MAX_NANOS_F32: f32 = ((u64::MAX as u128 + 1) * (NANOS_PER_SEC as u128)) as f32;
        let nanos = secs * (NANOS_PER_SEC as f32);
757 758 759 760 761 762 763 764 765
        if !nanos.is_finite() {
            panic!("got non-finite value when converting float to duration");
        }
        if nanos >= MAX_NANOS_F32 {
            panic!("overflow when converting float to duration");
        }
        if nanos < 0.0 {
            panic!("underflow when converting float to duration");
        }
D
David Tolnay 已提交
766
        let nanos = nanos as u128;
767 768 769 770 771 772
        Duration {
            secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
            nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
        }
    }

773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
    /// The checked version of [`from_secs_f32`].
    ///
    /// [`from_secs_f32`]: Duration::from_secs_f32
    ///
    /// This constructor will return an `Err` if `secs` is not finite, negative or overflows `Duration`.
    ///
    /// # Examples
    /// ```
    /// #![feature(duration_checked_float)]
    ///
    /// use std::time::Duration;
    ///
    /// let dur = Duration::try_from_secs_f32(2.7);
    /// assert_eq!(dur, Ok(Duration::new(2, 700_000_000)));
    ///
    /// let negative = Duration::try_from_secs_f32(-5.0);
    /// assert!(negative.is_err());
    /// ```
    #[unstable(feature = "duration_checked_float", issue = "83400")]
    #[inline]
    pub const fn try_from_secs_f32(secs: f32) -> Result<Duration, FromSecsError> {
        const MAX_NANOS_F32: f32 = ((u64::MAX as u128 + 1) * (NANOS_PER_SEC as u128)) as f32;
        let nanos = secs * (NANOS_PER_SEC as f32);
        if !nanos.is_finite() {
            Err(FromSecsError { kind: FromSecsErrorKind::NonFinite })
        } else if nanos >= MAX_NANOS_F32 {
            Err(FromSecsError { kind: FromSecsErrorKind::Overflow })
        } else if nanos < 0.0 {
            Err(FromSecsError { kind: FromSecsErrorKind::Underflow })
        } else {
            let nanos = nanos as u128;
            Ok(Duration {
                secs: (nanos / (NANOS_PER_SEC as u128)) as u64,
                nanos: (nanos % (NANOS_PER_SEC as u128)) as u32,
            })
        }
    }

A
Alexander Regueiro 已提交
811
    /// Multiplies `Duration` by `f64`.
812
    ///
813 814 815
    /// # Panics
    /// This method will panic if result is not finite, negative or overflows `Duration`.
    ///
816 817
    /// # Examples
    /// ```
A
Artyom Pavlov 已提交
818 819
    /// use std::time::Duration;
    ///
820 821 822 823
    /// let dur = Duration::new(2, 700_000_000);
    /// assert_eq!(dur.mul_f64(3.14), Duration::new(8, 478_000_000));
    /// assert_eq!(dur.mul_f64(3.14e5), Duration::new(847_800, 0));
    /// ```
N
newpavlov 已提交
824
    #[stable(feature = "duration_float", since = "1.38.0")]
825
    #[inline]
826 827
    #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
    pub const fn mul_f64(self, rhs: f64) -> Duration {
828 829 830 831 832 833 834 835 836 837 838 839 840
        Duration::from_secs_f64(rhs * self.as_secs_f64())
    }

    /// Multiplies `Duration` by `f32`.
    ///
    /// # Panics
    /// This method will panic if result is not finite, negative or overflows `Duration`.
    ///
    /// # Examples
    /// ```
    /// use std::time::Duration;
    ///
    /// let dur = Duration::new(2, 700_000_000);
N
newpavlov 已提交
841
    /// // note that due to rounding errors result is slightly different
A
Artyom Pavlov 已提交
842
    /// // from 8.478 and 847800.0
N
newpavlov 已提交
843
    /// assert_eq!(dur.mul_f32(3.14), Duration::new(8, 478_000_640));
A
Artyom Pavlov 已提交
844
    /// assert_eq!(dur.mul_f32(3.14e5), Duration::new(847799, 969_120_256));
845
    /// ```
N
newpavlov 已提交
846
    #[stable(feature = "duration_float", since = "1.38.0")]
847
    #[inline]
848 849
    #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
    pub const fn mul_f32(self, rhs: f32) -> Duration {
850
        Duration::from_secs_f32(rhs * self.as_secs_f32())
851 852 853 854
    }

    /// Divide `Duration` by `f64`.
    ///
855 856 857
    /// # Panics
    /// This method will panic if result is not finite, negative or overflows `Duration`.
    ///
858 859
    /// # Examples
    /// ```
A
Artyom Pavlov 已提交
860 861
    /// use std::time::Duration;
    ///
862 863 864 865 866
    /// let dur = Duration::new(2, 700_000_000);
    /// assert_eq!(dur.div_f64(3.14), Duration::new(0, 859_872_611));
    /// // note that truncation is used, not rounding
    /// assert_eq!(dur.div_f64(3.14e5), Duration::new(0, 8_598));
    /// ```
N
newpavlov 已提交
867
    #[stable(feature = "duration_float", since = "1.38.0")]
868
    #[inline]
869 870
    #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
    pub const fn div_f64(self, rhs: f64) -> Duration {
871 872 873 874 875 876 877 878 879 880 881 882 883
        Duration::from_secs_f64(self.as_secs_f64() / rhs)
    }

    /// Divide `Duration` by `f32`.
    ///
    /// # Panics
    /// This method will panic if result is not finite, negative or overflows `Duration`.
    ///
    /// # Examples
    /// ```
    /// use std::time::Duration;
    ///
    /// let dur = Duration::new(2, 700_000_000);
N
newpavlov 已提交
884 885 886
    /// // note that due to rounding errors result is slightly
    /// // different from 0.859_872_611
    /// assert_eq!(dur.div_f32(3.14), Duration::new(0, 859_872_576));
887 888 889
    /// // note that truncation is used, not rounding
    /// assert_eq!(dur.div_f32(3.14e5), Duration::new(0, 8_598));
    /// ```
N
newpavlov 已提交
890
    #[stable(feature = "duration_float", since = "1.38.0")]
891
    #[inline]
892 893
    #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
    pub const fn div_f32(self, rhs: f32) -> Duration {
894
        Duration::from_secs_f32(self.as_secs_f32() / rhs)
895 896 897 898 899 900
    }

    /// Divide `Duration` by `Duration` and return `f64`.
    ///
    /// # Examples
    /// ```
A
Artyom Pavlov 已提交
901
    /// #![feature(div_duration)]
A
Artyom Pavlov 已提交
902 903
    /// use std::time::Duration;
    ///
904 905
    /// let dur1 = Duration::new(2, 700_000_000);
    /// let dur2 = Duration::new(5, 400_000_000);
N
newpavlov 已提交
906
    /// assert_eq!(dur1.div_duration_f64(dur2), 0.5);
907
    /// ```
908
    #[unstable(feature = "div_duration", issue = "63139")]
909
    #[inline]
910 911
    #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
    pub const fn div_duration_f64(self, rhs: Duration) -> f64 {
912 913 914 915 916 917 918
        self.as_secs_f64() / rhs.as_secs_f64()
    }

    /// Divide `Duration` by `Duration` and return `f32`.
    ///
    /// # Examples
    /// ```
A
Artyom Pavlov 已提交
919
    /// #![feature(div_duration)]
920 921 922 923
    /// use std::time::Duration;
    ///
    /// let dur1 = Duration::new(2, 700_000_000);
    /// let dur2 = Duration::new(5, 400_000_000);
N
newpavlov 已提交
924
    /// assert_eq!(dur1.div_duration_f32(dur2), 0.5);
925
    /// ```
926
    #[unstable(feature = "div_duration", issue = "63139")]
927
    #[inline]
928 929
    #[rustc_const_unstable(feature = "duration_consts_2", issue = "72440")]
    pub const fn div_duration_f32(self, rhs: Duration) -> f32 {
930
        self.as_secs_f32() / rhs.as_secs_f32()
931
    }
932 933
}

934
#[stable(feature = "duration", since = "1.3.0")]
J
Jorge Aparicio 已提交
935 936 937
impl Add for Duration {
    type Output = Duration;

938
    fn add(self, rhs: Duration) -> Duration {
939
        self.checked_add(rhs).expect("overflow when adding durations")
940 941 942
    }
}

943 944 945 946 947 948 949
#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
impl AddAssign for Duration {
    fn add_assign(&mut self, rhs: Duration) {
        *self = *self + rhs;
    }
}

950
#[stable(feature = "duration", since = "1.3.0")]
J
Jorge Aparicio 已提交
951 952 953
impl Sub for Duration {
    type Output = Duration;

954
    fn sub(self, rhs: Duration) -> Duration {
955
        self.checked_sub(rhs).expect("overflow when subtracting durations")
956 957 958
    }
}

959 960 961 962 963 964 965
#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
impl SubAssign for Duration {
    fn sub_assign(&mut self, rhs: Duration) {
        *self = *self - rhs;
    }
}

966
#[stable(feature = "duration", since = "1.3.0")]
967
impl Mul<u32> for Duration {
J
Jorge Aparicio 已提交
968 969
    type Output = Duration;

970
    fn mul(self, rhs: u32) -> Duration {
971
        self.checked_mul(rhs).expect("overflow when multiplying duration by scalar")
972 973 974
    }
}

975
#[stable(feature = "symmetric_u32_duration_mul", since = "1.31.0")]
976 977 978 979
impl Mul<Duration> for u32 {
    type Output = Duration;

    fn mul(self, rhs: Duration) -> Duration {
A
Artyom Pavlov 已提交
980
        rhs * self
981
    }
982 983
}

984 985 986 987 988 989 990
#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
impl MulAssign<u32> for Duration {
    fn mul_assign(&mut self, rhs: u32) {
        *self = *self * rhs;
    }
}

991
#[stable(feature = "duration", since = "1.3.0")]
992
impl Div<u32> for Duration {
J
Jorge Aparicio 已提交
993 994
    type Output = Duration;

995
    fn div(self, rhs: u32) -> Duration {
996
        self.checked_div(rhs).expect("divide by zero error when dividing duration by scalar")
B
Brian Anderson 已提交
997 998 999
    }
}

1000 1001 1002 1003 1004 1005 1006
#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
impl DivAssign<u32> for Duration {
    fn div_assign(&mut self, rhs: u32) {
        *self = *self / rhs;
    }
}

1007 1008 1009 1010 1011 1012
macro_rules! sum_durations {
    ($iter:expr) => {{
        let mut total_secs: u64 = 0;
        let mut total_nanos: u64 = 0;

        for entry in $iter {
D
David Tolnay 已提交
1013 1014
            total_secs =
                total_secs.checked_add(entry.secs).expect("overflow in iter::sum over durations");
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
            total_nanos = match total_nanos.checked_add(entry.nanos as u64) {
                Some(n) => n,
                None => {
                    total_secs = total_secs
                        .checked_add(total_nanos / NANOS_PER_SEC as u64)
                        .expect("overflow in iter::sum over durations");
                    (total_nanos % NANOS_PER_SEC as u64) + entry.nanos as u64
                }
            };
        }
        total_secs = total_secs
            .checked_add(total_nanos / NANOS_PER_SEC as u64)
            .expect("overflow in iter::sum over durations");
        total_nanos = total_nanos % NANOS_PER_SEC as u64;
D
David Tolnay 已提交
1029
        Duration { secs: total_secs, nanos: total_nanos as u32 }
1030 1031 1032
    }};
}

C
Clar Charr 已提交
1033 1034
#[stable(feature = "duration_sum", since = "1.16.0")]
impl Sum for Duration {
D
David Tolnay 已提交
1035
    fn sum<I: Iterator<Item = Duration>>(iter: I) -> Duration {
1036
        sum_durations!(iter)
C
Clar Charr 已提交
1037 1038 1039 1040 1041
    }
}

#[stable(feature = "duration_sum", since = "1.16.0")]
impl<'a> Sum<&'a Duration> for Duration {
D
David Tolnay 已提交
1042
    fn sum<I: Iterator<Item = &'a Duration>>(iter: I) -> Duration {
1043
        sum_durations!(iter)
C
Clar Charr 已提交
1044 1045
    }
}
1046 1047 1048

#[stable(feature = "duration_debug_impl", since = "1.27.0")]
impl fmt::Debug for Duration {
M
Mazdak Farrokhzad 已提交
1049
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
        /// Formats a floating point number in decimal notation.
        ///
        /// The number is given as the `integer_part` and a fractional part.
        /// The value of the fractional part is `fractional_part / divisor`. So
        /// `integer_part` = 3, `fractional_part` = 12 and `divisor` = 100
        /// represents the number `3.012`. Trailing zeros are omitted.
        ///
        /// `divisor` must not be above 100_000_000. It also should be a power
        /// of 10, everything else doesn't make sense. `fractional_part` has
        /// to be less than `10 * divisor`!
        fn fmt_decimal(
M
Mazdak Farrokhzad 已提交
1061
            f: &mut fmt::Formatter<'_>,
1062
            mut integer_part: u64,
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
            mut fractional_part: u32,
            mut divisor: u32,
        ) -> fmt::Result {
            // Encode the fractional part into a temporary buffer. The buffer
            // only need to hold 9 elements, because `fractional_part` has to
            // be smaller than 10^9. The buffer is prefilled with '0' digits
            // to simplify the code below.
            let mut buf = [b'0'; 9];

            // The next digit is written at this position
            let mut pos = 0;

1075 1076 1077
            // We keep writing digits into the buffer while there are non-zero
            // digits left and we haven't written enough digits yet.
            while fractional_part > 0 && pos < f.precision().unwrap_or(9) {
1078 1079 1080 1081 1082 1083 1084 1085
                // Write new digit into the buffer
                buf[pos] = b'0' + (fractional_part / divisor) as u8;

                fractional_part %= divisor;
                divisor /= 10;
                pos += 1;
            }

1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
            // If a precision < 9 was specified, there may be some non-zero
            // digits left that weren't written into the buffer. In that case we
            // need to perform rounding to match the semantics of printing
            // normal floating point numbers. However, we only need to do work
            // when rounding up. This happens if the first digit of the
            // remaining ones is >= 5.
            if fractional_part > 0 && fractional_part >= divisor * 5 {
                // Round up the number contained in the buffer. We go through
                // the buffer backwards and keep track of the carry.
                let mut rev_pos = pos;
                let mut carry = true;
                while carry && rev_pos > 0 {
                    rev_pos -= 1;

                    // If the digit in the buffer is not '9', we just need to
                    // increment it and can stop then (since we don't have a
                    // carry anymore). Otherwise, we set it to '0' (overflow)
                    // and continue.
                    if buf[rev_pos] < b'9' {
                        buf[rev_pos] += 1;
                        carry = false;
                    } else {
                        buf[rev_pos] = b'0';
                    }
                }

                // If we still have the carry bit set, that means that we set
                // the whole buffer to '0's and need to increment the integer
                // part.
                if carry {
                    integer_part += 1;
                }
            }

1120 1121 1122
            // Determine the end of the buffer: if precision is set, we just
            // use as many digits from the buffer (capped to 9). If it isn't
            // set, we only use all digits up to the last non-zero one.
T
Taiki Endo 已提交
1123
            let end = f.precision().map(|p| crate::cmp::min(p, 9)).unwrap_or(pos);
1124

1125 1126 1127 1128 1129
            // If we haven't emitted a single fractional digit and the precision
            // wasn't set to a non-zero value, we don't print the decimal point.
            if end == 0 {
                write!(f, "{}", integer_part)
            } else {
1130
                // SAFETY: We are only writing ASCII digits into the buffer and it was
1131
                // initialized with '0's, so it contains valid UTF8.
D
David Tolnay 已提交
1132
                let s = unsafe { crate::str::from_utf8_unchecked(&buf[..end]) };
1133

1134 1135 1136
                // If the user request a precision > 9, we pad '0's at the end.
                let w = f.precision().unwrap_or(pos);
                write!(f, "{}.{:0<width$}", integer_part, s, width = w)
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
            }
        }

        // Print leading '+' sign if requested
        if f.sign_plus() {
            write!(f, "+")?;
        }

        if self.secs > 0 {
            fmt_decimal(f, self.secs, self.nanos, 100_000_000)?;
            f.write_str("s")
        } else if self.nanos >= 1_000_000 {
            fmt_decimal(f, self.nanos as u64 / 1_000_000, self.nanos % 1_000_000, 100_000)?;
            f.write_str("ms")
        } else if self.nanos >= 1_000 {
            fmt_decimal(f, self.nanos as u64 / 1_000, self.nanos % 1_000, 100)?;
            f.write_str("µs")
        } else {
1155 1156
            fmt_decimal(f, self.nanos as u64, 0, 1)?;
            f.write_str("ns")
1157 1158 1159
        }
    }
}
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211

/// An error which can be returned when converting a floating-point value of seconds
/// into a [`Duration`].
///
/// This error is used as the error type for [`Duration::try_from_secs_f32`] and
/// [`Duration::try_from_secs_f64`].
///
/// # Example
///
/// ```
/// #![feature(duration_checked_float)]
///
/// use std::time::Duration;
///
/// if let Err(e) = Duration::try_from_secs_f32(-1.0) {
///     println!("Failed conversion to Duration: {}", e);
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[unstable(feature = "duration_checked_float", issue = "83400")]
pub struct FromSecsError {
    kind: FromSecsErrorKind,
}

impl FromSecsError {
    const fn description(&self) -> &'static str {
        match self.kind {
            FromSecsErrorKind::NonFinite => {
                "got non-finite value when converting float to duration"
            }
            FromSecsErrorKind::Overflow => "overflow when converting float to duration",
            FromSecsErrorKind::Underflow => "underflow when converting float to duration",
        }
    }
}

#[unstable(feature = "duration_checked_float", issue = "83400")]
impl fmt::Display for FromSecsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self.description(), f)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum FromSecsErrorKind {
    // Value is not a finite value (either infinity or NaN).
    NonFinite,
    // Value is too large to store in a `Duration`.
    Overflow,
    // Value is less than `0.0`.
    Underflow,
}