Skip to main content

hotshot_new_protocol/coordinator/
timer.rs

1use std::{
2    pin::Pin,
3    task::{Context, Poll, ready},
4    time::Duration,
5};
6
7use hotshot_types::data::{EpochNumber, ViewNumber};
8use tokio::time::{Instant, Sleep, sleep};
9
10pub struct Timer {
11    sleep: Pin<Box<Sleep>>,
12    view: ViewNumber,
13    epoch: EpochNumber,
14    duration: Duration,
15    done: bool,
16}
17
18impl Timer {
19    pub fn new(d: Duration, v: ViewNumber, e: EpochNumber) -> Self {
20        Self {
21            sleep: Box::pin(sleep(d)),
22            view: v,
23            epoch: e,
24            duration: d,
25            done: false,
26        }
27    }
28
29    pub fn view(&self) -> ViewNumber {
30        self.view
31    }
32
33    pub fn epoch(&self) -> EpochNumber {
34        self.epoch
35    }
36
37    pub fn reset(&mut self) {
38        self.done = false;
39        self.sleep.as_mut().reset(Instant::now() + self.duration);
40    }
41
42    pub fn reset_with(&mut self, v: ViewNumber) {
43        self.view = v;
44        self.done = false;
45        self.sleep.as_mut().reset(Instant::now() + self.duration);
46    }
47    pub fn reset_with_epoch(&mut self, v: ViewNumber, e: EpochNumber) {
48        self.view = v;
49        self.epoch = e;
50        self.done = false;
51        self.sleep.as_mut().reset(Instant::now() + self.duration);
52    }
53}
54
55impl Future for Timer {
56    type Output = ();
57
58    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
59        if self.done {
60            return Poll::Pending;
61        }
62        ready!(self.sleep.as_mut().poll(cx));
63        self.done = true;
64        Poll::Ready(())
65    }
66}