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
use std::collections::VecDeque;
use std::rc::Rc;
use std::cell::RefCell;
use {Shared, Hidden};
pub(crate) type BoxedRunnable<CTX> = Box<Runnable<CTX>>;
pub(crate) trait Runnable<CTX> {
fn run<'a>(&mut self, context: &'a mut CTX, msg: *mut Hidden);
}
pub struct Scheduler<CTX> {
context: Shared<CTX>,
sequence: Shared<VecDeque<(Shared<BoxedRunnable<CTX>>, *mut Hidden)>>,
}
impl<CTX> Clone for Scheduler<CTX> {
fn clone(&self) -> Self {
Scheduler {
context: self.context.clone(),
sequence: self.sequence.clone(),
}
}
}
impl<CTX> Scheduler<CTX> {
pub fn new(context: CTX) -> Self {
let sequence = VecDeque::new();
Scheduler {
context: Rc::new(RefCell::new(context)),
sequence: Rc::new(RefCell::new(sequence)),
}
}
pub(crate) fn put_and_try_run(&mut self, pair: (Shared<BoxedRunnable<CTX>>, *mut Hidden)) {
self.sequence.borrow_mut().push_back(pair);
if let Ok(ref mut context) = self.context.try_borrow_mut() {
loop {
let do_next = self.sequence.borrow_mut().pop_front();
if let Some((routine, msg)) = do_next {
routine.borrow_mut().run(context, msg);
} else {
break;
}
}
}
}
}