Skip to content

Commit

Permalink
Rollup merge of rust-lang#50167 - fintelia:duration-nanos, r=sfackler
Browse files Browse the repository at this point in the history
 Add as_nanos function to Duration

Duration has historically lacked a way to get the actual number of nanoseconds it contained as a normal Rust type because u64 was of insufficient range, and f64 of insufficient precision. The u128 type solves both issues, so I propose adding an `as_nanos` function to expose the capability.
  • Loading branch information
Mark-Simulacrum committed Jun 2, 2018
2 parents 4ecf12b + fc89566 commit 77c8bd0
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions src/libcore/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,57 @@ impl Duration {
#[inline]
pub const fn subsec_nanos(&self) -> u32 { self.nanos }

/// Returns the total number of milliseconds contained by this `Duration`.
///
/// # Examples
///
/// ```
/// # #![feature(duration_as_u128)]
/// use std::time::Duration;
///
/// let duration = Duration::new(5, 730023852);
/// assert_eq!(duration.as_millis(), 5730);
/// ```
#[unstable(feature = "duration_as_u128", issue = "50202")]
#[inline]
pub fn as_millis(&self) -> u128 {
self.secs as u128 * MILLIS_PER_SEC as u128 + (self.nanos / NANOS_PER_MILLI) as u128
}

/// Returns the total number of microseconds contained by this `Duration`.
///
/// # Examples
///
/// ```
/// # #![feature(duration_as_u128)]
/// use std::time::Duration;
///
/// let duration = Duration::new(5, 730023852);
/// assert_eq!(duration.as_micros(), 5730023);
/// ```
#[unstable(feature = "duration_as_u128", issue = "50202")]
#[inline]
pub fn as_micros(&self) -> u128 {
self.secs as u128 * MICROS_PER_SEC as u128 + (self.nanos / NANOS_PER_MICRO) as u128
}

/// Returns the total number of nanoseconds contained by this `Duration`.
///
/// # Examples
///
/// ```
/// # #![feature(duration_as_u128)]
/// use std::time::Duration;
///
/// let duration = Duration::new(5, 730023852);
/// assert_eq!(duration.as_nanos(), 5730023852);
/// ```
#[unstable(feature = "duration_as_u128", issue = "50202")]
#[inline]
pub fn as_nanos(&self) -> u128 {
self.secs as u128 * NANOS_PER_SEC as u128 + self.nanos as u128
}

/// Checked `Duration` addition. Computes `self + other`, returning [`None`]
/// if overflow occurred.
///
Expand Down

0 comments on commit 77c8bd0

Please sign in to comment.