use anyhow::Context;
use std::{fs, path::Path};
use wasmtime::{
component::{bindgen, Component, Linker},
Config, Engine, Result, Store,
};
bindgen!("convert" in "./examples/component/convert.wit");
struct HostComponent;
impl host::Host for HostComponent {
fn multiply(&mut self, a: f32, b: f32) -> f32 {
a * b
}
}
struct MyState {
host: HostComponent,
}
fn convert_to_component(path: impl AsRef<Path>) -> Result<Vec<u8>> {
let bytes = &fs::read(&path).context("failed to read input file")?;
wit_component::ComponentEncoder::default()
.module(&bytes)?
.encode()
}
fn main() -> Result<()> {
let engine = Engine::new(Config::new().wasm_component_model(true))?;
let component = convert_to_component("target/wasm32-unknown-unknown/debug/guest.wasm")?;
let component = Component::from_binary(&engine, &component)?;
let mut store = Store::new(
&engine,
MyState {
host: HostComponent {},
},
);
let mut linker = Linker::new(&engine);
host::add_to_linker(&mut linker, |state: &mut MyState| &mut state.host)?;
let convert = Convert::instantiate(&mut store, &component, &linker)?;
let result = convert.call_convert_celsius_to_fahrenheit(&mut store, 23.4)?;
println!("Converted to: {result:?}");
Ok(())
}