summaryrefslogtreecommitdiff
path: root/examples/gc.rs
diff options
context:
space:
mode:
authorMica White <botahamec@outlook.com>2026-10-31 11:10:49 -0400
committerMica White <botahamec@outlook.com>2026-10-31 11:10:49 -0400
commit264ea48cc8c6dd9c3c9e0fe1a559252863fc9962 (patch)
tree84a4a58de14442f4fcfa06bd0d82480508f82759 /examples/gc.rs
parent7877eca4e8be283e7c51168ee3a3b05d9000f39c (diff)
parentb45a98a85c776d956a797773acd2f198c06b40ed (diff)
Merge branch 'main' into bota-tortuise
Diffstat (limited to 'examples/gc.rs')
-rw-r--r--examples/gc.rs33
1 files changed, 33 insertions, 0 deletions
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(())
+}