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
use crate::{
sync::{LockClassKey, Ref, RefBorrow},
types::PointerWrapper,
Result,
};
use core::{
future::Future,
task::{RawWaker, RawWakerVTable, Waker},
};
pub mod workqueue;
#[macro_export]
macro_rules! spawn_task {
($executor:expr, $task:expr) => {{
static CLASS: $crate::sync::LockClassKey = $crate::sync::LockClassKey::new();
$crate::kasync::executor::Executor::spawn($executor, &CLASS, $task)
}};
}
pub trait Task {
fn sync_stop(self: Ref<Self>);
}
pub trait Executor: Sync + Send {
fn spawn(
self: RefBorrow<'_, Self>,
lock_class_key: &'static LockClassKey,
future: impl Future + 'static + Send,
) -> Result<Ref<dyn Task>>
where
Self: Sized;
fn stop(&self);
}
pub trait RefWake: Send + Sync {
fn wake_by_ref(self: RefBorrow<'_, Self>);
fn wake(self: Ref<Self>) {
self.as_ref_borrow().wake_by_ref();
}
}
pub fn ref_waker<T: 'static + RefWake>(w: Ref<T>) -> Waker {
fn raw_waker<T: 'static + RefWake>(w: Ref<T>) -> RawWaker {
let data = w.into_pointer();
RawWaker::new(
data.cast(),
&RawWakerVTable::new(clone::<T>, wake::<T>, wake_by_ref::<T>, drop::<T>),
)
}
unsafe fn clone<T: 'static + RefWake>(ptr: *const ()) -> RawWaker {
let w = unsafe { Ref::<T>::borrow(ptr.cast()) };
raw_waker(w.into())
}
unsafe fn wake<T: 'static + RefWake>(ptr: *const ()) {
let w = unsafe { Ref::<T>::from_pointer(ptr.cast()) };
w.wake();
}
unsafe fn wake_by_ref<T: 'static + RefWake>(ptr: *const ()) {
let w = unsafe { Ref::<T>::borrow(ptr.cast()) };
w.wake_by_ref();
}
unsafe fn drop<T: 'static + RefWake>(ptr: *const ()) {
unsafe { Ref::<T>::from_pointer(ptr.cast()) };
}
let raw = raw_waker(w);
unsafe { Waker::from_raw(raw) }
}
pub struct AutoStopHandle<T: Executor + ?Sized> {
executor: Option<Ref<T>>,
}
impl<T: Executor + ?Sized> AutoStopHandle<T> {
pub fn new(executor: Ref<T>) -> Self {
Self {
executor: Some(executor),
}
}
pub fn detach(mut self) -> Ref<T> {
self.executor.take().unwrap()
}
pub fn executor(&self) -> RefBorrow<'_, T> {
self.executor.as_ref().unwrap().as_ref_borrow()
}
}
impl<T: Executor + ?Sized> Drop for AutoStopHandle<T> {
fn drop(&mut self) {
if let Some(ex) = self.executor.take() {
ex.stop();
}
}
}
impl<T: 'static + Executor> From<AutoStopHandle<T>> for AutoStopHandle<dyn Executor> {
fn from(src: AutoStopHandle<T>) -> Self {
Self::new(src.detach())
}
}