Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Duration from nanos u128 #139243

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
31 changes: 30 additions & 1 deletion library/core/src/time.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#![stable(feature = "duration_core", since = "1.25.0")]

//! Temporal quantification.
//!
//! # Examples:
Expand Down Expand Up @@ -308,6 +307,36 @@ impl Duration {
Duration { secs, nanos: subsec_nanos }
}


/// Creates a new Duration from the specified number of nanoseconds.
///
/// # Panics
///
/// Panics if the given number of weeks overflows the `Duration` size.
/// Use this function if you need to specify time greater than what can fit in u64
/// (around 584 years).
///
/// # Examples
///
/// ```
/// #![feature(duration_from_nanos_u128)]
/// use std::time::Duration;
/// let time_in_nanos = 2u128.pow(64);
/// let duration = Duration::from_nanos_u128(time_in_nanos);
/// ```
#[unstable(feature = "duration_from_nanos_u128", issue = "139201")]
#[must_use]
#[inline]
pub const fn from_nanos_u128(nanos: u128) -> Duration {
const NANOS_PER_SEC: u128 = self::NANOS_PER_SEC as u128;
let secs : u64 = (nanos/ NANOS_PER_SEC) as u64 ;
let subsec_nanos = (nanos % NANOS_PER_SEC) as u32;
// SAFETY: x % 1_000_000_000 < 1_000_000_000
let subsec_nanos = unsafe { Nanoseconds::new_unchecked(subsec_nanos) };

Duration { secs, nanos: subsec_nanos }
}

/// Creates a new `Duration` from the specified number of weeks.
///
/// # Panics
Expand Down
Loading