1 use crate::future::{Either, TryFutureExt};
2 use core::pin::Pin;
3 use futures_core::future::{Future, TryFuture};
4 use futures_core::task::{Context, Poll};
5 
6 /// Future for the [`try_select()`] function.
7 #[must_use = "futures do nothing unless you `.await` or poll them"]
8 #[derive(Debug)]
9 pub struct TrySelect<A, B> {
10     inner: Option<(A, B)>,
11 }
12 
13 impl<A: Unpin, B: Unpin> Unpin for TrySelect<A, B> {}
14 
15 type EitherOk<A, B> = Either<(<A as TryFuture>::Ok, B), (<B as TryFuture>::Ok, A)>;
16 type EitherErr<A, B> = Either<(<A as TryFuture>::Error, B), (<B as TryFuture>::Error, A)>;
17 
18 /// Waits for either one of two differently-typed futures to complete.
19 ///
20 /// This function will return a new future which awaits for either one of both
21 /// futures to complete. The returned future will finish with both the value
22 /// resolved and a future representing the completion of the other work.
23 ///
24 /// Note that this function consumes the receiving futures and returns a
25 /// wrapped version of them.
26 ///
27 /// Also note that if both this and the second future have the same
28 /// success/error type you can use the `Either::factor_first` method to
29 /// conveniently extract out the value at the end.
30 ///
31 /// # Examples
32 ///
33 /// ```
34 /// use futures::future::{self, Either, Future, FutureExt, TryFuture, TryFutureExt};
35 ///
36 /// // A poor-man's try_join implemented on top of select
37 ///
38 /// fn try_join<A, B, E>(a: A, b: B) -> impl TryFuture<Ok=(A::Ok, B::Ok), Error=E>
39 ///      where A: TryFuture<Error = E> + Unpin + 'static,
40 ///            B: TryFuture<Error = E> + Unpin + 'static,
41 ///            E: 'static,
42 /// {
43 ///     future::try_select(a, b).then(|res| -> Box<dyn Future<Output = Result<_, _>> + Unpin> {
44 ///         match res {
45 ///             Ok(Either::Left((x, b))) => Box::new(b.map_ok(move |y| (x, y))),
46 ///             Ok(Either::Right((y, a))) => Box::new(a.map_ok(move |x| (x, y))),
47 ///             Err(Either::Left((e, _))) => Box::new(future::err(e)),
48 ///             Err(Either::Right((e, _))) => Box::new(future::err(e)),
49 ///         }
50 ///     })
51 /// }
52 /// ```
try_select<A, B>(future1: A, future2: B) -> TrySelect<A, B> where A: TryFuture + Unpin, B: TryFuture + Unpin,53 pub fn try_select<A, B>(future1: A, future2: B) -> TrySelect<A, B>
54 where
55     A: TryFuture + Unpin,
56     B: TryFuture + Unpin,
57 {
58     super::assert_future::<Result<EitherOk<A, B>, EitherErr<A, B>>, _>(TrySelect {
59         inner: Some((future1, future2)),
60     })
61 }
62 
63 impl<A: Unpin, B: Unpin> Future for TrySelect<A, B>
64 where
65     A: TryFuture,
66     B: TryFuture,
67 {
68     type Output = Result<EitherOk<A, B>, EitherErr<A, B>>;
69 
poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>70     fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
71         let (mut a, mut b) = self.inner.take().expect("cannot poll Select twice");
72         match a.try_poll_unpin(cx) {
73             Poll::Ready(Err(x)) => Poll::Ready(Err(Either::Left((x, b)))),
74             Poll::Ready(Ok(x)) => Poll::Ready(Ok(Either::Left((x, b)))),
75             Poll::Pending => match b.try_poll_unpin(cx) {
76                 Poll::Ready(Err(x)) => Poll::Ready(Err(Either::Right((x, a)))),
77                 Poll::Ready(Ok(x)) => Poll::Ready(Ok(Either::Right((x, a)))),
78                 Poll::Pending => {
79                     self.inner = Some((a, b));
80                     Poll::Pending
81                 }
82             },
83         }
84     }
85 }
86