1use alloc::collections::VecDeque;
2use alloc::rc::Rc;
3use core::cell::{Cell, RefCell};
4use js_sys::Promise;
5use wasm_bindgen::prelude::*;
67#[wasm_bindgen]
8extern "C" {
9#[wasm_bindgen]
10fn queueMicrotask(closure: &Closure<dyn FnMut(JsValue)>);
1112type Global;
1314#[wasm_bindgen(method, getter, js_name = queueMicrotask)]
15fn hasQueueMicrotask(this: &Global) -> JsValue;
16}
1718struct QueueState {
19// The queue of Tasks which are to be run in order. In practice this is all the
20 // synchronous work of futures, and each `Task` represents calling `poll` on
21 // a future "at the right time".
22tasks: RefCell<VecDeque<Rc<crate::task::Task>>>,
2324// This flag indicates whether we've scheduled `run_all` to run in the future.
25 // This is used to ensure that it's only scheduled once.
26is_scheduled: Cell<bool>,
27}
2829impl QueueState {
30fn run_all(&self) {
31// "consume" the schedule
32let _was_scheduled = self.is_scheduled.replace(false);
33debug_assert!(_was_scheduled);
3435// Stop when all tasks that have been scheduled before this tick have been run.
36 // Tasks that are scheduled while running tasks will run on the next tick.
37let mut task_count_left = self.tasks.borrow().len();
38while task_count_left > 0 {
39 task_count_left -= 1;
40let task = match self.tasks.borrow_mut().pop_front() {
41Some(task) => task,
42None => break,
43 };
44 task.run();
45 }
4647// All of the Tasks have been run, so it's now possible to schedule the
48 // next tick again
49}
50}
5152pub(crate) struct Queue {
53 state: Rc<QueueState>,
54 promise: Promise,
55 closure: Closure<dyn FnMut(JsValue)>,
56 has_queue_microtask: bool,
57}
5859impl Queue {
60// Schedule a task to run on the next tick
61pub(crate) fn schedule_task(&self, task: Rc<crate::task::Task>) {
62self.state.tasks.borrow_mut().push_back(task);
63// Use queueMicrotask to execute as soon as possible. If it does not exist
64 // fall back to the promise resolution
65if !self.state.is_scheduled.replace(true) {
66if self.has_queue_microtask {
67 queueMicrotask(&self.closure);
68 } else {
69let _ = self.promise.then(&self.closure);
70 }
71 }
72 }
73// Append a task to the currently running queue, or schedule it
74#[cfg(not(target_feature = "atomics"))]
75pub(crate) fn push_task(&self, task: Rc<crate::task::Task>) {
76// It would make sense to run this task on the same tick. For now, we
77 // make the simplifying choice of always scheduling tasks for a future tick.
78self.schedule_task(task)
79 }
80}
8182impl Queue {
83fn new() -> Self {
84let state = Rc::new(QueueState {
85 is_scheduled: Cell::new(false),
86 tasks: RefCell::new(VecDeque::new()),
87 });
8889let has_queue_microtask = js_sys::global()
90 .unchecked_into::<Global>()
91 .hasQueueMicrotask()
92 .is_function();
9394Self {
95 promise: Promise::resolve(&JsValue::undefined()),
9697 closure: {
98let state = Rc::clone(&state);
99100// This closure will only be called on the next microtask event
101 // tick
102Closure::new(move |_| state.run_all())
103 },
104105 state,
106 has_queue_microtask,
107 }
108 }
109110pub(crate) fn with<R>(f: impl FnOnce(&Self) -> R) -> R {
111use once_cell::unsync::Lazy;
112113struct Wrapper<T>(Lazy<T>);
114115#[cfg(not(target_feature = "atomics"))]
116unsafe impl<T> Sync for Wrapper<T> {}
117118#[cfg(not(target_feature = "atomics"))]
119unsafe impl<T> Send for Wrapper<T> {}
120121#[cfg_attr(target_feature = "atomics", thread_local)]
122static QUEUE: Wrapper<Queue> = Wrapper(Lazy::new(Queue::new));
123124 f(&QUEUE.0)
125 }
126}