-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathinstant.rs
More file actions
91 lines (76 loc) · 2.2 KB
/
instant.rs
File metadata and controls
91 lines (76 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
use super::{Duration, Wait};
use std::future::IntoFuture;
use std::ops::{Add, AddAssign, Sub, SubAssign};
use wasip2::clocks::monotonic_clock;
/// A measurement of a monotonically nondecreasing clock. Opaque and useful only
/// with Duration.
///
/// This type wraps `std::time::Duration` so we can implement traits on it
/// without coherence issues, just like if we were implementing this in the
/// stdlib.
#[derive(Debug, PartialEq, PartialOrd, Ord, Eq, Hash, Clone, Copy)]
pub struct Instant(pub(crate) monotonic_clock::Instant);
impl Instant {
/// Returns an instant corresponding to "now".
///
/// # Examples
///
/// ```no_run
/// use wstd::time::Instant;
///
/// let now = Instant::now();
/// ```
#[must_use]
pub fn now() -> Self {
Instant(wasip2::clocks::monotonic_clock::now())
}
/// Returns the amount of time elapsed from another instant to this one, or zero duration if
/// that instant is later than this one.
pub fn duration_since(&self, earlier: Instant) -> Duration {
Duration::from_nanos(self.0.saturating_sub(earlier.0))
}
/// Returns the amount of time elapsed since this instant.
pub fn elapsed(&self) -> Duration {
Instant::now().duration_since(*self)
}
}
impl Add<Duration> for Instant {
type Output = Self;
fn add(self, rhs: Duration) -> Self::Output {
Self(self.0 + rhs.0)
}
}
impl AddAssign<Duration> for Instant {
fn add_assign(&mut self, rhs: Duration) {
*self = Self(self.0 + rhs.0)
}
}
impl Sub<Duration> for Instant {
type Output = Self;
fn sub(self, rhs: Duration) -> Self::Output {
Self(self.0 - rhs.0)
}
}
impl SubAssign<Duration> for Instant {
fn sub_assign(&mut self, rhs: Duration) {
*self = Self(self.0 - rhs.0)
}
}
impl IntoFuture for Instant {
type Output = Instant;
type IntoFuture = Wait;
fn into_future(self) -> Self::IntoFuture {
crate::task::sleep_until(self)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_duration_since() {
let x = Instant::now();
let d = Duration::new(456, 789);
let y = x + d;
assert_eq!(y.duration_since(x), d);
}
}