use super::*;
use std::cell::UnsafeCell;
thread_local!(
static LOCAL_EXECUTOR: UnsafeCell<Option<Box<dyn CanExecute>>> = UnsafeCell::new(Option::None);
);
pub(crate) fn set_local_executor<E>(executor: E)
where
E: CanExecute + 'static,
{
LOCAL_EXECUTOR.with(move |e| unsafe {
*e.get() = Some(Box::new(executor));
});
}
pub(crate) fn unset_local_executor() {
LOCAL_EXECUTOR.with(move |e| unsafe {
*e.get() = None;
});
}
pub fn try_execute_locally<F>(f: F) -> Result<(), F>
where
F: FnOnce() + Send + 'static,
{
LOCAL_EXECUTOR.with(move |e| {
if let Some(Some(boxed)) = unsafe { e.get().as_ref() } {
boxed.execute_job(Box::new(f));
Ok(())
} else {
Err(f)
}
})
}