Skip to content

Commit

Permalink
Add Instant::saturating_duration_since
Browse files Browse the repository at this point in the history
  • Loading branch information
vi committed Feb 13, 2019
1 parent d15c358 commit 91f67fd
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/libstd/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,27 @@ impl Instant {
}
}

/// Returns the amount of time elapsed from another instant to this one,
/// or zero duration if that instant is earlier than this one.
///
/// # Examples
///
/// ```no_run
/// #![feature(checked_duration_since)]
/// use std::time::{Duration, Instant};
/// use std::thread::sleep;
///
/// let now = Instant::now();
/// sleep(Duration::new(1, 0));
/// let new_now = Instant::now();
/// println!("{:?}", new_now.saturating_duration_since(now));
/// println!("{:?}", now.saturating_duration_since(new_now)); // 0ns
/// ```
#[unstable(feature = "checked_duration_since", issue = "58402")]
pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
self.checked_duration_since(earlier).unwrap_or(Duration::new(0, 0))
}

/// Returns the amount of time elapsed since this instant was created.
///
/// # Panics
Expand Down Expand Up @@ -658,6 +679,13 @@ mod tests {
assert_eq!(ret, None);
}

#[test]
fn saturating_instant_duration_nopanic() {
let a = Instant::now();
let ret = (a - Duration::new(1, 0)).saturating_duration_since(a);
assert_eq!(ret, Duration::new(0,0));
}

#[test]
fn system_time_math() {
let a = SystemTime::now();
Expand Down

0 comments on commit 91f67fd

Please sign in to comment.