1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
use crate::channel;
use crate::prelude::*;
use crate::string::SharedString;
use crate::task::{self, Task};
use fnv::FnvHashMap;
pub type Index = usize;
pub struct Join<T> {
children: FnvHashMap<Index, Child>,
next_index: Index,
rx: channel::Receiver<Stopped<T>>,
tx: channel::Sender<Stopped<T>>,
}
struct Child {
name: SharedString,
_monitor: Task<()>,
}
struct Stopped<T> {
index: usize,
result: Result<T, Panic>,
}
impl<T> Join<T>
where
T: Send + 'static,
{
pub fn new() -> Self {
let (tx, rx) = channel::unbounded();
Self { children: default(), next_index: 0, rx, tx }
}
pub fn add(&mut self, task: impl task::Start<T>) -> Index {
self.add_as("", task)
}
pub fn add_as(&mut self, name: impl Into<SharedString>, task: impl task::Start<T>) -> Index {
let index = self.next_index;
self.next_index += 1;
let task = task.start();
let tx = self.tx.clone();
let _monitor = task::start(async move {
let result = task.join().await;
tx.send(Stopped { index, result }).await.ok();
});
self.children.insert(index, Child { name: name.into(), _monitor });
index
}
pub async fn next(&mut self) -> Option<StoppedTask<Result<T, task::Panic>>> {
if self.children.is_empty() {
return None;
}
let Stopped { index, result } = self.rx.recv().await.ok()?;
let child = self.children.remove(&index).expect("Received result from unknown child.");
Some(StoppedTask { index, name: child.name, result })
}
pub async fn try_next(&mut self) -> Option<Result<StoppedTask<T>, PanickedTask>> {
if self.children.is_empty() {
return None;
}
let Stopped { index, result } = self.rx.recv().await.ok()?;
let child = self.children.remove(&index).expect("Received result from unknown child.");
Some(match result {
Ok(result) => Ok(StoppedTask { index, name: child.name, result }),
Err(panic) => Err(PanickedTask { index, name: child.name, panic }),
})
}
pub async fn drain(&mut self) {
while self.next().await.is_some() {}
}
pub async fn try_drain(&mut self) -> Result<(), PanickedTask> {
while self.try_next().await.transpose()?.is_some() {}
Ok(())
}
}
impl<T> Default for Join<T>
where
T: Send + 'static,
{
fn default() -> Self {
Self::new()
}
}
#[derive(Debug)]
pub struct StoppedTask<T> {
pub index: Index,
pub name: SharedString,
pub result: T,
}
#[derive(Debug, Error)]
pub struct PanickedTask {
pub index: Index,
pub name: SharedString,
pub panic: task::Panic,
}
impl Display for PanickedTask {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.name.as_str() {
"" => write!(f, "Task #{} ", self.index)?,
name => write!(f, "Task `{}`", name)?,
}
write!(f, "panicked")?;
if let Some(value) = self.panic.value_str() {
write!(f, " with `{}`", value)?;
}
write!(f, ".")
}
}