1//! A type that wraps a future to keep track of its completion status.
2//!
3//! This implementation was taken from the original `macro_rules` `join/try_join`
4//! macros in the `futures-preview` crate.
56use std::future::Future;
7use std::mem;
8use std::pin::Pin;
9use std::task::{Context, Poll};
1011use futures_core::ready;
1213/// A future that may have completed.
14#[derive(Debug)]
15pub(crate) enum MaybeDone<Fut: Future> {
16/// A not-yet-completed future
17Future(Fut),
1819/// The output of the completed future
20Done(Fut::Output),
2122/// The empty variant after the result of a [`MaybeDone`] has been
23 /// taken using the [`take`](MaybeDone::take) method.
24Gone,
25}
2627impl<Fut: Future> MaybeDone<Fut> {
28/// Create a new instance of `MaybeDone`.
29pub(crate) fn new(future: Fut) -> MaybeDone<Fut> {
30Self::Future(future)
31 }
3233/// Returns an [`Option`] containing a reference to the output of the future.
34 /// The output of this method will be [`Some`] if and only if the inner
35 /// future has been completed and [`take`](MaybeDone::take)
36 /// has not yet been called.
37#[inline]
38pub(crate) fn output(self: Pin<&Self>) -> Option<&Fut::Output> {
39let this = self.get_ref();
40match this {
41 MaybeDone::Done(res) => Some(res),
42_ => None,
43 }
44 }
4546/// Attempt to take the output of a `MaybeDone` without driving it
47 /// towards completion.
48#[inline]
49pub(crate) fn take(self: Pin<&mut Self>) -> Option<Fut::Output> {
50unsafe {
51let this = self.get_unchecked_mut();
52match this {
53 MaybeDone::Done(_) => {}
54 MaybeDone::Future(_) | MaybeDone::Gone => return None,
55 };
56if let MaybeDone::Done(output) = mem::replace(this, MaybeDone::Gone) {
57Some(output)
58 } else {
59unreachable!()
60 }
61 }
62 }
63}
6465impl<Fut: Future> Future for MaybeDone<Fut> {
66type Output = ();
6768fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
69let res = unsafe {
70match Pin::as_mut(&mut self).get_unchecked_mut() {
71 MaybeDone::Future(a) => ready!(Pin::new_unchecked(a).poll(cx)),
72 MaybeDone::Done(_) => return Poll::Ready(()),
73 MaybeDone::Gone => panic!("MaybeDone polled after value taken"),
74 }
75 };
76self.set(MaybeDone::Done(res));
77 Poll::Ready(())
78 }
79}