1 use anyhow::Context;
2 use std::{fs, path::Path};
3 
4 use wasmtime::{
5     Config, Engine, Result, Store,
6     component::{Component, HasSelf, Linker, bindgen},
7 };
8 
9 // Generate bindings of the guest and host components.
10 bindgen!("convert" in "./examples/component/convert.wit");
11 
12 struct MyState {
13     // ..
14 }
15 
16 // Implementation of the host interface defined in the wit file.
17 impl host::Host for MyState {
18     fn multiply(&mut self, a: f32, b: f32) -> f32 {
19         a * b
20     }
21 }
22 
23 /// This function is only needed until rust can natively output a component.
24 ///
25 /// Generally embeddings should not be expected to do this programmatically, but instead
26 /// language specific tooling should be used, for example in Rust `cargo component`
27 /// is a good way of doing that: https://github.com/bytecodealliance/cargo-component
28 ///
29 /// In this example we convert the code here to simplify the testing process and build system.
30 fn convert_to_component(path: impl AsRef<Path>) -> Result<Vec<u8>> {
31     let bytes = &fs::read(&path).context("failed to read input file")?;
32     wit_component::ComponentEncoder::default()
33         .module(&bytes)?
34         .encode()
35 }
36 
37 fn main() -> Result<()> {
38     // Create an engine with the component model enabled (disabled by default).
39     let engine = Engine::new(Config::new().wasm_component_model(true))?;
40 
41     // NOTE: The wasm32-unknown-unknown target is used here for simplicity, real world use cases
42     // should probably use the wasm32-wasip1 target, and enable wasi preview2 within the component
43     // model.
44     let component = convert_to_component("target/wasm32-unknown-unknown/debug/guest.wasm")?;
45 
46     // Create our component and call our generated host function.
47     let component = Component::from_binary(&engine, &component)?;
48     let mut store = Store::new(&engine, MyState {});
49     let mut linker = Linker::new(&engine);
50     host::add_to_linker::<_, HasSelf<_>>(&mut linker, |state| state)?;
51     let convert = Convert::instantiate(&mut store, &component, &linker)?;
52     let result = convert.call_convert_celsius_to_fahrenheit(&mut store, 23.4)?;
53     println!("Converted to: {result:?}");
54     Ok(())
55 }
56