@@ -218,6 +218,30 @@ impl Instant {
218
218
self . 0 . sub_instant ( & earlier. 0 )
219
219
}
220
220
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
+
221
245
/// Returns the amount of time elapsed since this instant was created.
222
246
///
223
247
/// # Panics
@@ -626,6 +650,12 @@ mod tests {
626
650
( a - Duration :: new ( 1 , 0 ) ) . duration_since ( a) ;
627
651
}
628
652
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
+
629
659
#[ test]
630
660
fn system_time_math ( ) {
631
661
let a = SystemTime :: now ( ) ;
0 commit comments