Skip to content

Commit 65de37a

Browse files
committed
Inline Duration construction into Duration::from_{millis,micros,nanos}
1 parent e703bb1 commit 65de37a

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

core/src/time.rs

+21-3
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,13 @@ impl Duration {
260260
#[inline]
261261
#[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
262262
pub const fn from_millis(millis: u64) -> Duration {
263-
Duration::new(millis / MILLIS_PER_SEC, ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI)
263+
let secs = millis / MILLIS_PER_SEC;
264+
let subsec_millis = (millis % MILLIS_PER_SEC) as u32;
265+
// SAFETY: (x % 1_000) * 1_000_000 < 1_000_000_000
266+
// => x % 1_000 < 1_000
267+
let subsec_nanos = unsafe { Nanoseconds(subsec_millis * NANOS_PER_MILLI) };
268+
269+
Duration { secs, nanos: subsec_nanos }
264270
}
265271

266272
/// Creates a new `Duration` from the specified number of microseconds.
@@ -280,7 +286,13 @@ impl Duration {
280286
#[inline]
281287
#[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
282288
pub const fn from_micros(micros: u64) -> Duration {
283-
Duration::new(micros / MICROS_PER_SEC, ((micros % MICROS_PER_SEC) as u32) * NANOS_PER_MICRO)
289+
let secs = micros / MICROS_PER_SEC;
290+
let subsec_micros = (micros % MICROS_PER_SEC) as u32;
291+
// SAFETY: (x % 1_000_000) * 1_000 < 1_000_000_000
292+
// => x % 1_000_000 < 1_000_000
293+
let subsec_nanos = unsafe { Nanoseconds(subsec_micros * NANOS_PER_MICRO) };
294+
295+
Duration { secs, nanos: subsec_nanos }
284296
}
285297

286298
/// Creates a new `Duration` from the specified number of nanoseconds.
@@ -305,7 +317,13 @@ impl Duration {
305317
#[inline]
306318
#[rustc_const_stable(feature = "duration_consts", since = "1.32.0")]
307319
pub const fn from_nanos(nanos: u64) -> Duration {
308-
Duration::new(nanos / (NANOS_PER_SEC as u64), (nanos % (NANOS_PER_SEC as u64)) as u32)
320+
const NANOS_PER_SEC: u64 = self::NANOS_PER_SEC as u64;
321+
let secs = nanos / NANOS_PER_SEC;
322+
let subsec_nanos = (nanos % NANOS_PER_SEC) as u32;
323+
// SAFETY: x % 1_000_000_000 < 1_000_000_000
324+
let subsec_nanos = unsafe { Nanoseconds(subsec_nanos) };
325+
326+
Duration { secs, nanos: subsec_nanos }
309327
}
310328

311329
/// Creates a new `Duration` from the specified number of weeks.

0 commit comments

Comments
 (0)