Skip to content

Commit bcc16a5

Browse files
committed
add checked_duration_since & saturating_duration_since
1 parent ee6f010 commit bcc16a5

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

src/wasm.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,18 @@ impl Instant {
7070
pub fn elapsed(&self) -> Duration {
7171
Instant::now() - *self
7272
}
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+
}
7385
}
7486

7587
impl Add<Duration> for Instant {
@@ -188,3 +200,25 @@ impl SubAssign<Duration> for SystemTime {
188200
*self = *self - rhs;
189201
}
190202
}
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

Comments
 (0)