1use std::cell::{Cell, RefCell};
7use std::collections::HashMap;
8use std::rc::{Rc, Weak};
9use std::sync::{Arc, Mutex};
10use std::task::{Context, Poll, Wake, Waker};
11
12use serge_core::{Executor, LocalFuture, TaskHandle};
13
14struct TaskWaker {
15 id: u64,
16 ready: Arc<Mutex<Vec<u64>>>,
17 notify: Arc<dyn Fn() + Send + Sync>,
18}
19
20impl Wake for TaskWaker {
21 fn wake(self: Arc<Self>) {
22 self.wake_by_ref();
23 }
24
25 fn wake_by_ref(self: &Arc<Self>) {
26 self.ready.lock().expect("ready queue").push(self.id);
27 (self.notify)();
28 }
29}
30
31struct Inner {
32 _shared_wake: hyve::state::SharedWake,
33 tasks: RefCell<HashMap<u64, LocalFuture>>,
34 aborted: RefCell<Vec<u64>>,
35 next: Cell<u64>,
36 ready: Arc<Mutex<Vec<u64>>>,
37 notify: Arc<dyn Fn() + Send + Sync>,
38}
39
40#[derive(Clone)]
43pub struct LocalExecutor(Rc<Inner>);
44
45impl std::fmt::Debug for LocalExecutor {
46 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47 f.debug_struct("LocalExecutor")
48 .field("tasks", &self.0.tasks.borrow().len())
49 .finish()
50 }
51}
52
53impl LocalExecutor {
54 pub fn new(notify: impl Fn() + Send + Sync + 'static) -> LocalExecutor {
57 let notify = Arc::new(notify);
58 let wake = notify.clone();
59 LocalExecutor(Rc::new(Inner {
60 _shared_wake: hyve::state::on_shared_wake(move || wake()),
61 tasks: RefCell::new(HashMap::new()),
62 aborted: RefCell::new(Vec::new()),
63 next: Cell::new(0),
64 ready: Arc::new(Mutex::new(Vec::new())),
65 notify,
66 }))
67 }
68
69 pub fn run_ready(&self) -> bool {
71 let _rt = serge_core::runtime().enter();
72 let mut any = hyve::state::drain_shared_updates();
73 loop {
74 let ids: Vec<u64> = std::mem::take(&mut *self.0.ready.lock().expect("ready queue"));
75 if ids.is_empty() {
76 return any;
77 }
78 for id in ids {
79 let Some(mut task) = self.0.tasks.borrow_mut().remove(&id) else {
80 continue;
81 };
82 any = true;
83 let waker = Waker::from(Arc::new(TaskWaker {
84 id,
85 ready: self.0.ready.clone(),
86 notify: self.0.notify.clone(),
87 }));
88 let mut cx = Context::from_waker(&waker);
89 if task.as_mut().poll(&mut cx).is_pending() {
90 let mut aborted = self.0.aborted.borrow_mut();
91 if let Some(p) = aborted.iter().position(|a| *a == id) {
92 aborted.swap_remove(p);
93 } else {
94 self.0.tasks.borrow_mut().insert(id, task);
95 }
96 }
97 }
98 }
99 }
100
101 pub fn len(&self) -> usize {
103 self.0.tasks.borrow().len()
104 }
105
106 pub fn is_empty(&self) -> bool {
108 self.len() == 0
109 }
110}
111
112impl Executor for LocalExecutor {
113 fn spawn(&self, task: LocalFuture) -> TaskHandle {
114 let id = self.0.next.get();
115 self.0.next.set(id + 1);
116 self.0.tasks.borrow_mut().insert(id, task);
117 self.0.ready.lock().expect("ready queue").push(id);
118 (self.0.notify)();
119 let weak: Weak<Inner> = Rc::downgrade(&self.0);
120 TaskHandle::new(move || {
121 if let Some(inner) = weak.upgrade() {
122 if inner.tasks.borrow_mut().remove(&id).is_none() {
125 inner.aborted.borrow_mut().push(id);
126 }
127 }
128 })
129 }
130}
131
132pub fn yield_now() -> impl std::future::Future<Output = ()> {
135 let mut yielded = false;
136 std::future::poll_fn(move |cx| {
137 if yielded {
138 Poll::Ready(())
139 } else {
140 yielded = true;
141 cx.waker().wake_by_ref();
142 Poll::Pending
143 }
144 })
145}