Skip to content

Commit 8a850cd

Browse files
std/time: avoid divisions in Duration::new
1 parent f6ee4bf commit 8a850cd

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

library/core/src/time.rs

+12-7
Original file line numberDiff line numberDiff line change
@@ -197,13 +197,18 @@ impl Duration {
197197
#[must_use]
198198
#[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")]
199199
pub const fn new(secs: u64, nanos: u32) -> Duration {
200-
let secs = match secs.checked_add((nanos / NANOS_PER_SEC) as u64) {
201-
Some(secs) => secs,
202-
None => panic!("overflow in Duration::new"),
203-
};
204-
let nanos = nanos % NANOS_PER_SEC;
205-
// SAFETY: nanos % NANOS_PER_SEC < NANOS_PER_SEC, therefore nanos is within the valid range
206-
Duration { secs, nanos: unsafe { Nanoseconds(nanos) } }
200+
if nanos < NANOS_PER_SEC {
201+
// SAFETY: nanos < NANOS_PER_SEC, therefore nanos is within the valid range
202+
Duration { secs, nanos: unsafe { Nanoseconds(nanos) } }
203+
} else {
204+
let secs = match secs.checked_add((nanos / NANOS_PER_SEC) as u64) {
205+
Some(secs) => secs,
206+
None => panic!("overflow in Duration::new"),
207+
};
208+
let nanos = nanos % NANOS_PER_SEC;
209+
// SAFETY: nanos % NANOS_PER_SEC < NANOS_PER_SEC, therefore nanos is within the valid range
210+
Duration { secs, nanos: unsafe { Nanoseconds(nanos) } }
211+
}
207212
}
208213

209214
/// Creates a new `Duration` from the specified number of whole seconds.

0 commit comments

Comments
 (0)