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
use crate::{
cps::{self, AsyncStack, ContinuationFunction},
Arc, Closure,
};
use alloc::boxed::Box;
use core::{future::Future, intrinsics::transmute, pin::Pin, task::Poll};
impl<T, F: Future<Output = T>> From<F> for Arc<Closure> {
fn from(future: F) -> Self {
to_closure(future)
}
}
pub fn to_closure<O, F: Future<Output = O>>(future: F) -> Arc<Closure> {
let closure = Arc::new(Closure::new(
get_result::<O, F> as *const u8,
Some(Box::pin(future)),
));
unsafe { transmute(closure) }
}
extern "C" fn get_result<O, F: Future<Output = O>>(
stack: &mut AsyncStack,
continue_: ContinuationFunction<O>,
closure: Arc<Closure<Option<Pin<Box<F>>>>>,
) -> cps::Result {
poll(
stack,
continue_,
unsafe { &mut *(closure.payload() as *mut Option<Pin<Box<F>>>) }
.take()
.unwrap(),
)
}
fn resume<O, F: Future<Output = O>>(
stack: &mut AsyncStack,
continue_: ContinuationFunction<O>,
) -> cps::Result {
let future = stack.restore::<Pin<Box<F>>>().unwrap();
poll(stack, continue_, future)
}
fn poll<O, F: Future<Output = O>>(
stack: &mut AsyncStack,
continue_: ContinuationFunction<O>,
mut future: Pin<Box<F>>,
) -> cps::Result {
match future.as_mut().poll(stack.context().unwrap()) {
Poll::Ready(value) => {
stack.trampoline(continue_, value).unwrap();
}
Poll::Pending => {
stack.suspend(resume::<O, F>, continue_, future).unwrap();
}
}
cps::Result::new()
}