diff options
| author | Utkarsh Gupta <utkarshgupta137@gmail.com> | 2024-01-24 11:10:07 +0000 | 
|---|---|---|
| committer | Utkarsh Gupta <utkarshgupta137@gmail.com> | 2024-01-24 11:10:14 +0000 | 
| commit | 8a850cd12b51507c8a7455c973e54eb14c51696e (patch) | |
| tree | 9e5080776c7ed550903c80b69f5edfa691b9d2ab | |
| parent | f6ee4bf3847277d6d6e2007ff664f8ea0895b11b (diff) | |
| download | rust-8a850cd12b51507c8a7455c973e54eb14c51696e.tar.gz rust-8a850cd12b51507c8a7455c973e54eb14c51696e.zip  | |
std/time: avoid divisions in Duration::new
| -rw-r--r-- | library/core/src/time.rs | 19 | 
1 files changed, 12 insertions, 7 deletions
diff --git a/library/core/src/time.rs b/library/core/src/time.rs index b677776443f..e4f29942966 100644 --- a/library/core/src/time.rs +++ b/library/core/src/time.rs @@ -197,13 +197,18 @@ impl Duration { #[must_use] #[rustc_const_stable(feature = "duration_consts_2", since = "1.58.0")] 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"), - }; - 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) } } + if nanos < NANOS_PER_SEC { + // SAFETY: nanos < NANOS_PER_SEC, therefore nanos is within the valid range + Duration { secs, nanos: unsafe { Nanoseconds(nanos) } } + } else { + let secs = match secs.checked_add((nanos / NANOS_PER_SEC) as u64) { + Some(secs) => secs, + 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.  | 
