macro_rules! instance_local {
($vis:vis fn $name:ident() -> $ty:ty = $init:expr;) => {
#[cfg(target_arch = "wasm32")]
$vis fn $name<R>(f: impl FnOnce(&mut $ty) -> R) -> R {
struct Slot(core::cell::RefCell<Option<$ty>>);
unsafe impl Sync for Slot {}
static SLOT: Slot = Slot(core::cell::RefCell::new(None));
let mut slot = SLOT.0.borrow_mut();
f(slot.get_or_insert_with(|| $init))
}
#[cfg(not(target_arch = "wasm32"))]
$vis fn $name<R>(f: impl FnOnce(&mut $ty) -> R) -> R {
std::thread_local! {
static SLOT: core::cell::RefCell<Option<$ty>> =
const { core::cell::RefCell::new(None) };
}
SLOT.with(|slot| f(slot.borrow_mut().get_or_insert_with(|| $init)))
}
};
}
pub(crate) use instance_local;