|
| 1 | +#![allow(non_snake_case)] |
| 2 | + |
| 3 | +/// Waits for either one of several similarly-typed futures to complete. |
| 4 | +/// Awaits multiple futures simultaneously, returning all results once complete. |
| 5 | +/// |
| 6 | +/// `try_select!` is similar to [`select!`], but keeps going if a future |
| 7 | +/// resolved to an error until all futures have been resolved. In which case |
| 8 | +/// the last error found will be returned. |
| 9 | +/// |
| 10 | +/// This macro is only usable inside of async functions, closures, and blocks. |
| 11 | +/// |
| 12 | +/// # Examples |
| 13 | +/// |
| 14 | +/// ``` |
| 15 | +/// # futures::executor::block_on(async { |
| 16 | +/// # async fn main() -> Result<(), std::io::Error> { |
| 17 | +/// use async_macros::try_select; |
| 18 | +/// use futures::future; |
| 19 | +/// use std::io::{Error, ErrorKind}; |
| 20 | +/// |
| 21 | +/// let a = future::pending::<Result<u8, Error>>(); |
| 22 | +/// let b = future::ready(Err(Error::from(ErrorKind::Other))); |
| 23 | +/// let c = future::ready(Ok(1u8)); |
| 24 | +/// |
| 25 | +/// assert_eq!(try_select!(a, b, c).await?, 1u8); |
| 26 | +/// # Ok(()) |
| 27 | +/// # } |
| 28 | +/// # main().await.unwrap(); |
| 29 | +/// # }); |
| 30 | +/// ``` |
| 31 | +#[macro_export] |
| 32 | +macro_rules! try_select { |
| 33 | + ($($fut:ident),* $(,)?) => { { |
| 34 | + async { |
| 35 | + $( |
| 36 | + // Move future into a local so that it is pinned in one place and |
| 37 | + // is no longer accessible by the end user. |
| 38 | + let mut $fut = $crate::maybe_done($fut); |
| 39 | + )* |
| 40 | + $crate::utils::poll_fn(move |cx| { |
| 41 | + use $crate::utils::future::Future; |
| 42 | + use $crate::utils::task::Poll; |
| 43 | + use $crate::utils::pin::Pin; |
| 44 | + |
| 45 | + let mut all_done = true; |
| 46 | + |
| 47 | + $( |
| 48 | + let fut = unsafe { Pin::new_unchecked(&mut $fut) }; |
| 49 | + if Future::poll(fut, cx).is_ready() { |
| 50 | + let fut = Pin::new(&$fut); |
| 51 | + if fut.output().unwrap().is_ok() { |
| 52 | + let fut = unsafe { Pin::new_unchecked(&mut $fut) }; |
| 53 | + let output = fut.take_output().unwrap(); |
| 54 | + return Poll::Ready(output); |
| 55 | + } |
| 56 | + } |
| 57 | + )* |
| 58 | + |
| 59 | + if all_done { |
| 60 | + unimplemented!(); |
| 61 | + } else { |
| 62 | + Poll::Pending |
| 63 | + } |
| 64 | + }).await |
| 65 | + } |
| 66 | + } } |
| 67 | +} |
0 commit comments