futures_util/future/
maybe_done.rs1use 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#[derive(Debug)]
14pub enum MaybeDone<Fut: Future> {
15    Future(Fut),
17    Done(Fut::Output),
19    Gone,
22}
23
24impl<Fut: Future + Unpin> Unpin for MaybeDone<Fut> {}
25
26pub fn maybe_done<Fut: Future>(future: Fut) -> MaybeDone<Fut> {
44    assert_future::<(), _>(MaybeDone::Future(future))
45}
46
47impl<Fut: Future> MaybeDone<Fut> {
48    #[inline]
53    pub fn output_mut(self: Pin<&mut Self>) -> Option<&mut Fut::Output> {
54        unsafe {
55            match self.get_unchecked_mut() {
56                Self::Done(res) => Some(res),
57                _ => None,
58            }
59        }
60    }
61
62    #[inline]
65    pub fn take_output(self: Pin<&mut Self>) -> Option<Fut::Output> {
66        match &*self {
67            Self::Done(_) => {}
68            Self::Future(_) | Self::Gone => return None,
69        }
70        unsafe {
71            match mem::replace(self.get_unchecked_mut(), Self::Gone) {
72                Self::Done(output) => Some(output),
73                _ => unreachable!(),
74            }
75        }
76    }
77}
78
79impl<Fut: Future> FusedFuture for MaybeDone<Fut> {
80    fn is_terminated(&self) -> bool {
81        match self {
82            Self::Future(_) => false,
83            Self::Done(_) | Self::Gone => true,
84        }
85    }
86}
87
88impl<Fut: Future> Future for MaybeDone<Fut> {
89    type Output = ();
90
91    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
92        unsafe {
93            match self.as_mut().get_unchecked_mut() {
94                Self::Future(f) => {
95                    let res = ready!(Pin::new_unchecked(f).poll(cx));
96                    self.set(Self::Done(res));
97                }
98                Self::Done(_) => {}
99                Self::Gone => panic!("MaybeDone polled after value taken"),
100            }
101        }
102        Poll::Ready(())
103    }
104}