Skip to content

Instantly share code, notes, and snippets.

@xxshady
Last active June 8, 2024 22:05
Show Gist options
  • Save xxshady/fa019b8ddd4ddcc745f503c668f836c2 to your computer and use it in GitHub Desktop.
Save xxshady/fa019b8ddd4ddcc745f503c668f836c2 to your computer and use it in GitHub Desktop.
Simple WASM Rust async executor + spawn_future helper
// js usage example for https://github.com/xxshady/altv-esbuild-rust-wasm
import alt from "alt-shared"
import loadWasm from "./rust-wasm/pkg/rust_wasm_bg.wasm"
const { on_every_tick } = loadWasm({})
alt.everyTick(on_every_tick);
// Make sure to install "futures" crate
use futures::{
executor::{LocalPool, LocalSpawner},
task::LocalSpawnExt,
task::SpawnError,
};
use std::{cell::RefCell, future::Future};
thread_local! {
pub(crate) static EXECUTOR_INSTANCE: RefCell<Executor> = Default::default();
}
#[derive(Debug)]
pub(crate) struct Executor {
pool: LocalPool,
spawner: LocalSpawner,
}
impl Executor {
pub(crate) fn run(&mut self) {
self.pool.run_until_stalled();
}
}
impl Default for Executor {
fn default() -> Self {
let pool = LocalPool::new();
let spawner = pool.spawner();
Self { pool, spawner }
}
}
pub fn spawn_future<F>(future: F) -> Result<(), SpawnError>
where
F: Future<Output = ()> + 'static,
{
EXECUTOR_INSTANCE.with_borrow(|executor| executor.spawner.spawn_local(future))
}
// needs to be called from JS in every tick (a.k.a setInterval with 0 delay)
#[wasm_bindgen]
pub fn on_every_tick() {
EXECUTOR_INSTANCE.with_borrow_mut(|executor| {
executor.run();
});
}
spawn_future(async {
// ...
})
.unwrap();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment