Skip to content

Commit 77c8bd0

Browse files
Rollup merge of rust-lang#50167 - fintelia:duration-nanos, r=sfackler
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.
2 parents 4ecf12b + fc89566 commit 77c8bd0

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

src/libcore/time.rs

+51
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,57 @@ impl Duration {
268268
#[inline]
269269
pub const fn subsec_nanos(&self) -> u32 { self.nanos }
270270

271+
/// Returns the total number of milliseconds contained by this `Duration`.
272+
///
273+
/// # Examples
274+
///
275+
/// ```
276+
/// # #![feature(duration_as_u128)]
277+
/// use std::time::Duration;
278+
///
279+
/// let duration = Duration::new(5, 730023852);
280+
/// assert_eq!(duration.as_millis(), 5730);
281+
/// ```
282+
#[unstable(feature = "duration_as_u128", issue = "50202")]
283+
#[inline]
284+
pub fn as_millis(&self) -> u128 {
285+
self.secs as u128 * MILLIS_PER_SEC as u128 + (self.nanos / NANOS_PER_MILLI) as u128
286+
}
287+
288+
/// Returns the total number of microseconds contained by this `Duration`.
289+
///
290+
/// # Examples
291+
///
292+
/// ```
293+
/// # #![feature(duration_as_u128)]
294+
/// use std::time::Duration;
295+
///
296+
/// let duration = Duration::new(5, 730023852);
297+
/// assert_eq!(duration.as_micros(), 5730023);
298+
/// ```
299+
#[unstable(feature = "duration_as_u128", issue = "50202")]
300+
#[inline]
301+
pub fn as_micros(&self) -> u128 {
302+
self.secs as u128 * MICROS_PER_SEC as u128 + (self.nanos / NANOS_PER_MICRO) as u128
303+
}
304+
305+
/// Returns the total number of nanoseconds contained by this `Duration`.
306+
///
307+
/// # Examples
308+
///
309+
/// ```
310+
/// # #![feature(duration_as_u128)]
311+
/// use std::time::Duration;
312+
///
313+
/// let duration = Duration::new(5, 730023852);
314+
/// assert_eq!(duration.as_nanos(), 5730023852);
315+
/// ```
316+
#[unstable(feature = "duration_as_u128", issue = "50202")]
317+
#[inline]
318+
pub fn as_nanos(&self) -> u128 {
319+
self.secs as u128 * NANOS_PER_SEC as u128 + self.nanos as u128
320+
}
321+
271322
/// Checked `Duration` addition. Computes `self + other`, returning [`None`]
272323
/// if overflow occurred.
273324
///

0 commit comments

Comments
 (0)