async_foundation/timer/
timer_future.rs

1use crate::timer::timer_future_state::TimerFutureState;
2use futures::future::FusedFuture;
3use std::future::Future;
4use std::pin::Pin;
5use std::sync::{Arc, Mutex};
6use std::task::{Context, Poll};
7use std::time::Instant;
8
9pub type TimerFutureStateSafe = Arc<Mutex<TimerFutureState>>;
10
11pub struct TimerFuture {
12    shared_state: TimerFutureStateSafe,
13    completed: bool,
14}
15
16impl TimerFuture {
17    pub fn new(expiration: Instant) -> TimerFuture {
18        TimerFuture {
19            shared_state: Arc::new(Mutex::new(TimerFutureState::new(expiration))),
20            completed: false,
21        }
22    }
23
24    pub fn clone_state(&self) -> TimerFutureStateSafe {
25        self.shared_state.clone()
26    }
27}
28
29impl Future for TimerFuture {
30    type Output = ();
31    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
32        // Look at the shared state to see if the timer has already completed.
33        let mut shared_state = self.shared_state.lock().unwrap();
34        if shared_state.completed {
35            drop(shared_state);
36            self.completed = true;
37            Poll::Ready(())
38        } else {
39            shared_state.waker = Some(cx.waker().clone());
40            Poll::Pending
41        }
42    }
43}
44
45impl FusedFuture for TimerFuture {
46    fn is_terminated(&self) -> bool {
47        self.completed
48    }
49}