Skip to content

Commit 7f6707b

Browse files
Merge branch 'duration-from-nanos-u128' of https://github.com/omanirudh/rust into nanos
2 parents 5ae50d3 + ee10071 commit 7f6707b

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

library/core/src/time.rs

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
#![stable(feature = "duration_core", since = "1.25.0")]
2-
32
//! Temporal quantification.
43
//!
54
//! # Examples:
@@ -308,6 +307,39 @@ impl Duration {
308307
Duration { secs, nanos: subsec_nanos }
309308
}
310309

310+
/// Creates a new Duration from the specified number of nanoseconds.
311+
///
312+
/// # Panics
313+
///
314+
/// Panics if the given number of nanoseconds is greater than what Duration can handle,
315+
/// which is `(u64::MAX * NANOS_PER_SEC) + NANOS_PER_SEC - 1`
316+
/// Use this function if you need to specify time greater than what can fit in u64
317+
/// (around 584 years).
318+
///
319+
/// # Examples
320+
///
321+
/// ```
322+
/// #![feature(duration_from_nanos_u128)]
323+
/// use std::time::Duration;
324+
/// let time_in_nanos = 2u128.pow(64);
325+
/// let duration = Duration::from_nanos_u128(time_in_nanos);
326+
/// ```
327+
#[unstable(feature = "duration_from_nanos_u128", issue = "139201")]
328+
#[must_use]
329+
#[inline]
330+
pub const fn from_nanos_u128(nanos: u128) -> Duration {
331+
const NANOS_PER_SEC: u128 = self::NANOS_PER_SEC as u128;
332+
let secs: u128 = nanos / NANOS_PER_SEC;
333+
if secs > u64::MAX as u128 {
334+
panic!("overflow in duration in Duration::from_nanos_u128");
335+
}
336+
let subsec_nanos = (nanos % NANOS_PER_SEC) as u32;
337+
// SAFETY: x % 1_000_000_000 < 1_000_000_000 also, subsec_nanos >= 0 since u128 >=0 and u32 >=0
338+
let subsec_nanos = unsafe { Nanoseconds::new_unchecked(subsec_nanos) };
339+
340+
Duration { secs: secs as u64, nanos: subsec_nanos }
341+
}
342+
311343
/// Creates a new `Duration` from the specified number of weeks.
312344
///
313345
/// # Panics

0 commit comments

Comments
 (0)