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](core::task::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](crate::stream::Stream) implementation that can be polled repeatedly until the future is done.
47/// The stream will never return [Poll::Pending](core::task::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 returns [Poll::Ready](core::task::Poll::Ready).
93///
94/// # Caution
95///
96/// When consuming the future by this function, note the following:
97///
98/// - 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.
99/// - Even if the future is cancellation-safe, creating and dropping new futures frequently may lead to performance problems.
100///
101/// # Examples
102///
103/// ```
104/// # futures::executor::block_on(async {
105/// use futures::future;
106///
107/// let r = future::poll_immediate(async { 1_u32 });
108/// assert_eq!(r.await, Some(1));
109///
110/// let p = future::poll_immediate(future::pending::<i32>());
111/// assert_eq!(p.await, None);
112/// # });
113/// ```
114///
115/// ### Reusing a future
116///
117/// ```
118/// # futures::executor::block_on(async {
119/// use core::pin::pin;
120///
121/// use futures::future;
122///
123/// let f = async {futures::pending!(); 42_u8};
124/// let mut f = pin!(f);
125/// assert_eq!(None, future::poll_immediate(&mut f).await);
126/// assert_eq!(42, f.await);
127/// # });
128/// ```
129pub fn poll_immediate<F: Future>(f: F) -> PollImmediate<F> {
130 assert_future::<Option<F::Output>, PollImmediate<F>>(PollImmediate { future: Some(f) })
131}