async-foundation 0.2.1

Foundational async primitives for Rust - timers, networking, and common utilities
Documentation
use crate::timer::timer_future_state::TimerFutureState;
use futures::future::FusedFuture;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
use std::time::Instant;

pub type TimerFutureStateSafe = Arc<Mutex<TimerFutureState>>;

pub struct TimerFuture {
    shared_state: TimerFutureStateSafe,
    completed: bool,
}

impl TimerFuture {
    pub fn new(expiration: Instant) -> TimerFuture {
        TimerFuture {
            shared_state: Arc::new(Mutex::new(TimerFutureState::new(expiration))),
            completed: false,
        }
    }

    pub fn clone_state(&self) -> TimerFutureStateSafe {
        self.shared_state.clone()
    }
}

impl Future for TimerFuture {
    type Output = ();
    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        // Look at the shared state to see if the timer has already completed.
        let mut shared_state = self.shared_state.lock().unwrap();
        if shared_state.completed {
            drop(shared_state);
            self.completed = true;
            Poll::Ready(())
        } else {
            shared_state.waker = Some(cx.waker().clone());
            Poll::Pending
        }
    }
}

impl FusedFuture for TimerFuture {
    fn is_terminated(&self) -> bool {
        self.completed
    }
}