Add Instant::checked_duration_since, address #58402.

This commit is contained in:
Vitaly _Vi Shukela 2019-02-12 10:56:26 +03:00
parent ba2853b6d3
commit 7b2a08cf49
No known key found for this signature in database
GPG Key ID: C097221D6E03DF68
2 changed files with 31 additions and 0 deletions

View File

@ -295,6 +295,7 @@
#![feature(non_exhaustive)]
#![feature(alloc_layout_extra)]
#![feature(maybe_uninit)]
#![feature(checked_duration_since)]
#![cfg_attr(all(target_vendor = "fortanix", target_env = "sgx"),
feature(global_asm, range_contains, slice_index_methods,
decl_macro, coerce_unsized, sgx_platform, ptr_wrapping_offset_from))]

View File

@ -218,6 +218,30 @@ pub fn duration_since(&self, earlier: Instant) -> Duration {
self.0.sub_instant(&earlier.0)
}
/// Returns the amount of time elapsed from another instant to this one,
/// or None if that instant is earlier than this one.
///
/// # Examples
///
/// ```no_run
/// 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.checked_duration_since(now));
/// println!("{:?}", now.checked_duration_since(new_now)); // None
/// ```
#[unstable(feature = "checked_duration_since", issue = "58402")]
pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> {
if self >= &earlier {
Some(self.0.sub_instant(&earlier.0))
} else {
None
}
}
/// Returns the amount of time elapsed since this instant was created.
///
/// # Panics
@ -626,6 +650,12 @@ fn instant_duration_panic() {
(a - Duration::new(1, 0)).duration_since(a);
}
#[test]
fn checked_instant_duration_nopanic() {
let a = Instant::now();
(a - Duration::new(1, 0)).checked_duration_since(a);
}
#[test]
fn system_time_math() {
let a = SystemTime::now();