@@ -243,6 +243,27 @@ impl Instant {
243
243
}
244
244
}
245
245
246
+ /// Returns the amount of time elapsed from another instant to this one,
247
+ /// or zero duration if that instant is earlier than this one.
248
+ ///
249
+ /// # Examples
250
+ ///
251
+ /// ```no_run
252
+ /// #![feature(checked_duration_since)]
253
+ /// use std::time::{Duration, Instant};
254
+ /// use std::thread::sleep;
255
+ ///
256
+ /// let now = Instant::now();
257
+ /// sleep(Duration::new(1, 0));
258
+ /// let new_now = Instant::now();
259
+ /// println!("{:?}", new_now.saturating_duration_since(now));
260
+ /// println!("{:?}", now.saturating_duration_since(new_now)); // 0ns
261
+ /// ```
262
+ #[ unstable( feature = "checked_duration_since" , issue = "58402" ) ]
263
+ pub fn saturating_duration_since ( & self , earlier : Instant ) -> Duration {
264
+ self . checked_duration_since ( earlier) . unwrap_or ( Duration :: new ( 0 , 0 ) )
265
+ }
266
+
246
267
/// Returns the amount of time elapsed since this instant was created.
247
268
///
248
269
/// # Panics
@@ -658,6 +679,13 @@ mod tests {
658
679
assert_eq ! ( ret, None ) ;
659
680
}
660
681
682
+ #[ test]
683
+ fn saturating_instant_duration_nopanic ( ) {
684
+ let a = Instant :: now ( ) ;
685
+ let ret = ( a - Duration :: new ( 1 , 0 ) ) . saturating_duration_since ( a) ;
686
+ assert_eq ! ( ret, Duration :: new( 0 , 0 ) ) ;
687
+ }
688
+
661
689
#[ test]
662
690
fn system_time_math ( ) {
663
691
let a = SystemTime :: now ( ) ;
0 commit comments