Skip to content

Commit 7b2a08c

Browse files
committed
Add Instant::checked_duration_since, address #58402.
1 parent ba2853b commit 7b2a08c

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

src/libstd/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -295,6 +295,7 @@
295295
#![feature(non_exhaustive)]
296296
#![feature(alloc_layout_extra)]
297297
#![feature(maybe_uninit)]
298+
#![feature(checked_duration_since)]
298299
#![cfg_attr(all(target_vendor = "fortanix", target_env = "sgx"),
299300
feature(global_asm, range_contains, slice_index_methods,
300301
decl_macro, coerce_unsized, sgx_platform, ptr_wrapping_offset_from))]

src/libstd/time.rs

+30
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,30 @@ impl Instant {
218218
self.0.sub_instant(&earlier.0)
219219
}
220220

221+
/// Returns the amount of time elapsed from another instant to this one,
222+
/// or None if that instant is earlier than this one.
223+
///
224+
/// # Examples
225+
///
226+
/// ```no_run
227+
/// use std::time::{Duration, Instant};
228+
/// use std::thread::sleep;
229+
///
230+
/// let now = Instant::now();
231+
/// sleep(Duration::new(1, 0));
232+
/// let new_now = Instant::now();
233+
/// println!("{:?}", new_now.checked_duration_since(now));
234+
/// println!("{:?}", now.checked_duration_since(new_now)); // None
235+
/// ```
236+
#[unstable(feature = "checked_duration_since", issue = "58402")]
237+
pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> {
238+
if self >= &earlier {
239+
Some(self.0.sub_instant(&earlier.0))
240+
} else {
241+
None
242+
}
243+
}
244+
221245
/// Returns the amount of time elapsed since this instant was created.
222246
///
223247
/// # Panics
@@ -626,6 +650,12 @@ mod tests {
626650
(a - Duration::new(1, 0)).duration_since(a);
627651
}
628652

653+
#[test]
654+
fn checked_instant_duration_nopanic() {
655+
let a = Instant::now();
656+
(a - Duration::new(1, 0)).checked_duration_since(a);
657+
}
658+
629659
#[test]
630660
fn system_time_math() {
631661
let a = SystemTime::now();

0 commit comments

Comments
 (0)