@@ -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