Skip to main content

rquickjs_core/runtime/
spawner.rs

1use super::{
2    job_error::JobError,
3    schedular::{Schedular, SchedularPoll},
4    AsyncWeakRuntime, InnerRuntime,
5};
6use crate::AsyncRuntime;
7use alloc::vec::Vec;
8use core::{
9    future::Future,
10    pin::Pin,
11    result::Result as StdResult,
12    task::{ready, Context, Poll, Waker},
13};
14
15use async_lock::futures::LockArc;
16
17/// A structure to hold futures spawned inside the runtime.
18pub struct Spawner {
19    schedular: Schedular,
20    wakeup: Vec<Waker>,
21}
22
23impl Spawner {
24    pub fn new() -> Self {
25        Spawner {
26            schedular: Schedular::new(),
27            wakeup: Vec::new(),
28        }
29    }
30
31    pub unsafe fn push<F>(&mut self, f: F)
32    where
33        F: Future<Output = ()>,
34    {
35        unsafe { self.schedular.push(f) };
36        self.wakeup.drain(..).for_each(Waker::wake);
37    }
38
39    pub fn listen(&mut self, wake: Waker) {
40        self.wakeup.push(wake);
41    }
42
43    pub fn is_empty(&mut self) -> bool {
44        self.schedular.is_empty()
45    }
46
47    pub fn poll(&mut self, cx: &mut Context) -> SchedularPoll {
48        unsafe { self.schedular.poll(cx) }
49    }
50}
51
52enum DriveFutureState {
53    Initial,
54    Lock {
55        lock_future: Option<LockArc<InnerRuntime>>,
56        // Here to ensure the lock remains valid.
57        _runtime: AsyncRuntime,
58    },
59}
60
61pub struct DriveFuture {
62    rt: AsyncWeakRuntime,
63    state: DriveFutureState,
64}
65
66#[cfg(feature = "parallel")]
67unsafe impl Send for DriveFuture {}
68#[cfg(feature = "parallel")]
69unsafe impl Sync for DriveFuture {}
70
71impl DriveFuture {
72    pub(crate) fn new(rt: AsyncWeakRuntime) -> Self {
73        Self {
74            rt,
75            state: DriveFutureState::Initial,
76        }
77    }
78}
79
80impl Future for DriveFuture {
81    type Output = StdResult<(), JobError>;
82
83    fn poll(self: Pin<&mut Self>, cx: &mut core::task::Context<'_>) -> Poll<Self::Output> {
84        // Safety: We manually ensure that pinned values remained properly pinned.
85        let this = unsafe { self.get_unchecked_mut() };
86        loop {
87            let lock = match this.state {
88                DriveFutureState::Initial => {
89                    let Some(_runtime) = this.rt.try_ref() else {
90                        return Poll::Ready(Ok(()));
91                    };
92
93                    let lock_future = _runtime.inner.lock_arc();
94                    this.state = DriveFutureState::Lock {
95                        lock_future: Some(lock_future),
96                        _runtime,
97                    };
98                    continue;
99                }
100                DriveFutureState::Lock {
101                    ref mut lock_future,
102                    ..
103                } => {
104                    // Safety: The future will not be moved until it is ready and then dropped.
105                    let res = unsafe {
106                        ready!(Pin::new_unchecked(lock_future.as_mut().unwrap()).poll(cx))
107                    };
108                    // Assign none explicitly so it we don't move out of the future.
109                    *lock_future = None;
110                    res
111                }
112            };
113
114            lock.runtime.update_stack_top();
115
116            lock.runtime.get_opaque().listen(cx.waker().clone());
117
118            loop {
119                match lock.runtime.execute_pending_job() {
120                    Ok(true) => continue,
121                    Ok(false) => {}
122                    Err(err) => {
123                        this.state = DriveFutureState::Initial;
124                        return Poll::Ready(Err(err));
125                    }
126                }
127
128                match lock.runtime.get_opaque().poll(cx) {
129                    SchedularPoll::ShouldYield | SchedularPoll::Empty | SchedularPoll::Pending => {
130                        break
131                    }
132                    SchedularPoll::PendingProgress => {}
133                }
134            }
135
136            this.state = DriveFutureState::Initial;
137            return Poll::Pending;
138        }
139    }
140}