1
- use anyhow:: Context ;
2
1
use std:: path:: PathBuf ;
3
- use wasmtime:: component:: * ;
2
+
3
+ use anyhow:: Context ;
4
+ use wasmtime:: component:: { Component , Linker } ;
4
5
use wasmtime:: { Config , Engine , Store } ;
6
+
5
7
use crate :: state:: States ;
6
8
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
+ }
12
17
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 > {
14
30
// Construct engine
15
31
let mut config = Config :: default ( ) ;
16
32
config. async_support ( true ) ;
17
33
let engine = Engine :: new ( & config) ?;
34
+
18
35
// Construct component
19
36
let component = Component :: from_file ( & engine, path) . context ( "Component file not found" ) ?;
37
+
20
38
// Construct store for storing running states of the component
21
39
let wasi_view = States :: new ( ) ;
22
40
let mut store = Store :: new ( & engine, wasi_view) ;
41
+
23
42
// Construct linker for linking interfaces.
24
- // For this simple adder component, no need to manually link additional interfaces.
25
43
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
27
47
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)
29
52
. await
30
53
. context ( "Failed to instantiate the example world" ) ?;
54
+
55
+ // Call the add function on instance
31
56
instance
57
+ . docs_adder_add ( )
32
58
. call_add ( & mut store, x, y)
33
59
. await
34
- . context ( "Failed to call add function" )
35
- }
60
+ . context ( "calling add function" )
61
+ }
0 commit comments