Skip to content

Instantly share code, notes, and snippets.

@matklad
Created May 18, 2021 10:22
Show Gist options
  • Save matklad/8583937b980fc5f3f6fcfdaa2bb90bb0 to your computer and use it in GitHub Desktop.
Save matklad/8583937b980fc5f3f6fcfdaa2bb90bb0 to your computer and use it in GitHub Desktop.
pub struct WasmRefCell<T>(core::cell::RefCell<T>);
impl<T> WasmRefCell<T> {
pub const fn new(initial_value: T) -> WasmRefCell<T> {
WasmRefCell(core::cell::RefCell::new(initial_value))
}
pub fn with<U, F: FnOnce(&mut T) -> U>(&self, f: F) -> U {
f(&mut *self.0.borrow_mut())
}
}
#[cfg(target_arch = "wasm32")]
mod wasm32_has_no_threads {
unsafe impl<T> Send for super::WasmRefCell<T> {}
unsafe impl<T> Sync for super::WasmRefCell<T> {}
}
pub struct GlobalContext {
spam: i32,
}
impl GlobalContext {
pub fn with<T, F: FnOnce(&mut GlobalContext) -> T>(f: F) -> T {
static INSTANCE: WasmRefCell<GlobalContext> = WasmRefCell::new(GlobalContext { spam: 0 });
INSTANCE.with(f)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment