Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide an or! macro that handles any number of futures #7

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions src/future.rs
Original file line number Diff line number Diff line change
Expand Up @@ -670,3 +670,42 @@ where
Poll::Pending
}
}

// Helper for `or!`
#[doc(hidden)]
#[macro_export]
macro_rules! __internal_fold_with {
($func:path, $e:expr) => { $e };
($func:path, $e:expr, $($es:expr),+) => {
$func($e, $crate::__internal_fold_with!($func, $($es),+))
};
}

/// Like `FutureExt::or()`, but accepts an arbitrary number of futures rather than just
/// two. Returns the result of the first future to complete; if multiple futures complete at the
/// same time, returns the first one to complete. All of the futures must have the same return
/// type.
///
/// You can call this as either `or_futures!` or `future::or!`.
///
/// # Examples
///
/// ```
/// use futures_lite::future::{self, pending, ready};
///
/// # future::block_on(async {
/// assert_eq!(future::or!(ready(1)).await, 1);
/// assert_eq!(future::or!(pending(), ready(2)).await, 2);
/// assert_eq!(future::or!(pending(), pending(), ready(3)).await, 3);
///
/// // The first future wins.
/// assert_eq!(future::or!(ready(1), ready(2), ready(3)).await, 1);
/// # })
/// ```
#[macro_export]
macro_rules! or_futures {
($($es:expr),+$(,)?) => { $crate::__internal_fold_with!($crate::future::FutureExt::or, $($es),+) };
}

#[doc(inline)]
pub use crate::or_futures as or;