1- use anyhow:: Context ;
21use std:: path:: PathBuf ;
3- use wasmtime:: component:: * ;
2+
3+ use anyhow:: Context ;
4+ use wasmtime:: component:: { Component , Linker } ;
45use wasmtime:: { Config , Engine , Store } ;
6+
57use crate :: state:: States ;
68
7- bindgen ! ( {
8- path: "add.wit" ,
9- world: "example" ,
10- async : true
11- } ) ;
9+ mod bindings {
10+ //! Generated code for the
11+ wasmtime:: component:: bindgen!( {
12+ path: "../tutorial/wit/adder/world.wit" ,
13+ world: "adder" ,
14+ async : true
15+ } ) ;
16+ }
1217
13- pub async fn add ( path : PathBuf , x : i32 , y : i32 ) -> wasmtime:: Result < i32 > {
18+ /// Perform the add operation for a given WebAssembly component
19+ ///
20+ /// This operation asynchronously (as opposed to synchronously
21+ /// without an async runtime like `tokio` or `async-std`).
22+ ///
23+ /// # Arguments
24+ ///
25+ /// * `path` - Path to the Wasm component bytes
26+ /// * `x` - The left hand side of the addition
27+ /// * `y` - The right hand side of the addition
28+ ///
29+ pub async fn add ( path : PathBuf , x : u32 , y : u32 ) -> wasmtime:: Result < u32 > {
1430 // Construct engine
1531 let mut config = Config :: default ( ) ;
1632 config. async_support ( true ) ;
1733 let engine = Engine :: new ( & config) ?;
34+
1835 // Construct component
1936 let component = Component :: from_file ( & engine, path) . context ( "Component file not found" ) ?;
37+
2038 // Construct store for storing running states of the component
2139 let wasi_view = States :: new ( ) ;
2240 let mut store = Store :: new ( & engine, wasi_view) ;
41+
2342 // Construct linker for linking interfaces.
24- // For this simple adder component, no need to manually link additional interfaces.
2543 let mut linker = Linker :: new ( & engine) ;
26- // Add wasi exports to linker to support io interfaces
44+
45+ // Add wasi exports to linker to support I/O (as in `wasi:io`) interfaces
46+ // see: https://github.com/WebAssembly/wasi-io
2747 wasmtime_wasi:: add_to_linker_async ( & mut linker) ?;
28- let instance = Example :: instantiate_async ( & mut store, & component, & linker)
48+
49+ // Instantiate the component as an instance of the `adder` world,
50+ // with the generated bindings
51+ let instance = bindings:: Adder :: instantiate_async ( & mut store, & component, & linker)
2952 . await
3053 . context ( "Failed to instantiate the example world" ) ?;
54+
55+ // Call the add function on instance
3156 instance
57+ . docs_adder_add ( )
3258 . call_add ( & mut store, x, y)
3359 . await
34- . context ( "Failed to call add function" )
35- }
60+ . context ( "calling add function" )
61+ }
0 commit comments