ntex-util 4.10.0

Utilities for ntex framework
Documentation
//! Future and stream utilities.
use std::future::{Future, poll_fn};
use std::pin::Pin;
use std::task::{Context, Poll, ready};

pub use futures_core::{Stream, TryFuture};

mod either;
mod join;
mod lazy;
mod on_drop;
mod select;

pub use self::either::Either;
pub use self::join::{join, join_all};
pub use self::lazy::{Lazy, lazy};
pub use self::on_drop::{OnDropFn, OnDropFuture, OnDropFutureExt};
pub use self::select::select;

/// An owned, dynamically dispatched future.
///
/// This is useful when a concrete future type cannot be named or when type
/// erasure is required.
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>;

/// Waits for and returns the next item from a stream.
pub async fn stream_recv<S>(stream: &mut S) -> Option<S::Item>
where
    S: Stream + Unpin,
{
    poll_fn(|cx| Pin::new(&mut *stream).poll_next(cx)).await
}

pin_project_lite::pin_project! {
    #[project = MaybeDoneProj]
    #[project_replace = MaybeDoneReplace]
    enum MaybeDone<F: Future> {
        Pending { #[pin] fut: F },
        Done { output: F::Output },
        Gone,
    }
}

impl<F: Future> MaybeDone<F> {
    fn pending(fut: F) -> Self {
        MaybeDone::Pending { fut }
    }

    fn take_output(mut self: Pin<&mut Self>) -> Option<F::Output> {
        match &*self {
            Self::Done { .. } => {}
            Self::Pending { .. } | Self::Gone => return None,
        }
        match self.as_mut().project_replace(Self::Gone) {
            MaybeDoneReplace::Done { output } => Some(output),
            _ => unreachable!(),
        }
    }
}

impl<F: Future> Future for MaybeDone<F> {
    type Output = ();

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        match self.as_mut().project() {
            MaybeDoneProj::Pending { fut } => {
                let output = ready!(fut.poll(cx));
                self.set(Self::Done { output });
            }
            MaybeDoneProj::Done { .. } => {}
            MaybeDoneProj::Gone => panic!("MaybeDone polled after value taken"),
        }
        Poll::Ready(())
    }
}

#[cfg(test)]
mod tests {
    use std::{future::pending, future::ready, pin::pin};

    use super::*;

    /// STATEMENT: `MaybeDone` exposes an output only after completion and only once.
    ///
    /// HOW:
    /// - Try taking output from a pending future.
    /// - Complete a ready future, take its output, and verify a second take returns `None`.
    #[ntex::test]
    async fn maybe_done_take_output() {
        let mut fut = pin!(MaybeDone::pending(pending::<()>()));
        assert!(fut.as_mut().take_output().is_none());

        let mut fut = pin!(MaybeDone::pending(ready(1)));
        fut.as_mut().await;
        assert_eq!(fut.as_mut().take_output(), Some(1));
        // the output is taken once
        assert!(fut.as_mut().take_output().is_none());
    }

    /// STATEMENT: Polling `MaybeDone` after taking its output panics with the expected message.
    ///
    /// HOW:
    /// - Complete the future, extract and check its output, then await it again.
    #[ntex::test]
    #[should_panic(expected = "MaybeDone polled after value taken")]
    async fn maybe_done_poll_after_take() {
        let mut fut = pin!(MaybeDone::pending(ready(1)));
        fut.as_mut().await;
        assert_eq!(fut.as_mut().take_output(), Some(1));
        fut.as_mut().await;
    }

    /// STATEMENT: `MaybeDone` moves its output out of the pinned value exactly once
    /// without undefined behavior.
    ///
    /// HOW:
    /// - Check a pending `MaybeDone` has no output and stays pending under `Waker::noop`.
    /// - Poll a ready `String` future to completion and take its output.
    /// - Check a second take returns `None`.
    #[test]
    fn miri_maybe_done_takes_output_once() {
        let mut cx = Context::from_waker(std::task::Waker::noop());
        let mut fut = pin!(MaybeDone::pending(pending::<String>()));
        assert!(fut.as_mut().poll(&mut cx).is_pending());
        assert!(fut.as_mut().take_output().is_none());

        let mut fut = pin!(MaybeDone::pending(ready("a".to_string())));
        assert!(fut.as_mut().poll(&mut cx).is_ready());
        assert_eq!(fut.as_mut().take_output(), Some("a".to_string()));
        assert!(fut.as_mut().take_output().is_none());
    }
}