mirror of
https://github.com/rust-lang/rust.git
synced 2025-05-09 16:37:36 +00:00
std/time: avoid divisions in Duration::new
This commit is contained in:
parent
f6ee4bf384
commit
8a850cd12b
@ -197,13 +197,18 @@ impl Duration {
|
|||||||
#[must_use]
|
#[must_use]
|
||||||
#[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
|
#[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
|
||||||
pub const fn new(secs: u64, nanos: u32) -> Duration {
|
pub const fn new(secs: u64, nanos: u32) -> Duration {
|
||||||
let secs = match secs.checked_add((nanos / NANOS_PER_SEC) as u64) {
|
if nanos < NANOS_PER_SEC {
|
||||||
Some(secs) => secs,
|
// SAFETY: nanos < NANOS_PER_SEC, therefore nanos is within the valid range
|
||||||
None => panic!("overflow in Duration::new"),
|
Duration { secs, nanos: unsafe { Nanoseconds(nanos) } }
|
||||||
};
|
} else {
|
||||||
let nanos = nanos % NANOS_PER_SEC;
|
let secs = match secs.checked_add((nanos / NANOS_PER_SEC) as u64) {
|
||||||
// SAFETY: nanos % NANOS_PER_SEC < NANOS_PER_SEC, therefore nanos is within the valid range
|
Some(secs) => secs,
|
||||||
Duration { secs, nanos: unsafe { Nanoseconds(nanos) } }
|
None => panic!("overflow in Duration::new"),
|
||||||
|
};
|
||||||
|
let nanos = nanos % NANOS_PER_SEC;
|
||||||
|
// SAFETY: nanos % NANOS_PER_SEC < NANOS_PER_SEC, therefore nanos is within the valid range
|
||||||
|
Duration { secs, nanos: unsafe { Nanoseconds(nanos) } }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Creates a new `Duration` from the specified number of whole seconds.
|
/// Creates a new `Duration` from the specified number of whole seconds.
|
||||||
|
Loading…
Reference in New Issue
Block a user