networky 0.1.1

networking library for indigo with NaCl (Curve25519) encrypted connections and an async progress monitor.
Documentation
use std::pin::Pin;
use std::time::{Duration, Instant};
use std::task::Poll;
use futures::Future;
use tokio::time::Sleep;
use pin_project_lite::pin_project;

pin_project! {
    /// Future returned by [`timeout`](timeout) and [`timeout_at`](timeout_at).
    #[must_use = "futures do nothing unless you `.await` or poll them"]
    #[derive(Debug)]
    pub struct StaleTimeout<T> {
        #[pin]
        value: T,
        #[pin]
        delay: Sleep,
        #[pin]
        duration: Duration,
    }
}

impl<T> StaleTimeout<T> {
    pub(crate) fn new_with_duration(value: T, duration: Duration) -> StaleTimeout<T> {
        StaleTimeout { value, delay: tokio::time::sleep(duration), duration }
    }

    /// Gets a reference to the underlying value in this timeout.
    pub fn get_ref(&self) -> &T {
        &self.value
    }

    /// Gets a mutable reference to the underlying value in this timeout.
    pub fn get_mut(&mut self) -> &mut T {
        &mut self.value
    }

    /// Consumes this timeout, returning the underlying value.
    pub fn into_inner(self) -> T {
        self.value
    }
}

#[derive(Debug,Default)]
pub struct Stale {
}

impl std::fmt::Display for Stale {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Stale")
    }
}

impl Stale {
    pub fn new() -> Self {
        Self {}
    }
}

impl<T> Future for StaleTimeout<T>
where
    T: Future,
{
    type Output = Result<T::Output, Stale>;

    fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
        let mut me = self.project();
        //eprintln!("poll -> {:?}", me.delay.deadline().duration_since(tokio::time::Instant::now()));

        match me.delay.as_mut().poll(cx) {
            Poll::Ready(()) => return Poll::Ready(Err(Stale::new())),
            Poll::Pending => {},
        }
        me.delay.as_mut().reset((Instant::now() + *me.duration).into());

        if let Poll::Ready(v) = me.value.poll(cx) {
            return Poll::Ready(Ok(v));
        }

        Poll::Pending
    }
}

/// Will time-out and report [`Stale`] error if not polled every `duration` time.
pub fn progress<T>(request: T, duration: Duration) -> StaleTimeout<T>
where
  T: Future
{
    StaleTimeout::new_with_duration(request, duration)
}