Skip to content

Commit 00773f8

Browse files
Add from_nanos_u128 to Duration for handling large time spans
1 parent 8c35f4a commit 00773f8

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

library/core/src/time.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,29 @@ impl Duration {
308308
Duration { secs, nanos: subsec_nanos }
309309
}
310310

311+
312+
/// creates a new Duration from the specified number of nano seconds.
313+
/// Use this function if you need to specify time greater than what can fit in u64
314+
/// which is around 584 years and above 584.94 years to be a little more precise.
315+
///
316+
/// # Examples
317+
///
318+
/// ```
319+
/// use std::time::Duration;
320+
/// let time_in_nanos = 2.pow(64);
321+
/// let duration = Duration::from_nanos_u128(time_in_nanos);
322+
///
323+
/// ```
324+
pub const fn from_nanos_u128(nanos: u128) -> Duration {
325+
const NANOS_PER_SEC: u128 = self::NANOS_PER_SEC as u128;
326+
let secs = nanos / NANOS_PER_SEC;
327+
let subsec_nanos = (nanos % NANOS_PER_SEC) as u32;
328+
// SAFETY: x % 1_000_000_000 < 1_000_000_000
329+
let subsec_nanos = unsafe { Nanoseconds::new_unchecked(subsec_nanos) };
330+
331+
Duration { secs, nanos: subsec_nanos }
332+
}
333+
311334
/// Creates a new `Duration` from the specified number of weeks.
312335
///
313336
/// # Panics

0 commit comments

Comments
 (0)