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> {
45 assert_future::<(), _>(MaybeDone::Future(future))
46}
47
48impl<Fut: Future> MaybeDone<Fut> {
49 #[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 #[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}