Add Instant::saturating_duration_since

This commit is contained in:
Vitaly _Vi Shukela 2019-02-13 15:08:44 +03:00
parent d15c358000
commit 91f67fd1a7
No known key found for this signature in database
GPG Key ID: C097221D6E03DF68

View File

@ -243,6 +243,27 @@ pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> {
}
}
/// 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
@ -658,6 +679,13 @@ fn checked_instant_duration_nopanic() {
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();