Last active
June 8, 2024 22:05
-
-
Save xxshady/fa019b8ddd4ddcc745f503c668f836c2 to your computer and use it in GitHub Desktop.
Simple WASM Rust async executor + spawn_future helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
}); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
spawn_future(async { | |
// ... | |
}) | |
.unwrap(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment