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
use crate::context::{Context, Transfer};
use crate::id::IdGenerator;
use crate::scheduler::Scheduler;
use crate::stack::ProtectedFixedSizeStack;
use std::cell::RefCell;
use std::marker::PhantomData;
use std::os::raw::c_void;
#[repr(C)]
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Status {
Created,
Ready,
Running,
Suspend,
SystemCall,
CopyStack,
Finished,
Exited,
}
#[repr(transparent)]
pub struct Yielder<'a, Param, Yield, Return> {
sp: &'a Transfer,
marker: PhantomData<fn(Yield) -> CoroutineResult<Param, Return>>,
}
thread_local! {
static DELAY_TIME: Box<RefCell<u64>> = Box::new(RefCell::new(0));
}
impl<'a, Param, Yield, Return> Yielder<'a, Param, Yield, Return> {
pub extern "C" fn suspend(&self, val: Yield) -> Param {
unsafe {
let mut coroutine_result = CoroutineResult::<Yield, Return>::Yield(val);
let transfer = self
.sp
.context
.resume(&mut coroutine_result as *mut _ as usize);
let backed = transfer.data as *mut c_void as *mut _
as *mut OpenCoroutine<'_, Param, Yield, Return>;
std::ptr::read_unaligned(&(*backed).param)
}
}
pub extern "C" fn delay(&self, val: Yield, ms_time: u64) -> Param {
self.delay_ns(
val,
match ms_time.checked_mul(1_000_000) {
Some(v) => v,
None => u64::MAX,
},
)
}
pub extern "C" fn delay_ns(&self, val: Yield, ns_time: u64) -> Param {
Yielder::<Param, Yield, Return>::init_delay_time(ns_time);
self.suspend(val)
}
fn init_delay_time(time: u64) {
DELAY_TIME.with(|boxed| {
*boxed.borrow_mut() = time;
});
}
pub(crate) fn delay_time() -> u64 {
DELAY_TIME.with(|boxed| *boxed.borrow_mut())
}
pub(crate) fn clean_delay() {
DELAY_TIME.with(|boxed| *boxed.borrow_mut() = 0)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CoroutineResult<Yield, Return> {
Yield(Yield),
Return(Return),
}
impl<Yield, Return> CoroutineResult<Yield, Return> {
pub fn as_yield(self) -> Option<Yield> {
match self {
CoroutineResult::Yield(val) => Some(val),
CoroutineResult::Return(_) => None,
}
}
pub fn as_return(self) -> Option<Return> {
match self {
CoroutineResult::Yield(_) => None,
CoroutineResult::Return(val) => Some(val),
}
}
}
pub type UserFunc<'a, Param, Yield, Return> =
extern "C" fn(&'a Yielder<Param, Yield, Return>, Param) -> Return;
pub type Coroutine<Input, Return> = OpenCoroutine<'static, Input, (), Return>;
#[repr(C)]
pub struct OpenCoroutine<'a, Param, Yield, Return> {
pub(crate) id: usize,
sp: Transfer,
stack: ProtectedFixedSizeStack,
pub(crate) status: Status,
proc: UserFunc<'a, Param, Yield, Return>,
marker: PhantomData<&'a extern "C" fn(Param) -> CoroutineResult<Yield, Return>>,
param: Param,
}
impl<'a, Param, Yield, Return> OpenCoroutine<'a, Param, Yield, Return> {
extern "C" fn child_context_func(t: Transfer) {
let coroutine =
t.data as *const c_void as *const _ as *const OpenCoroutine<'_, Param, Yield, Return>;
let yielder = Yielder {
sp: &t,
marker: Default::default(),
};
unsafe {
let proc = (*coroutine).proc;
let param = std::ptr::read_unaligned(&(*coroutine).param);
let result = proc(&yielder, param);
Scheduler::current().do_schedule();
let mut coroutine_result = CoroutineResult::<Yield, Return>::Return(result);
t.context.resume(&mut coroutine_result as *mut _ as usize);
unreachable!("should not execute to here !")
}
}
pub fn new(proc: UserFunc<'a, Param, Yield, Return>, param: Param, size: usize) -> Self {
let stack = ProtectedFixedSizeStack::new(size).unwrap_or_else(|err| {
panic!("Failed to allocate ProtectedFixedSizeStack with {:?}", err)
});
OpenCoroutine {
id: IdGenerator::next_coroutine_id(),
sp: Transfer::new(
unsafe {
Context::new(
&stack,
OpenCoroutine::<Param, Yield, Return>::child_context_func,
)
},
0,
),
stack,
status: Status::Created,
proc,
marker: Default::default(),
param,
}
}
pub fn resume_with(&mut self, val: Param) -> CoroutineResult<Yield, Return> {
self.param = val;
self.resume()
}
pub fn resume(&mut self) -> CoroutineResult<Yield, Return> {
self.status = Status::Ready;
self.sp.data = self as *mut _ as usize;
unsafe {
let transfer = self.sp.context.resume(self.sp.data);
self.sp.context = transfer.context;
std::ptr::read_unaligned(
transfer.data as *mut c_void as *mut _ as *mut CoroutineResult<Yield, Return>,
)
}
}
}
#[cfg(test)]
mod tests {
use crate::coroutine::{OpenCoroutine, Yielder};
#[test]
fn test_return() {
extern "C" fn context_func(_yielder: &Yielder<usize, usize, usize>, input: usize) -> usize {
assert_eq!(0, input);
1
}
let mut coroutine = OpenCoroutine::new(context_func, 0, 2048);
assert_eq!(1, coroutine.resume_with(0).as_return().unwrap());
}
#[test]
fn test_yield_once() {
extern "C" fn context_func(yielder: &Yielder<usize, usize, usize>, input: usize) -> usize {
assert_eq!(1, input);
assert_eq!(3, yielder.suspend(2));
6
}
let mut coroutine = OpenCoroutine::new(context_func, 1, 2048);
assert_eq!(2, coroutine.resume_with(1).as_yield().unwrap());
}
#[test]
fn test_yield() {
extern "C" fn context_func(yielder: &Yielder<usize, usize, usize>, input: usize) -> usize {
assert_eq!(1, input);
assert_eq!(3, yielder.suspend(2));
assert_eq!(5, yielder.suspend(4));
6
}
let mut coroutine = OpenCoroutine::new(context_func, 1, 2048);
assert_eq!(2, coroutine.resume_with(1).as_yield().unwrap());
assert_eq!(4, coroutine.resume_with(3).as_yield().unwrap());
assert_eq!(6, coroutine.resume_with(5).as_return().unwrap());
}
}