use anyhow::Context;
use std::{fs, path::Path};
use wasmtime::{
Config, Engine, Result, Store,
component::{Component, HasSelf, Linker, bindgen},
};
bindgen!("convert" in "./examples/component/convert.wit");
struct MyState {
}
impl host::Host for MyState {
fn multiply(&mut self, a: f32, b: f32) -> f32 {
a * b
}
}
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 {});
let mut linker = Linker::new(&engine);
host::add_to_linker::<_, HasSelf<_>>(&mut linker, |state| state)?;
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(())
}