Files
wasmtime/crates/api/examples/gcd.rs
Alex Crichton 045d6a7310 Remove the need for HostRef<Store> (#771)
* Remove the need for `HostRef<Store>`

This commit goes through the public API of the `wasmtime` crate and
removes the need for `HostRef<Store>`, as discussed in #708. This commit
is accompanied with a few changes:

* The `Store` type now also implements `Default`, creating a new
  `Engine` with default settings and returning that.

* The `Store` type now implements `Clone`, and is documented as being a
  "cheap clone" aka being reference counted. As before there is no
  supported way to create a deep clone of a `Store`.

* All APIs take/return `&Store` or `Store` instead of `HostRef<Store>`,
  and `HostRef<T>` is left as purely a detail of the C API.

* The `global_exports` function is tagged as `#[doc(hidden)]` for now
  while we await its removal.

* The `Store` type is not yet `Send` nor `Sync` due to the usage of
  `global_exports`, but it is intended to become so eventually.

* Touch up comments on some examples

* Run rustfmt
2020-01-07 16:29:44 -06:00

63 lines
1.4 KiB
Rust

//! Example of instantiating of the WebAssembly module and
//! invoking its exported function.
use wasmtime::*;
const WAT: &str = r#"
(module
(func $gcd (param i32 i32) (result i32)
(local i32)
block ;; label = @1
block ;; label = @2
local.get 0
br_if 0 (;@2;)
local.get 1
local.set 2
br 1 (;@1;)
end
loop ;; label = @2
local.get 1
local.get 0
local.tee 2
i32.rem_u
local.set 0
local.get 2
local.set 1
local.get 0
br_if 0 (;@2;)
end
end
local.get 2
)
(export "gcd" (func $gcd))
)
"#;
fn main() -> anyhow::Result<()> {
// Load our WebAssembly (parsed WAT in our case), and then load it into a
// `Module` which is attached to a `Store` cache.
let wasm = wat::parse_str(WAT)?;
let store = Store::default();
let module = HostRef::new(Module::new(&store, &wasm)?);
// Find index of the `gcd` export.
let gcd_index = module
.borrow()
.exports()
.iter()
.enumerate()
.find(|(_, export)| export.name().to_string() == "gcd")
.unwrap()
.0;
// Instantiate the module.
let instance = Instance::new(&store, &module, &[])?;
// Invoke `gcd` export
let gcd = instance.exports()[gcd_index].func().expect("gcd");
let result = gcd.borrow().call(&[Val::from(6i32), Val::from(27i32)])?;
println!("{:?}", result);
Ok(())
}