Skip to main content

ntex_util/future/
mod.rs

1//! Future and stream utilities.
2use std::future::{Future, poll_fn};
3use std::pin::Pin;
4use std::task::{Context, Poll, ready};
5
6pub use futures_core::{Stream, TryFuture};
7
8mod either;
9mod join;
10mod lazy;
11mod on_drop;
12mod select;
13
14pub use self::either::Either;
15pub use self::join::{join, join_all};
16pub use self::lazy::{Lazy, lazy};
17pub use self::on_drop::{OnDropFn, OnDropFuture, OnDropFutureExt};
18pub use self::select::select;
19
20pub use ntex_service::dev::InlineFuture;
21
22/// An owned, dynamically dispatched future.
23///
24/// This is useful when a concrete future type cannot be named or when type
25/// erasure is required.
26pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>;
27
28/// Waits for and returns the next item from a stream.
29pub async fn stream_recv<S>(stream: &mut S) -> Option<S::Item>
30where
31    S: Stream + Unpin,
32{
33    poll_fn(|cx| Pin::new(&mut *stream).poll_next(cx)).await
34}
35
36pin_project_lite::pin_project! {
37    #[project = MaybeDoneProj]
38    #[project_replace = MaybeDoneReplace]
39    enum MaybeDone<F: Future> {
40        Pending { #[pin] fut: F },
41        Done { output: F::Output },
42        Gone,
43    }
44}
45
46impl<F: Future> MaybeDone<F> {
47    fn pending(fut: F) -> Self {
48        MaybeDone::Pending { fut }
49    }
50
51    fn take_output(mut self: Pin<&mut Self>) -> Option<F::Output> {
52        match &*self {
53            Self::Done { .. } => {}
54            Self::Pending { .. } | Self::Gone => return None,
55        }
56        match self.as_mut().project_replace(Self::Gone) {
57            MaybeDoneReplace::Done { output } => Some(output),
58            _ => unreachable!(),
59        }
60    }
61}
62
63impl<F: Future> Future for MaybeDone<F> {
64    type Output = ();
65
66    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
67        match self.as_mut().project() {
68            MaybeDoneProj::Pending { fut } => {
69                let output = ready!(fut.poll(cx));
70                self.set(Self::Done { output });
71            }
72            MaybeDoneProj::Done { .. } => {}
73            MaybeDoneProj::Gone => panic!("MaybeDone polled after value taken"),
74        }
75        Poll::Ready(())
76    }
77}
78
79#[cfg(test)]
80mod tests {
81    use std::{future::pending, future::ready, pin::pin};
82
83    use super::*;
84
85    /// STATEMENT: `MaybeDone` exposes an output only after completion and only once.
86    ///
87    /// HOW:
88    /// - Try taking output from a pending future.
89    /// - Complete a ready future, take its output, and verify a second take returns `None`.
90    #[ntex::test]
91    async fn maybe_done_take_output() {
92        let mut fut = pin!(MaybeDone::pending(pending::<()>()));
93        assert!(fut.as_mut().take_output().is_none());
94
95        let mut fut = pin!(MaybeDone::pending(ready(1)));
96        fut.as_mut().await;
97        assert_eq!(fut.as_mut().take_output(), Some(1));
98        // the output is taken once
99        assert!(fut.as_mut().take_output().is_none());
100    }
101
102    /// STATEMENT: Polling `MaybeDone` after taking its output panics with the expected message.
103    ///
104    /// HOW:
105    /// - Complete the future, extract and check its output, then await it again.
106    #[ntex::test]
107    #[should_panic(expected = "MaybeDone polled after value taken")]
108    async fn maybe_done_poll_after_take() {
109        let mut fut = pin!(MaybeDone::pending(ready(1)));
110        fut.as_mut().await;
111        assert_eq!(fut.as_mut().take_output(), Some(1));
112        fut.as_mut().await;
113    }
114
115    /// STATEMENT: `MaybeDone` moves its output out of the pinned value exactly once
116    /// without undefined behavior.
117    ///
118    /// HOW:
119    /// - Check a pending `MaybeDone` has no output and stays pending under `Waker::noop`.
120    /// - Poll a ready `String` future to completion and take its output.
121    /// - Check a second take returns `None`.
122    #[test]
123    fn miri_maybe_done_takes_output_once() {
124        let mut cx = Context::from_waker(std::task::Waker::noop());
125        let mut fut = pin!(MaybeDone::pending(pending::<String>()));
126        assert!(fut.as_mut().poll(&mut cx).is_pending());
127        assert!(fut.as_mut().take_output().is_none());
128
129        let mut fut = pin!(MaybeDone::pending(ready("a".to_string())));
130        assert!(fut.as_mut().poll(&mut cx).is_ready());
131        assert_eq!(fut.as_mut().take_output(), Some("a".to_string()));
132        assert!(fut.as_mut().take_output().is_none());
133    }
134}