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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
use std::panic;
use std::sync::Arc;
use std::time::{Instant, Duration};
use std::sync::atomic::{AtomicUsize, Ordering};
use cancel::Cancel;
use join::JoinHandle;
use may_queue::mpsc_list;
use scoped::spawn_unsafe;
use yield_now::yield_with;
use sync::{AtomicOption, Blocker};
use coroutine_impl::{Coroutine, CoroutineImpl, EventSource, run_coroutine, current_cancel_data};
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub enum PollError {
Timeout,
Finished,
}
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
enum EventKind {
Normal,
Done,
}
#[derive(Debug)]
pub struct Event {
pub tocken: usize,
pub extra: usize,
id: usize,
kind: EventKind,
co: Option<CoroutineImpl>,
}
impl Event {
fn continue_bottom(&mut self) {
self.co.take().map(run_coroutine);
}
}
pub struct Selector {
co: Coroutine,
}
impl Selector {
pub fn remove(self) {
unsafe { self.co.cancel() };
}
}
pub struct EventSender<'a> {
id: usize,
tocken: usize,
extra: usize,
cqueue: &'a Cqueue,
}
impl<'a> EventSender<'a> {
pub fn get_tocken(&self) -> usize {
self.tocken
}
pub fn send(&self, extra: usize) {
let cancel = current_cancel_data();
cancel.check_cancel();
let me = unsafe { &mut *(self as *const _ as *mut Self) };
me.extra = extra;
yield_with(self);
}
}
impl<'a> EventSource for EventSender<'a> {
fn subscribe(&mut self, co: CoroutineImpl) {
self.cqueue.ev_queue.push(Event {
id: self.id,
tocken: self.tocken,
extra: self.extra,
kind: EventKind::Normal,
co: Some(co),
});
self.cqueue.to_wake.take(Ordering::Acquire).map(|w| w.unpark());
}
fn yield_back(&self, _cancel: &'static Cancel) {
}
}
impl<'a> Drop for EventSender<'a> {
fn drop(&mut self) {
self.cqueue.ev_queue.push(Event {
id: self.id,
tocken: self.tocken,
extra: self.extra,
kind: EventKind::Done,
co: None,
});
self.cqueue.cnt.fetch_sub(1, Ordering::Relaxed);
self.cqueue.to_wake.take(Ordering::Acquire).map(|w| w.unpark());
}
}
pub struct Cqueue {
ev_queue: mpsc_list::Queue<Event>,
to_wake: AtomicOption<Arc<Blocker>>,
cnt: AtomicUsize,
selectors: Vec<Option<JoinHandle<()>>>,
total: usize,
is_panicking: bool,
}
unsafe impl Sync for Cqueue {}
impl Cqueue {
pub fn add<'a, F>(&self, tocken: usize, f: F) -> Selector
where F: FnOnce(EventSender) + Send + 'a
{
let sender = EventSender {
id: self.total,
tocken: tocken,
extra: 0,
cqueue: self,
};
let h = unsafe { spawn_unsafe(move || f(sender)) };
let co = h.coroutine().clone();
self.cnt.fetch_add(1, Ordering::Relaxed);
let me = unsafe { &mut *(self as *const _ as *mut Self) };
me.total += 1;
me.selectors.push(Some(h));
Selector { co: co }
}
fn check_panic(&self, id: usize) {
if self.is_panicking {
return;
}
use generator::Error;
let me = unsafe { &mut *(self as *const _ as *mut Self) };
match me.selectors[id].take().expect("join handler not set").join() {
Ok(_) => {}
Err(panic) => {
if let Some(err) = panic.downcast_ref::<Error>() {
if *err == Error::Cancel {
return;
}
}
me.is_panicking = true;
panic::resume_unwind(panic);
}
}
}
pub fn poll(&self, timeout: Option<Duration>) -> Result<Event, PollError> {
macro_rules! run_ev {
($ev:ident) => ({
if $ev.kind == EventKind::Done {
self.check_panic($ev.id);
continue;
}
$ev.continue_bottom();
return Ok($ev);
})
}
let deadline = timeout.map(|dur| Instant::now() + dur);
loop {
match self.ev_queue.pop() {
Some(mut ev) => run_ev!(ev),
None if self.cnt.load(Ordering::Relaxed) == 0 => return Err(PollError::Finished),
_ => {}
}
let cur = Blocker::current();
self.to_wake.swap(cur.clone(), Ordering::Release);
match self.ev_queue.pop() {
None => {
cur.park(timeout).ok();
}
Some(mut ev) => {
self.to_wake.take(Ordering::Relaxed).map(|w| w.unpark());
cur.park(timeout).ok();
run_ev!(ev);
}
}
match deadline {
Some(d) if Instant::now() >= d => return Err(PollError::Timeout),
_ => {}
}
}
}
}
impl Drop for Cqueue {
fn drop(&mut self) {
self.selectors.iter().map(|j| j.as_ref()).fold((), |_, join| {
match join {
Some(j) if !j.is_done() => unsafe { j.coroutine().cancel() },
_ => {}
}
});
loop {
match self.poll(None) {
Ok(_) => {}
Err(_e @ PollError::Finished) => break,
_ => unreachable!("cqueue drop unreachable"),
}
}
}
}
pub fn scope<'a, F, R>(f: F) -> R
where F: FnOnce(&Cqueue) -> R + 'a
{
let cqueue = Cqueue {
ev_queue: mpsc_list::Queue::new(),
to_wake: AtomicOption::none(),
cnt: AtomicUsize::new(0),
selectors: Vec::new(),
total: 0,
is_panicking: false,
};
f(&cqueue)
}
#[macro_export]
macro_rules! cqueue_add{
(
$cqueue:ident, $tocken:expr, $name:pat = $top:expr => $bottom:expr
) => ({
$cqueue.add($tocken, |es| {
loop {
let $name = $top;
es.send(es.get_tocken());
$bottom
}
})
})
}
#[macro_export]
macro_rules! cqueue_add_oneshot{
(
$cqueue:ident, $tocken:expr, $name:pat = $top:expr => $bottom:expr
) => ({
$cqueue.add($tocken, |es| {
let $name = $top;
es.send(es.get_tocken());
$bottom
})
})
}
#[macro_export]
macro_rules! select {
(
$($name:pat = $top:expr => $bottom:expr),+
) => ({
use $crate::cqueue;
cqueue::scope(|cqueue| {
let mut _tocken = 0;
$(
cqueue_add_oneshot!(cqueue, _tocken, $name = $top => $bottom);
_tocken += 1;
)+
match cqueue.poll(None) {
Ok(ev) => return ev.tocken,
_ => unreachable!("select error"),
}
})
})
}