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
//! Context-tagged task set and abort-on-drop guard.
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::task::{AbortHandle, JoinError, JoinHandle, JoinSet};
/// A `JoinSet` whose tasks carry a caller-supplied context label.
///
/// Dropping the set aborts every remaining task.
pub struct WorkSet<C, T> {
tasks: JoinSet<T>,
contexts: HashMap<tokio::task::Id, C>,
}
impl<C: Send + 'static, T: Send + 'static> Default for WorkSet<C, T> {
fn default() -> Self {
Self::new()
}
}
impl<C: Send + 'static, T: Send + 'static> WorkSet<C, T> {
pub fn new() -> Self {
Self {
tasks: JoinSet::new(),
contexts: HashMap::new(),
}
}
/// Spawn a task tagged with `context`; the returned handle aborts it.
pub fn spawn<F>(&mut self, context: C, future: F) -> AbortHandle
where
F: Future<Output = T> + Send + 'static,
{
let handle = self.tasks.spawn(future);
self.contexts.insert(handle.id(), context);
handle
}
/// Await the next finished task together with its context.
///
/// Cancel safe: dropping this future does not lose tasks.
pub async fn next(&mut self) -> Option<(C, Result<T, JoinError>)> {
let joined = self.tasks.join_next_with_id().await?;
match joined {
Ok((id, value)) => Some((
self.contexts.remove(&id).expect("workset context"),
Ok(value),
)),
Err(error) => {
let id = error.id();
Some((
self.contexts.remove(&id).expect("workset context"),
Err(error),
))
}
}
}
pub fn len(&self) -> usize {
self.tasks.len()
}
pub fn is_empty(&self) -> bool {
self.tasks.is_empty()
}
pub fn abort_all(&mut self) {
self.tasks.abort_all();
}
}
// No custom `Drop`: `JoinSet` already aborts every remaining task when the set
// is dropped, and a custom Drop impl would force `C`/`T: 'static` bounds on the
// struct itself.
/// A task handle that aborts its task when dropped.
pub struct AbortOnDrop<T> {
handle: JoinHandle<T>,
}
impl<T: Send + 'static> AbortOnDrop<T> {
pub fn new(handle: JoinHandle<T>) -> Self {
Self { handle }
}
pub fn spawn<F>(future: F) -> Self
where
F: Future<Output = T> + Send + 'static,
{
Self::new(tokio::spawn(future))
}
pub fn abort(&self) {
self.handle.abort();
}
}
impl<T> Drop for AbortOnDrop<T> {
fn drop(&mut self) {
self.handle.abort();
}
}
impl<T> Future for AbortOnDrop<T> {
type Output = Result<T, JoinError>;
fn poll(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
Pin::new(&mut self.handle).poll(context)
}
}