@@ -70,6 +70,18 @@ impl Instant {
70
70
pub fn elapsed ( & self ) -> Duration {
71
71
Instant :: now ( ) - * self
72
72
}
73
+
74
+ pub fn saturating_duration_since ( & self , earlier : Instant ) -> Duration {
75
+ self . checked_duration_since ( earlier) . unwrap_or ( Duration :: new ( 0 , 0 ) )
76
+ }
77
+
78
+ pub fn checked_duration_since ( & self , earlier : Instant ) -> Option < Duration > {
79
+ if self . inner >= earlier. inner {
80
+ Some ( * self - earlier)
81
+ } else {
82
+ None
83
+ }
84
+ }
73
85
}
74
86
75
87
impl Add < Duration > for Instant {
@@ -188,3 +200,25 @@ impl SubAssign<Duration> for SystemTime {
188
200
* self = * self - rhs;
189
201
}
190
202
}
203
+
204
+ #[ cfg( test) ]
205
+ mod tests {
206
+ use super :: * ;
207
+
208
+ #[ test]
209
+ fn instant_checked_duration_since_nopanic ( ) {
210
+ let now = Instant :: now ( ) ;
211
+ let earlier = now - Duration :: new ( 1 , 0 ) ;
212
+ let later = now + Duration :: new ( 1 , 0 ) ;
213
+ assert_eq ! ( earlier. checked_duration_since( now) , None ) ;
214
+ assert_eq ! ( later. checked_duration_since( now) , Some ( Duration :: new( 1 , 0 ) ) ) ;
215
+ assert_eq ! ( now. checked_duration_since( now) , Some ( Duration :: new( 0 , 0 ) ) ) ;
216
+ }
217
+
218
+ #[ test]
219
+ fn instant_saturating_duration_since_nopanic ( ) {
220
+ let a = Instant :: now ( ) ;
221
+ let ret = ( a - Duration :: new ( 1 , 0 ) ) . saturating_duration_since ( a) ;
222
+ assert_eq ! ( ret, Duration :: new( 0 , 0 ) ) ;
223
+ }
224
+ }
0 commit comments