@@ -218,6 +218,52 @@ 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
+ /// #![feature(checked_duration_since)]
228
+ /// use std::time::{Duration, Instant};
229
+ /// use std::thread::sleep;
230
+ ///
231
+ /// let now = Instant::now();
232
+ /// sleep(Duration::new(1, 0));
233
+ /// let new_now = Instant::now();
234
+ /// println!("{:?}", new_now.checked_duration_since(now));
235
+ /// println!("{:?}", now.checked_duration_since(new_now)); // None
236
+ /// ```
237
+ #[ unstable( feature = "checked_duration_since" , issue = "58402" ) ]
238
+ pub fn checked_duration_since ( & self , earlier : Instant ) -> Option < Duration > {
239
+ if self >= & earlier {
240
+ Some ( self . 0 . sub_instant ( & earlier. 0 ) )
241
+ } else {
242
+ None
243
+ }
244
+ }
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
+
221
267
/// Returns the amount of time elapsed since this instant was created.
222
268
///
223
269
/// # Panics
@@ -626,6 +672,20 @@ mod tests {
626
672
( a - Duration :: new ( 1 , 0 ) ) . duration_since ( a) ;
627
673
}
628
674
675
+ #[ test]
676
+ fn checked_instant_duration_nopanic ( ) {
677
+ let a = Instant :: now ( ) ;
678
+ let ret = ( a - Duration :: new ( 1 , 0 ) ) . checked_duration_since ( a) ;
679
+ assert_eq ! ( ret, None ) ;
680
+ }
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
+
629
689
#[ test]
630
690
fn system_time_math ( ) {
631
691
let a = SystemTime :: now ( ) ;
0 commit comments