use std::fmt;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
macro_rules! task {
($name:ident: move || $body:tt) => {{
#[allow(non_camel_case_types)]
struct $name<F>(F);
impl<F> crate::task::TaskOnce for $name<F>
where
F: ::std::ops::FnOnce() + Send,
{
fn name(&self) -> &'static str {
stringify!($name)
}
fn run_once(self) {
(self.0)();
}
}
$name(move || $body)
}};
}
pub(crate) trait TaskOnce: Send {
#[allow(unsafe_code)]
fn name(&self) -> &'static str {
::std::any::type_name::<Self>()
}
fn run_once(self);
}
pub(crate) trait TaskBox: Send {
fn name(&self) -> &'static str;
fn run_box(self: Box<Self>);
}
impl<T> TaskBox for T
where
T: TaskOnce,
{
fn name(&self) -> &'static str {
TaskOnce::name(self)
}
fn run_box(self: Box<Self>) {
self.run_once()
}
}
impl fmt::Debug for dyn TaskBox {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_tuple(self.name())
.field(&format_args!("..."))
.finish()
}
}
#[derive(Clone, Default, JSTraceable, MallocSizeOf)]
pub(crate) struct TaskCanceller {
#[ignore_malloc_size_of = "This is difficult, because only one of them should be measured"]
pub(crate) cancelled: Arc<AtomicBool>,
}
impl TaskCanceller {
pub(crate) fn wrap_task(&self, task: impl TaskOnce) -> impl TaskOnce {
CancellableTask {
canceller: self.clone(),
inner: task,
}
}
pub(crate) fn cancelled(&self) -> bool {
self.cancelled.load(Ordering::SeqCst)
}
}
pub(crate) struct CancellableTask<T: TaskOnce> {
canceller: TaskCanceller,
inner: T,
}
impl<T: TaskOnce> TaskOnce for CancellableTask<T> {
fn name(&self) -> &'static str {
self.inner.name()
}
fn run_once(self) {
if !self.canceller.cancelled() {
self.inner.run_once()
}
}
}