Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/libstd/time/duration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,16 @@ impl Duration {
#[stable(feature = "duration", since = "1.3.0")]
pub fn as_secs(&self) -> u64 { self.secs }

/// Returns the number of whole milliseconds represented by this duration.
///
/// Returns `None` if the operation would overflow.
#[unstable(feature = "duration_as_millis", reason = "newly added")]
pub fn as_millis(&self) -> Option<u64> {
self.secs.checked_mul(MILLIS_PER_SEC).and_then(|millis| {
millis.checked_add((self.nanos / NANOS_PER_MILLI) as u64)
})
}

/// Returns the nanosecond precision represented by this duration.
///
/// This method does **not** return the length of the duration when
Expand Down Expand Up @@ -188,6 +198,15 @@ mod tests {
assert_eq!(Duration::from_millis(1001).as_secs(), 1);
}

#[test]
fn millis() {
assert_eq!(Duration::new(0, 0).as_millis(), Some(0));
assert_eq!(Duration::new(0, 5).as_millis(), Some(0));
assert_eq!(Duration::from_secs(1).as_millis(), Some(1_000));
assert_eq!(Duration::from_millis(999).as_millis(), Some(999));
assert_eq!(Duration::from_millis(1001).as_millis(), Some(1001));
}

#[test]
fn nanos() {
assert_eq!(Duration::new(0, 0).subsec_nanos(), 0);
Expand Down