-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathasymmetric.rs
563 lines (463 loc) · 15.2 KB
/
asymmetric.rs
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
// The MIT License (MIT)
// Copyright (c) 2015 Y. T. Chung <[email protected]>
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//! Asymmetric coroutines
use std::fmt;
use std::usize;
use std::panic;
use std::mem;
use std::iter::Iterator;
use std::any::Any;
use context::{Context, Transfer};
use context::stack::ProtectedFixedSizeStack;
use options::Options;
#[derive(Debug)]
struct ForceUnwind;
trait FnBox {
fn call_box(self: Box<Self>, meta_ref: &mut Coroutine, data: usize) -> usize;
}
impl<F: FnOnce(&mut Coroutine, usize) -> usize> FnBox for F {
fn call_box(self: Box<F>, meta_ref: &mut Coroutine, data: usize) -> usize {
(*self)(meta_ref, data)
}
}
type Thunk<'a> = Box<FnBox + 'a>;
struct InitData {
stack: ProtectedFixedSizeStack,
callback: Thunk<'static>,
}
extern "C" fn coroutine_entry(t: Transfer) -> ! {
// Take over the data from Coroutine::spawn_opts
let InitData { stack, callback } = unsafe {
let data_opt_ref = &mut *(t.data as *mut Option<InitData>);
data_opt_ref.take().expect("failed to acquire InitData")
};
// This block will ensure the `meta` will be destroied before dropping the stack
let (ctx, result) = {
let mut meta = Coroutine {
context: None,
name: None,
state: State::Suspended,
panicked_error: None,
};
// Yield back after take out the callback function
// Now the Coroutine is initialized
let meta_ptr = &mut meta as *mut _ as usize;
let result = unsafe {
::try(move || {
let Transfer { context, data } = t.context.resume(meta_ptr);
let meta_ref = &mut *(meta_ptr as *mut Coroutine);
meta_ref.context = Some(context);
// Take out the callback and run it
// let result = callback.call_box((meta_ref, data));
let result = callback.call_box(meta_ref, data);
trace!("Coroutine `{}`: returned from callback with result {}",
meta_ref.debug_name(),
result);
result
})
};
let mut loc_data = match result {
Ok(d) => {
meta.state = State::Finished;
d
}
Err(err) => {
if err.is::<ForceUnwind>() {
meta.state = State::Finished
} else {
meta.state = State::Panicked;
meta.panicked_error = Some(err);
}
usize::MAX
}
};
trace!("Coroutine `{}`: exited with {:?}",
meta.debug_name(),
meta.state);
loop {
let Transfer { context, data } = meta.context.take().unwrap().resume(loc_data);
meta.context = Some(context);
loc_data = data;
if meta.state == State::Finished {
break;
}
}
trace!("Coroutine `{}`: finished => dropping stack",
meta.debug_name());
// If panicked inside, the meta.context stores the actual return Context
(meta.take_context(), loc_data)
};
// Drop the stack after it is finished
let mut stack_opt = Some((stack, result));
ctx.resume_ontop(&mut stack_opt as *mut _ as usize, coroutine_exit);
unreachable!();
}
extern "C" fn coroutine_exit(mut t: Transfer) -> Transfer {
let data = unsafe {
// Drop the stack
let stack_ref = &mut *(t.data as *mut Option<(ProtectedFixedSizeStack, usize)>);
let (_, result) = stack_ref.take().unwrap();
result
};
t.data = data;
t.context = unsafe { mem::transmute(0usize) };
t
}
extern "C" fn coroutine_unwind(t: Transfer) -> Transfer {
// Save the Context in the Coroutine object
// because the `t` won't be able to be passed to the caller
let coro = unsafe { &mut *(t.data as *mut Coroutine) };
coro.context = Some(t.context);
trace!("Coroutine `{}`: unwinding", coro.debug_name());
panic::resume_unwind(Box::new(ForceUnwind));
}
/// Coroutine state
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum State {
/// Suspended state (yield from coroutine inside, ready for resume).
Suspended,
/// Running state (executing in callback).
Running,
/// Parked state. Similar to `Suspended` state, but `Suspended` is representing that coroutine
/// will be waken up (resume) by scheduler automatically. Coroutines in `Parked` state should
/// be waken up manually.
Parked,
/// Coroutine is finished and internal data has been destroyed.
Finished,
/// Coroutine is panicked inside.
Panicked,
}
/// Coroutine context representation
#[derive(Debug)]
pub struct Coroutine {
context: Option<Context>,
name: Option<String>,
state: State,
panicked_error: Option<Box<Any + Send + 'static>>,
}
impl Coroutine {
/// Spawn a coroutine with `Options`
#[inline]
pub fn spawn_opts<F>(f: F, opts: Options) -> Handle
where F: FnOnce(&mut Coroutine, usize) -> usize + 'static
{
Self::spawn_opts_impl(Box::new(f) as Thunk<'static>, opts)
}
/// Spawn a coroutine with default options
#[inline]
pub fn spawn<F>(f: F) -> Handle
where F: FnOnce(&mut Coroutine, usize) -> usize + 'static
{
Self::spawn_opts_impl(Box::new(f), Options::default())
}
fn spawn_opts_impl(f: Thunk<'static>, opts: Options) -> Handle {
let data = InitData {
stack: ProtectedFixedSizeStack::new(opts.stack_size).expect("failed to acquire stack"),
callback: f,
};
let context = Context::new(&data.stack, coroutine_entry);
// Give him the initialization data
let mut data_opt = Some(data);
let t = context.resume(&mut data_opt as *mut _ as usize);
debug_assert!(data_opt.is_none());
let coro_ref = unsafe { &mut *(t.data as *mut Coroutine) };
coro_ref.context = Some(t.context);
if let Some(name) = opts.name {
coro_ref.set_name(name);
}
// Done!
Handle(coro_ref)
}
fn take_context(&mut self) -> Context {
self.context.take().unwrap()
}
/// Gets state of Coroutine
#[inline]
pub fn state(&self) -> State {
self.state
}
/// Gets name of Coroutine
#[inline]
pub fn name(&self) -> Option<&String> {
self.name.as_ref()
}
/// Set name of Coroutine
#[inline]
pub fn set_name(&mut self, name: String) {
self.name = Some(name);
}
/// Name for debugging
#[inline]
pub fn debug_name(&self) -> String {
match self.name {
Some(ref name) => name.clone(),
None => format!("{:p}", self),
}
}
#[inline(never)]
fn inner_yield_with_state(&mut self, state: State, data: usize) -> usize {
let context = self.take_context();
trace!("Coroutine `{}`: yielding to {:?}",
self.debug_name(),
&context);
self.state = state;
let Transfer { context, data } = context.resume(data);
if unsafe { mem::transmute_copy::<_, usize>(&context) } != 0usize {
self.context = Some(context);
}
data
}
#[inline]
fn yield_with_state(&mut self, state: State, data: usize) -> ::Result<usize> {
let data = self.inner_yield_with_state(state, data);
if self.state() == State::Panicked {
match self.panicked_error.take() {
Some(err) => Err(::Error::Panicking(err)),
None => Err(::Error::Panicked),
}
} else {
Ok(data)
}
}
/// Yield the current coroutine with `Suspended` state
#[inline]
pub fn yield_with(&mut self, data: usize) -> usize {
self.inner_yield_with_state(State::Suspended, data)
}
/// Yield the current coroutine with `Parked` state
#[inline]
pub fn park_with(&mut self, data: usize) -> usize {
self.inner_yield_with_state(State::Parked, data)
}
fn force_unwind(&mut self) {
trace!("Coroutine `{}`: force unwinding", self.debug_name());
let ctx = self.take_context();
let Transfer { context, .. } =
ctx.resume_ontop(self as *mut Coroutine as usize, coroutine_unwind);
self.context = Some(context);
trace!("Coroutine `{}`: force unwound", self.debug_name());
}
}
/// Handle for a Coroutine
#[derive(Eq, PartialEq)]
pub struct Handle(*mut Coroutine);
impl Handle {
#[doc(hidden)]
#[inline]
pub fn into_raw(self) -> *mut Coroutine {
let coro = self.0;
mem::forget(self);
coro
}
#[doc(hidden)]
#[inline]
pub unsafe fn from_raw(coro: *mut Coroutine) -> Handle {
assert!(!coro.is_null());
Handle(coro)
}
/// Check if the Coroutine is already finished
#[inline]
pub fn is_finished(&self) -> bool {
match self.state() {
State::Finished | State::Panicked => true,
_ => false,
}
}
#[inline]
fn yield_with_state(&mut self, state: State, data: usize) -> ::Result<usize> {
let coro = unsafe { &mut *self.0 };
coro.yield_with_state(state, data)
}
/// Resume the Coroutine
#[inline]
pub fn resume(&mut self, data: usize) -> ::Result<usize> {
assert!(!self.is_finished());
self.yield_with_state(State::Running, data)
}
/// Gets state of Coroutine
#[inline]
pub fn state(&self) -> State {
let coro = unsafe { &*self.0 };
coro.state()
}
/// Gets name of Coroutine
#[inline]
pub fn name(&self) -> Option<&String> {
let coro = unsafe { &*self.0 };
coro.name()
}
/// Set name of Coroutine
#[inline]
pub fn set_name(&mut self, name: String) {
let coro = unsafe { &mut *self.0 };
coro.set_name(name)
}
/// Name for debugging
#[inline]
pub fn debug_name(&self) -> String {
let coro = unsafe { &*self.0 };
coro.debug_name()
}
}
impl Drop for Handle {
fn drop(&mut self) {
trace!("Coroutine `{}`: dropping with {:?}",
self.debug_name(),
self.state());
let coro = unsafe { &mut *self.0 };
if !self.is_finished() {
coro.force_unwind()
}
coro.inner_yield_with_state(State::Finished, 0);
}
}
impl fmt::Debug for Handle {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.is_finished() {
write!(f, "Coroutine(None, Finished)")
} else {
write!(f,
"Coroutine(Some({}), {:?})",
self.debug_name(),
self.state())
}
}
}
impl Iterator for Handle {
type Item = ::Result<usize>;
fn next(&mut self) -> Option<Self::Item> {
if self.is_finished() {
None
} else {
let x = self.resume(0);
Some(x)
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn generator() {
let coro = Coroutine::spawn(|coro, _| {
for i in 0..10 {
coro.yield_with(i);
}
10
});
let ret = coro.map(|x| x.unwrap()).collect::<Vec<usize>>();
assert_eq!(&ret[..], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
}
#[test]
fn yield_data() {
let mut coro = Coroutine::spawn(|coro, data| coro.yield_with(data));
assert_eq!(coro.resume(0).unwrap(), 0);
assert_eq!(coro.resume(1).unwrap(), 1);
assert!(coro.is_finished());
}
#[test]
fn force_unwinding() {
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
struct Guard {
inner: Arc<AtomicUsize>,
}
impl Drop for Guard {
fn drop(&mut self) {
self.inner.fetch_add(1, Ordering::SeqCst);
}
}
let orig = Arc::new(AtomicUsize::new(0));
{
let pass = orig.clone();
let mut coro = Coroutine::spawn(move |coro, _| {
let _guard = Guard { inner: pass.clone() };
coro.yield_with(0);
let _guard2 = Guard { inner: pass };
0
});
let _ = coro.resume(0);
// Let it drop
}
assert_eq!(orig.load(Ordering::SeqCst), 1);
}
#[test]
fn unwinding() {
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
struct Guard {
inner: Arc<AtomicUsize>,
}
impl Drop for Guard {
fn drop(&mut self) {
self.inner.fetch_add(1, Ordering::SeqCst);
}
}
let orig = Arc::new(AtomicUsize::new(0));
{
let pass = orig.clone();
let mut coro = Coroutine::spawn(move |_, _| {
let _guard = Guard { inner: pass.clone() };
panic!("111");
});
let _ = coro.resume(0);
// Let it drop
}
assert_eq!(orig.load(Ordering::SeqCst), 1);
}
#[test]
#[should_panic]
fn resume_after_finished() {
let mut coro = Coroutine::spawn(|_, _| 0);
let _ = coro.resume(0);
let _ = coro.resume(0);
}
#[test]
fn state() {
let mut coro = Coroutine::spawn(|coro, _| {
coro.yield_with(0);
coro.park_with(0);
0
});
assert_eq!(coro.state(), State::Suspended);
let _ = coro.resume(0);
assert_eq!(coro.state(), State::Suspended);
let _ = coro.resume(0);
assert_eq!(coro.state(), State::Parked);
let _ = coro.resume(0);
assert_eq!(coro.state(), State::Finished);
}
#[test]
fn panicking() {
let mut coro = Coroutine::spawn(|_, _| {
panic!(1010);
});
let result = coro.resume(0);
println!("{:?} {:?}", result, coro.state());
assert!(result.is_err());
let err = result.unwrap_err();
match err {
::Error::Panicking(err) => {
assert!(err.is::<i32>());
}
_ => unreachable!(),
}
}
}