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
use crate::{fib, thr::prelude::*};
use core::{
fmt::Display,
future::Future,
pin::Pin,
task::{Context, Poll, Waker},
};
pub trait ThrExec: ThrToken {
fn wakeup(self);
fn waker(self) -> Waker;
#[inline]
fn exec<F, O>(self, fut: F)
where
F: Future<Output = O> + Send + 'static,
O: ExecOutput,
{
self.exec_factory(|| fut);
}
#[inline]
fn exec_factory<C, F, O>(self, factory: C)
where
C: FnOnce() -> F + Send + 'static,
F: Future<Output = O> + 'static,
O: ExecOutput,
{
self.add_exec_factory(factory);
self.wakeup();
}
#[inline]
fn add_exec<F, O>(self, fut: F)
where
F: Future<Output = O> + Send + 'static,
O: ExecOutput,
{
self.add_exec_factory(|| fut);
}
#[inline]
fn add_exec_factory<C, F, O>(self, factory: C)
where
C: FnOnce() -> F + Send + 'static,
F: Future<Output = O> + 'static,
O: ExecOutput,
{
fn poll<T: ThrExec, F: Future>(thr: T, fut: Pin<&mut F>) -> Poll<F::Output> {
let waker = thr.waker();
let mut cx = Context::from_waker(&waker);
fut.poll(&mut cx)
}
self.add_fn_factory(move || {
let mut fut = factory();
move || match poll(self, unsafe { Pin::new_unchecked(&mut fut) }) {
Poll::Pending => fib::Yielded(()),
Poll::Ready(output) => {
output.terminate();
fib::Complete(())
}
}
});
}
}
pub trait ExecOutput: Sized + Send {
type Terminate;
fn terminate(self) -> Self::Terminate;
}
impl ExecOutput for () {
type Terminate = ();
#[inline]
fn terminate(self) {}
}
impl<E: Send + Display> ExecOutput for Result<(), E> {
type Terminate = ();
#[inline]
fn terminate(self) {
match self {
Ok(()) => {}
Err(err) => terminate_err(err),
}
}
}
impl ExecOutput for ! {
type Terminate = !;
#[inline]
fn terminate(self) -> ! {
match self {}
}
}
impl<E: Send + Display> ExecOutput for Result<!, E> {
type Terminate = !;
#[inline]
fn terminate(self) -> ! {
let Err(err) = self;
terminate_err(err);
}
}
fn terminate_err<E: Display>(err: E) -> ! {
panic!("root future error: {}", err);
}