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
174
use std::pin::Pin;
use std::task::{Context, Poll};
use futures::{Future, FutureExt, Stream};
use futures::stream::FuturesUnordered;
use futures::channel::mpsc;
use std::cell::{RefCell};
use std::rc::Rc;
enum EnqueuedTask<E> {
Task(Pin<Box<dyn Future<Output=Result<(), E>>>>),
Terminate(Result<(), E>),
}
enum TaskInProgress<E> {
Task(Pin<Box<dyn Future<Output=()>>>),
Terminate(Option<Result<(), E>>),
}
impl <E> Unpin for TaskInProgress<E> {}
enum TaskDone<E> {
Continue,
Terminate(Result<(), E>),
}
impl <E> Future for TaskInProgress<E> {
type Output = TaskDone<E>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
match *self {
TaskInProgress::Terminate(ref mut r) =>
Poll::Ready(TaskDone::Terminate(r.take().unwrap())),
TaskInProgress::Task(ref mut f) => {
match f.as_mut().poll(cx) {
Poll::Pending => Poll::Pending,
Poll::Ready(()) => Poll::Ready(TaskDone::Continue),
}
}
}
}
}
#[must_use = "a TaskSet does nothing unless polled"]
pub struct TaskSet<E> {
enqueued: Option<mpsc::UnboundedReceiver<EnqueuedTask<E>>>,
in_progress: FuturesUnordered<TaskInProgress<E>>,
reaper: Rc<RefCell<Box<dyn TaskReaper<E>>>>,
}
impl<E> TaskSet<E> where E: 'static {
pub fn new(reaper: Box<dyn TaskReaper<E>>)
-> (TaskSetHandle<E>, TaskSet<E>)
where E: 'static, E: ::std::fmt::Debug,
{
let (sender, receiver) = mpsc::unbounded();
let set = TaskSet {
enqueued: Some(receiver),
in_progress: FuturesUnordered::new(),
reaper: Rc::new(RefCell::new(reaper)),
};
set.in_progress.push(TaskInProgress::Task(Box::pin(::futures::future::pending())));
let handle = TaskSetHandle {
sender: sender,
};
(handle, set)
}
}
#[derive(Clone)]
pub struct TaskSetHandle<E> {
sender: mpsc::UnboundedSender<EnqueuedTask<E>>
}
impl <E> TaskSetHandle<E> where E: 'static {
pub fn add<F>(&mut self, f: F)
where F: Future<Output = Result<(), E>> + 'static
{
let _ = self.sender.unbounded_send(EnqueuedTask::Task(Box::pin(f)));
}
pub fn terminate(&mut self, result: Result<(), E>) {
let _ = self.sender.unbounded_send(EnqueuedTask::Terminate(result));
}
}
pub trait TaskReaper<E> where E: 'static
{
fn task_succeeded(&mut self) {}
fn task_failed(&mut self, error: E);
}
impl <E> Future for TaskSet<E> where E: 'static {
type Output = Result<(),E>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let mut enqueued_stream_complete = false;
if let TaskSet { enqueued: Some(ref mut enqueued), ref mut in_progress, ref reaper, ..} = self.as_mut().get_mut() {
loop {
match Pin::new(&mut *enqueued).poll_next(cx) {
Poll::Pending => break,
Poll::Ready(None) => {
enqueued_stream_complete = true;
break;
}
Poll::Ready(Some(EnqueuedTask::Terminate(r))) => {
in_progress.push(TaskInProgress::Terminate(Some(r)));
}
Poll::Ready(Some(EnqueuedTask::Task(f))) => {
let reaper = Rc::downgrade(&reaper);
in_progress.push(
TaskInProgress::Task(Box::pin(
f.map(move |r| {
match reaper.upgrade() {
None => (),
Some(rc_reaper) => {
match r {
Ok(()) => rc_reaper.borrow_mut().task_succeeded(),
Err(e) => rc_reaper.borrow_mut().task_failed(e),
}
}
}
}))));
}
}
}
}
if enqueued_stream_complete {
drop(self.enqueued.take());
}
loop {
match Stream::poll_next(Pin::new(&mut self.in_progress), cx) {
Poll::Pending => return Poll::Pending,
Poll::Ready(v) => {
match v {
None => return Poll::Ready(Ok(())),
Some(TaskDone::Continue) => (),
Some(TaskDone::Terminate(Ok(()))) =>
return Poll::Ready(Ok(())),
Some(TaskDone::Terminate(Err(e))) => return Poll::Ready(Err(e)),
}
}
}
}
}
}