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
pub trait Timestamp {
type Duration: PartialOrd;
type Error;
fn now() -> Self;
fn duration_since_epoch(self) -> Self::Duration;
fn duration_since(&self, other: &Self) -> Result<Self::Duration, Self::Error>;
}
pub trait ElapsedTimer {
type Timestamp: Timestamp;
fn is_timeout(
&self,
from: &Self::Timestamp,
to: &Self::Timestamp,
) -> Result<bool, <Self::Timestamp as Timestamp>::Error>;
}
pub struct Timer<T: Timestamp> {
duration: T::Duration,
}
impl<T: Timestamp> Timer<T> {
pub const fn new(duration: T::Duration) -> Self {
Timer { duration }
}
pub fn borrow_duration(&self) -> &T::Duration {
&self.duration
}
pub fn borrow_mut_duration(&mut self) -> &mut T::Duration {
&mut self.duration
}
}
impl<T: Timestamp> ElapsedTimer for Timer<T> {
type Timestamp = T;
fn is_timeout(
&self,
from: &Self::Timestamp,
to: &Self::Timestamp,
) -> Result<bool, <Self::Timestamp as Timestamp>::Error> {
Ok(to.duration_since(from)? >= self.duration)
}
}