futures_util/future/
maybe_done.rs

1//! Definition of the MaybeDone combinator
2
3use super::assert_future;
4use core::mem;
5use core::pin::Pin;
6use futures_core::future::{FusedFuture, Future};
7use futures_core::ready;
8use futures_core::task::{Context, Poll};
9
10/// A future that may have completed.
11///
12/// This is created by the [`maybe_done()`] function.
13#[derive(Debug)]
14pub enum MaybeDone<Fut: Future> {
15    /// A not-yet-completed future
16    Future(/* #[pin] */ Fut),
17    /// The output of the completed future
18    Done(Fut::Output),
19    /// The empty variant after the result of a [`MaybeDone`] has been
20    /// taken using the [`take_output`](MaybeDone::take_output) method.
21    Gone,
22}
23
24impl<Fut: Future + Unpin> Unpin for MaybeDone<Fut> {}
25
26/// Wraps a future into a `MaybeDone`
27///
28/// # Examples
29///
30/// ```
31/// # futures::executor::block_on(async {
32/// use core::pin::pin;
33///
34/// use futures::future;
35///
36/// let future = future::maybe_done(async { 5 });
37/// let mut future = pin!(future);
38/// assert_eq!(future.as_mut().take_output(), None);
39/// let () = future.as_mut().await;
40/// assert_eq!(future.as_mut().take_output(), Some(5));
41/// assert_eq!(future.as_mut().take_output(), None);
42/// # });
43/// ```
44pub fn maybe_done<Fut: Future>(future: Fut) -> MaybeDone<Fut> {
45    assert_future::<(), _>(MaybeDone::Future(future))
46}
47
48impl<Fut: Future> MaybeDone<Fut> {
49    /// Returns an [`Option`] containing a mutable reference to the output of the future.
50    /// The output of this method will be [`Some`] if and only if the inner
51    /// future has been completed and [`take_output`](MaybeDone::take_output)
52    /// has not yet been called.
53    #[inline]
54    pub fn output_mut(self: Pin<&mut Self>) -> Option<&mut Fut::Output> {
55        unsafe {
56            match self.get_unchecked_mut() {
57                Self::Done(res) => Some(res),
58                _ => None,
59            }
60        }
61    }
62
63    /// Attempt to take the output of a `MaybeDone` without driving it
64    /// towards completion.
65    #[inline]
66    pub fn take_output(self: Pin<&mut Self>) -> Option<Fut::Output> {
67        match &*self {
68            Self::Done(_) => {}
69            Self::Future(_) | Self::Gone => return None,
70        }
71        unsafe {
72            match mem::replace(self.get_unchecked_mut(), Self::Gone) {
73                Self::Done(output) => Some(output),
74                _ => unreachable!(),
75            }
76        }
77    }
78}
79
80impl<Fut: Future> FusedFuture for MaybeDone<Fut> {
81    fn is_terminated(&self) -> bool {
82        match self {
83            Self::Future(_) => false,
84            Self::Done(_) | Self::Gone => true,
85        }
86    }
87}
88
89impl<Fut: Future> Future for MaybeDone<Fut> {
90    type Output = ();
91
92    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
93        unsafe {
94            match self.as_mut().get_unchecked_mut() {
95                Self::Future(f) => {
96                    let res = ready!(Pin::new_unchecked(f).poll(cx));
97                    self.set(Self::Done(res));
98                }
99                Self::Done(_) => {}
100                Self::Gone => panic!("MaybeDone polled after value taken"),
101            }
102        }
103        Poll::Ready(())
104    }
105}