Skip to content

Instantly share code, notes, and snippets.

@RunasSudo
Created April 5, 2024 12:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RunasSudo/491e132bd583c72ac3385a590052d511 to your computer and use it in GitHub Desktop.
Save RunasSudo/491e132bd583c72ac3385a590052d511 to your computer and use it in GitHub Desktop.
Vanilla Asyncify
[package]
name = "asyncify-vanilla"
version = "0.1.0"
authors = ["RunasSudo <runassudo@yingtongli.me>"]
edition = "2018"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2.74"
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"></head>
<body>
<script src="asyncify_vanilla.js"></script>
<script>
var wasmRaw;
const DATA_ADDR = 16;
const DATA_START = DATA_ADDR + 8;
const DATA_END = 1024;
function get_second_number() {
if (wasmRaw.asyncify_get_state() === 0) { // Normal execution
setTimeout(secondNumberCallback, 1000); // Simulate async function queued
// Unwind the stack
wasmRaw.asyncify_start_unwind(DATA_ADDR);
return null;
} else {
// Finished rewinding
wasmRaw.asyncify_stop_rewind();
return 5;
}
}
function secondNumberCallback() {
// Rewind the stack and resume execution
wasmRaw.asyncify_start_rewind(DATA_ADDR);
alert(wasmRaw.add_two_numbers()); // Should alert "5"
}
async function init() {
wasmRaw = await wasm_bindgen("asyncify_vanilla_async.wasm");
new Int32Array(wasmRaw.memory.buffer, DATA_ADDR).set([DATA_START, DATA_END]);
let result = wasm_bindgen.add_two_numbers(10);
if (wasmRaw.asyncify_get_state() !== 0) { // 0 if normal, 1 if unwinding, 2 if rewinding
// Stack unwinding so ignore the result
} else {
alert(result); // Unreachable
}
}
init();
</script>
</body>
</html>
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
fn get_second_number() -> u32;
}
#[wasm_bindgen]
pub fn add_two_numbers(first_number: u32) -> u32 {
let second_number = get_second_number();
return first_number + second_number;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment