1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#![allow(unused_imports)] // items are used by the macro

use crate::cell::UnsafeCell;
use crate::future::{poll_fn, Future};
use crate::mem;
use crate::pin::Pin;
use crate::task::{Context, Poll};

/// Polls multiple futures simultaneously, returning a tuple
/// of all results once complete.
///
/// While `join!(a, b)` is similar to `(a.await, b.await)`,
/// `join!` polls both futures concurrently and is therefore more efficient.
///
/// # Examples
///
/// ```
/// #![feature(future_join, future_poll_fn)]
///
/// use std::future::join;
///
/// async fn one() -> usize { 1 }
/// async fn two() -> usize { 2 }
///
/// # let _ =  async {
/// let x = join!(one(), two()).await;
/// assert_eq!(x, (1, 2));
/// # };
/// ```
///
/// `join!` is variadic, so you can pass any number of futures:
///
/// ```
/// #![feature(future_join, future_poll_fn)]
///
/// use std::future::join;
///
/// async fn one() -> usize { 1 }
/// async fn two() -> usize { 2 }
/// async fn three() -> usize { 3 }
///
/// # let _ = async {
/// let x = join!(one(), two(), three()).await;
/// assert_eq!(x, (1, 2, 3));
/// # };
/// ```
#[unstable(feature = "future_join", issue = "91642")]
pub macro join {
    ( $($fut:expr),* $(,)?) => {
        join! { @count: (), @futures: {}, @rest: ($($fut,)*) }
    },
    // Recurse until we have the position of each future in the tuple
    (
        // A token for each future that has been expanded: "_ _ _"
        @count: ($($count:tt)*),
        // Futures and their positions in the tuple: "{ a => (_), b => (_ _)) }"
        @futures: { $($fut:tt)* },
        // Take a future from @rest to expand
        @rest: ($current:expr, $($rest:tt)*)
    ) => {
        join! {
            @count: ($($count)* _),
            @futures: { $($fut)* $current => ($($count)*), },
            @rest: ($($rest)*)
        }
    },
    // Now generate the output future
    (
        @count: ($($count:tt)*),
        @futures: {
            $( $(@$f:tt)? $fut:expr => ( $($pos:tt)* ), )*
        },
        @rest: ()
    ) => {
        async move {
            let mut futures = ( $( MaybeDone::Future($fut), )* );

            poll_fn(move |cx| {
                let mut done = true;

                $(
                    let ( $($pos,)* fut, .. ) = &mut futures;

                    // SAFETY: The futures are never moved
                    done &= unsafe { Pin::new_unchecked(fut).poll(cx).is_ready() };
                )*

                if done {
                    // Extract all the outputs
                    Poll::Ready(($({
                        let ( $($pos,)* fut, .. ) = &mut futures;

                        fut.take_output().unwrap()
                    }),*))
                } else {
                    Poll::Pending
                }
            }).await
        }
    }
}

/// Future used by `join!` that stores it's output to
/// be later taken and doesn't panic when polled after ready.
///
/// This type is public in a private module for use by the macro.
#[allow(missing_debug_implementations)]
#[unstable(feature = "future_join", issue = "91642")]
pub enum MaybeDone<F: Future> {
    Future(F),
    Done(F::Output),
    Took,
}

#[unstable(feature = "future_join", issue = "91642")]
impl<F: Future> MaybeDone<F> {
    pub fn take_output(&mut self) -> Option<F::Output> {
        match &*self {
            MaybeDone::Done(_) => match mem::replace(self, Self::Took) {
                MaybeDone::Done(val) => Some(val),
                _ => unreachable!(),
            },
            _ => None,
        }
    }
}

#[unstable(feature = "future_join", issue = "91642")]
impl<F: Future> Future for MaybeDone<F> {
    type Output = ();

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        // SAFETY: pinning in structural for `f`
        unsafe {
            match self.as_mut().get_unchecked_mut() {
                MaybeDone::Future(f) => match Pin::new_unchecked(f).poll(cx) {
                    Poll::Ready(val) => self.set(Self::Done(val)),
                    Poll::Pending => return Poll::Pending,
                },
                MaybeDone::Done(_) => {}
                MaybeDone::Took => unreachable!(),
            }
        }

        Poll::Ready(())
    }
}