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::ViewNumber;
8use tokio::time::{Instant, Sleep, sleep};
9
10pub struct Timer {
11    sleep: Pin<Box<Sleep>>,
12    view: ViewNumber,
13    duration: Duration,
14    done: bool,
15}
16
17impl Timer {
18    pub fn new(d: Duration, v: ViewNumber) -> Self {
19        Self {
20            sleep: Box::pin(sleep(d)),
21            view: v,
22            duration: d,
23            done: false,
24        }
25    }
26
27    pub fn view(&self) -> ViewNumber {
28        self.view
29    }
30
31    pub fn reset(&mut self) {
32        self.done = false;
33        self.sleep.as_mut().reset(Instant::now() + self.duration);
34    }
35
36    pub fn reset_with(&mut self, v: ViewNumber) {
37        self.view = v;
38        self.done = false;
39        self.sleep.as_mut().reset(Instant::now() + self.duration);
40    }
41}
42
43impl Future for Timer {
44    type Output = ();
45
46    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
47        if self.done {
48            return Poll::Pending;
49        }
50        ready!(self.sleep.as_mut().poll(cx));
51        self.done = true;
52        Poll::Ready(())
53    }
54}