1use async_trait::async_trait;
4use futures::FutureExt;
5use futures::future::RemoteHandle;
6use futures::stream::{FuturesUnordered, StreamExt};
7use futures::task::SpawnError;
8
9use std::any::Any;
10use std::panic::AssertUnwindSafe;
11
12use crate::traits::{JoinSet, SpawnExt};
13
14pub struct FuturesJoinSet<T: Send + Sync + 'static, R> {
16 runtime: R,
18 pending: FuturesUnordered<RemoteHandle<Result<T, Box<dyn Any + Send>>>>,
23}
24
25impl<T, R> FuturesJoinSet<T, R>
26where
27 T: Send + Sync + 'static,
28 R: SpawnExt + Send + Sync + 'static,
29{
30 pub fn new(runtime: R) -> Self {
32 Self {
33 runtime,
34 pending: Default::default(),
35 }
36 }
37}
38
39#[async_trait]
40impl<T, R> JoinSet<T> for FuturesJoinSet<T, R>
41where
42 T: Send + Sync + 'static,
43 R: SpawnExt + Send + Sync + 'static,
44{
45 fn spawn<F>(&mut self, task: F) -> Result<(), SpawnError>
46 where
47 F: Future<Output = T> + Send + 'static,
48 {
49 let handle = self
50 .runtime
51 .spawn_with_handle(AssertUnwindSafe(task).catch_unwind())?;
52 self.pending.push(handle);
53 Ok(())
54 }
55
56 async fn join_next(&mut self) -> Option<Result<T, Box<dyn Any + Send>>> {
57 self.pending.next().await
58 }
59}
60
61#[cfg(all(
63 test,
64 any(feature = "native-tls", feature = "rustls"),
65 any(feature = "tokio", feature = "async-std", feature = "smol"),
66 not(miri), ))]
68mod test {
69 #![allow(clippy::bool_assert_comparison)]
71 #![allow(clippy::clone_on_copy)]
72 #![allow(clippy::dbg_macro)]
73 #![allow(clippy::mixed_attributes_style)]
74 #![allow(clippy::print_stderr)]
75 #![allow(clippy::print_stdout)]
76 #![allow(clippy::single_char_pattern)]
77 #![allow(clippy::unwrap_used)]
78 #![allow(clippy::unchecked_time_subtraction)]
79 #![allow(clippy::useless_vec)]
80 #![allow(clippy::needless_pass_by_value)]
81 #![allow(clippy::string_slice)] use super::*;
85 use crate::test_with_all_runtimes;
86
87 #[test]
88 fn catch_unwinding_panics() {
89 test_with_all_runtimes!(|rt| async move {
90 let mut join_set = FuturesJoinSet::new(rt);
91
92 let task_results = (1..=10).collect::<Vec<_>>();
94 for res in task_results.clone() {
95 join_set
96 .spawn(async move {
97 res
99 })
100 .unwrap();
101 }
102
103 join_set
104 .spawn(async {
105 panic!("")
108 })
109 .unwrap();
110
111 let mut num_tasks = 0;
112 let mut actual = vec![];
113 while let Some(res) = join_set.join_next().await {
114 if let Ok(res) = res {
115 actual.push(res);
116 }
117 num_tasks += 1;
118 }
119 actual.sort();
120
121 assert_eq!(num_tasks, task_results.len() + 1);
122 assert_eq!(actual, task_results);
123 });
124 }
125}