From 56021bbd6adc33743f605ff3f52479b2a7e7beea Mon Sep 17 00:00:00 2001 From: Erik Desjardins Date: Mon, 22 Jan 2024 22:16:53 -0500 Subject: [PATCH] task: implement `FromIterator` for `JoinSet` --- tokio/src/task/join_set.rs | 43 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/tokio/src/task/join_set.rs b/tokio/src/task/join_set.rs index 7aace14d850..c9251db86d7 100644 --- a/tokio/src/task/join_set.rs +++ b/tokio/src/task/join_set.rs @@ -526,6 +526,49 @@ impl Default for JoinSet { } } +/// Collect an iterator of futures into a [`JoinSet`]. +/// +/// This is equivalent to calling [`JoinSet::spawn`] on each element of the iterator. +/// +/// # Examples +/// +/// The main example from [`JoinSet`]'s documentation can also be written using [`collect`]: +/// +/// ``` +/// use tokio::task::JoinSet; +/// +/// #[tokio::main] +/// async fn main() { +/// let mut set: JoinSet<_> = (0..10).map(|i| async move { i }).collect(); +/// +/// let mut seen = [false; 10]; +/// while let Some(res) = set.join_next().await { +/// let idx = res.unwrap(); +/// seen[idx] = true; +/// } +/// +/// for i in 0..10 { +/// assert!(seen[i]); +/// } +/// } +/// ``` +/// +/// [`collect`]: std::iter::Iterator::collect +impl std::iter::FromIterator for JoinSet +where + F: Future, + F: Send + 'static, + T: Send + 'static, +{ + fn from_iter>(iter: I) -> Self { + let mut set = Self::new(); + iter.into_iter().for_each(|task| { + set.spawn(task); + }); + set + } +} + // === impl Builder === #[cfg(all(tokio_unstable, feature = "tracing"))]