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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#![deny(missing_docs)]
extern crate tokio_timer;
extern crate futures;
use tokio_timer::Delay;
use futures::Future;
use futures::Async;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::{Duration, Instant};
struct Impl {
del : Option<Delay>,
dur : Duration,
ins : Instant,
}
type H = Arc<Mutex<Impl>>;
pub struct Watchdog(H);
impl Watchdog {
pub fn new(dur: Duration) -> Self {
let ins = Instant::now() + dur;
let del = Delay::new(ins);
let i = Impl { del:Some(del), dur, ins };
Watchdog(Arc::new(Mutex::new(i)))
}
pub fn duration(&self) -> Duration {
if let Ok(g) = self.0.lock() {
g.dur
} else {
Duration::from_secs(0)
}
}
pub fn set_duration(&mut self, dur: Duration) {
if let Ok(mut g) = self.0.lock() {
g.ins = g.ins - g.dur + dur;
g.dur = dur;
let i = g.ins;
if let Some(ref mut d) = g.del {
d.reset(i);
}
}
}
pub fn handle(&self) -> Pet {
self.into()
}
}
#[derive(Clone)]
pub struct Pet(H);
impl Pet {
pub fn pet(&self) {
if let Ok(mut g) = self.0.lock() {
let i = Instant::now() + g.dur;
g.ins = i;
if let Some(ref mut x) = g.del {
x.reset(i);
}
} else {
}
}
pub fn get_remaining_time(&self) -> Option<Duration> {
if let Ok(g) = self.0.lock() {
let now = Instant::now();
let i = g.ins;
if now > i {
None
} else {
Some(i - now)
}
} else {
Some(Duration::from_secs(0))
}
}
}
impl<'a> From<&'a Watchdog> for Pet {
fn from(w : &'a Watchdog) -> Pet {
Pet(w.0.clone())
}
}
pub struct Rearm(H);
impl Rearm {
pub fn rearm(self) -> Watchdog {
Watchdog(self.0)
}
pub fn rearm_with_duration(self, dur: Duration) -> Watchdog {
let mut w = Watchdog(self.0);
w.set_duration(dur);
w
}
}
impl Future for Watchdog {
type Item = Rearm;
type Error = tokio_timer::Error;
fn poll(&mut self) -> futures::Poll<Rearm, tokio_timer::Error> {
if let Ok(mut g) = self.0.lock() {
if let Some(ref mut d) = g.del {
match d.poll() {
Ok(Async::Ready(())) => Ok(Async::Ready(
Rearm(self.0.clone())
)),
Ok(Async::NotReady) => Ok(Async::NotReady),
Err(x) => Err(x),
}
} else {
Ok(Async::Ready(Rearm(self.0.clone())))
}
} else {
Err(tokio_timer::Error::at_capacity())
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
}
}