Skip to main content

futures_util/future/
poll_immediate.rs

1use super::assert_future;
2use core::pin::Pin;
3use futures_core::task::{Context, Poll};
4use futures_core::{FusedFuture, Future, Stream};
5use pin_project_lite::pin_project;
6
7pin_project! {
8    /// Future for the [`poll_immediate`](poll_immediate()) function.
9    ///
10    /// It will never return [Poll::Pending].
11    #[derive(Debug, Clone)]
12    #[must_use = "futures do nothing unless you `.await` or poll them"]
13    pub struct PollImmediate<T> {
14        #[pin]
15        future: Option<T>
16    }
17}
18
19impl<T, F> Future for PollImmediate<F>
20where
21    F: Future<Output = T>,
22{
23    type Output = Option<T>;
24
25    #[inline]
26    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<T>> {
27        let mut this = self.project();
28        let inner =
29            this.future.as_mut().as_pin_mut().expect("PollImmediate polled after completion");
30        match inner.poll(cx) {
31            Poll::Ready(t) => {
32                this.future.set(None);
33                Poll::Ready(Some(t))
34            }
35            Poll::Pending => Poll::Ready(None),
36        }
37    }
38}
39
40impl<T: Future> FusedFuture for PollImmediate<T> {
41    fn is_terminated(&self) -> bool {
42        self.future.is_none()
43    }
44}
45
46/// A [Stream] implementation that can be polled repeatedly until the future is done.
47/// The stream will never return [Poll::Pending]
48/// so polling it in a tight loop is worse than using a blocking synchronous function.
49/// ```
50/// # futures::executor::block_on(async {
51/// use core::pin::pin;
52///
53/// use futures::task::Poll;
54/// use futures::{StreamExt, future};
55/// use future::FusedFuture;
56///
57/// let f = async { 1_u32 };
58/// let f = pin!(f);
59/// let mut r = future::poll_immediate(f);
60/// assert_eq!(r.next().await, Some(Poll::Ready(1)));
61///
62/// let f = async {futures::pending!(); 42_u8};
63/// let f = pin!(f);
64/// let mut p = future::poll_immediate(f);
65/// assert_eq!(p.next().await, Some(Poll::Pending));
66/// assert!(!p.is_terminated());
67/// assert_eq!(p.next().await, Some(Poll::Ready(42)));
68/// assert!(p.is_terminated());
69/// assert_eq!(p.next().await, None);
70/// # });
71/// ```
72impl<T, F> Stream for PollImmediate<F>
73where
74    F: Future<Output = T>,
75{
76    type Item = Poll<T>;
77
78    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
79        let mut this = self.project();
80        match this.future.as_mut().as_pin_mut() {
81            // inner is gone, so we can signal that the stream is closed.
82            None => Poll::Ready(None),
83            Some(fut) => Poll::Ready(Some(fut.poll(cx).map(|t| {
84                this.future.set(None);
85                t
86            }))),
87        }
88    }
89}
90
91/// Creates a future that is immediately ready with an Option of a value.
92/// Specifically this means that [poll](core::future::Future::poll()) always
93/// returns [Poll::Ready].
94///
95/// # Caution
96///
97/// When consuming the future by this function, note the following:
98///
99/// - This function does not guarantee that the future will run to completion, so it is generally incompatible with passing the non-cancellation-safe future by value.
100/// - Even if the future is cancellation-safe, creating and dropping new futures frequently may lead to performance problems.
101///
102/// # Examples
103///
104/// ```
105/// # futures::executor::block_on(async {
106/// use futures::future;
107///
108/// let r = future::poll_immediate(async { 1_u32 });
109/// assert_eq!(r.await, Some(1));
110///
111/// let p = future::poll_immediate(future::pending::<i32>());
112/// assert_eq!(p.await, None);
113/// # });
114/// ```
115///
116/// ### Reusing a future
117///
118/// ```
119/// # futures::executor::block_on(async {
120/// use core::pin::pin;
121///
122/// use futures::future;
123///
124/// let f = async {futures::pending!(); 42_u8};
125/// let mut f = pin!(f);
126/// assert_eq!(None, future::poll_immediate(&mut f).await);
127/// assert_eq!(42, f.await);
128/// # });
129/// ```
130pub fn poll_immediate<F: Future>(f: F) -> PollImmediate<F> {
131    assert_future::<Option<F::Output>, PollImmediate<F>>(PollImmediate { future: Some(f) })
132}