Skip to content

Instantly share code, notes, and snippets.

@PhoenixIllusion
Last active December 20, 2024 05:57
Show Gist options
  • Save PhoenixIllusion/0bd416583781447834b56be4c83b370e to your computer and use it in GitHub Desktop.
Save PhoenixIllusion/0bd416583781447834b56be4c83b370e to your computer and use it in GitHub Desktop.
AssemblyScript - asyncify example - using the JS for asyncify_ functions . Compile passing ` --runPasses asyncify` to the assembly-script asc command
import fs from 'fs';
const wasmBuffer = fs.readFileSync('./build/release.wasm');
interface WasmExports {
asyncStackPtr: number;
initAsyncStack(): void;
asyncify_start_unwind(stackPtr: number): void;
asyncify_start_rewind(stackPtr: number): void;
asyncify_stop_rewind(): void;
run(): void;
}
class AsyncDelay {
private trigger_rewind = false;
constructor(private wasmExports: WasmExports) {}
public async_method: (() => Promise<void>) | null = null;
trigger() {
const exports = this.wasmExports;
if(!this.trigger_rewind) {
exports.asyncify_start_unwind(exports.asyncStackPtr);
this.trigger_rewind = true;
this.async_method!().then(() => {
exports.asyncify_start_rewind(exports.asyncStackPtr);
exports.run();
})
} else {
exports.asyncify_stop_rewind();
this.trigger_rewind = false;
}
}
}
let delay!: AsyncDelay;
WebAssembly.instantiate(wasmBuffer, {
env: {
abort: console.error,
sleep: function () { return delay.trigger(); },
log: function(p) { console.log(p) }
}
}).then(wasmModule => {
delay = new AsyncDelay(wasmModule.instance.exports as any);
const { run, initAsyncStack } = wasmModule.instance.exports as any as WasmExports;
initAsyncStack();
delay.async_method = () => new Promise(resolve => setTimeout(resolve, 2000));
run();
});
@external("env", "log")
declare function print(num: i32): void;
@external("env", "sleep")
declare function sleep(): i32;
@unmanaged
class StackDescriptor {
public stackStart: usize;
public stackEnd: usize
constructor(){
this.stackStart = heap.alloc(1024);
this.stackEnd = this.stackStart + 1024;
}
}
@global
export let asyncStackPtr: usize = 0;
export function initAsyncStack(): void {
const stack = new StackDescriptor();
asyncStackPtr = changetype<usize>(stack);
}
export function run(): void {
print(10);
sleep();
print(20);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment