use js_sys::Promise;
use std::cell::{Cell, RefCell};
use std::collections::VecDeque;
use std::rc::Rc;
use wasm_bindgen::prelude::*;
struct QueueState {
tasks: RefCell<VecDeque<Rc<crate::task::Task>>>,
is_scheduled: Cell<bool>,
}
impl QueueState {
fn run_all(&self) {
let _was_scheduled = self.is_scheduled.replace(false);
debug_assert!(_was_scheduled);
let mut task_count_left = self.tasks.borrow().len();
while task_count_left > 0 {
task_count_left -= 1;
let task = match self.tasks.borrow_mut().pop_front() {
Some(task) => task,
None => break,
};
task.run();
}
}
}
pub(crate) struct Queue {
state: Rc<QueueState>,
promise: Promise,
closure: Closure<dyn FnMut(JsValue)>,
}
impl Queue {
pub(crate) fn schedule_task(&self, task: Rc<crate::task::Task>) {
self.state.tasks.borrow_mut().push_back(task);
if !self.state.is_scheduled.replace(true) {
let _ = self.promise.then(&self.closure);
}
}
pub(crate) fn push_task(&self, task: Rc<crate::task::Task>) {
self.schedule_task(task)
}
}
impl Queue {
fn new() -> Self {
let state = Rc::new(QueueState {
is_scheduled: Cell::new(false),
tasks: RefCell::new(VecDeque::new()),
});
Self {
promise: Promise::resolve(&JsValue::undefined()),
closure: {
let state = Rc::clone(&state);
Closure::new(move |_| state.run_all())
},
state,
}
}
}
thread_local! {
pub(crate) static QUEUE: Queue = Queue::new();
}