From 7b9b3ec681e68280399d9c67e01433c2d3acb6c2 Mon Sep 17 00:00:00 2001 From: Henry Gressmann Date: Mon, 24 Aug 2026 15:47:05 +0200 Subject: feat: add host typed reference / gc APIs (#54) - add Store-aware handles for references, GC objects, and exceptions - simplify host value conversion, rooting, and exception propagation - update examples, tests, and documentation - Remove deprecated APIs Signed-off-by: Henry --- examples/gc.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 examples/gc.rs (limited to 'examples/gc.rs') diff --git a/examples/gc.rs b/examples/gc.rs new file mode 100644 index 0000000..9a73d04 --- /dev/null +++ b/examples/gc.rs @@ -0,0 +1,33 @@ +use anyhow::Result; +use tinywasm::{ModuleInstance, Store, StructRef, WasmValue}; + +const WASM: &str = r#" +(module + (type $cube (struct (field (mut i32)) (field (mut i32)))) + (func $make-cube (result (ref $cube)) + i32.const 3 + i32.const 4 + struct.new $cube) + (func (export "cube") (result (ref struct)) + call $make-cube)) +"#; + +fn main() -> Result<()> { + let wasm = wat::parse_str(WASM)?; + let module = tinywasm::parse_bytes(&wasm)?; + let mut store = Store::default(); + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + let cube = instance.func::<(), StructRef>(&store, "cube")?.call(&mut store, ())?; + + // GC handles are Store-bound and expose typed field access through that Store. + assert_eq!(cube.fields(&mut store)?, [WasmValue::I32(3), WasmValue::I32(4)]); + cube.set_field(&mut store, 0, WasmValue::I32(5))?; + + // Cloned handles keep their guest objects live across explicit collection. + let retained = cube.clone(); + drop(cube); + store.gc()?; + + assert_eq!(retained.field(&mut store, 0)?, WasmValue::I32(5)); // still alive + Ok(()) +} -- cgit v1.3.1