1 //! Pre-compiling a Wasm program.
2 
3 use wasmtime::{Config, Engine, Result, Strategy};
4 
main() -> Result<()>5 fn main() -> Result<()> {
6     // Configure Wasmtime for compiling Wasm programs to x86_64 with the
7     // Cranelift compiler.
8     let mut config = Config::new();
9     config.strategy(Strategy::Cranelift);
10     if let Err(error) = config.target("x86_64") {
11         eprintln!(
12             "this Wasmtime was not built with the x86_64 Cranelift backend \
13              enabled: {error:?}",
14         );
15         return Ok(());
16     }
17 
18     // Create an `Engine` with that configuration.
19     let engine = match Engine::new(&config) {
20         Ok(engine) => engine,
21         Err(error) => {
22             println!("Wasmtime build is incompatible with config: {error:?}");
23             return Ok(());
24         }
25     };
26 
27     // Pre-compile a Wasm program.
28     //
29     // Note that passing the Wasm text format, like we are doing here, is only
30     // supported when the `wat` cargo feature is enabled.
31     let precompiled = engine.precompile_module(
32         r#"
33             (module
34               (func (export "add") (param i32 i32) (result i32)
35                 (i32.add (local.get 0) (local.get 1))
36               )
37             )
38         "#
39         .as_bytes(),
40     )?;
41 
42     // Write the pre-compiled program to a file.
43     //
44     // Note that the `.cwasm` extension is conventional for these files, and is
45     // what the Wasmtime CLI will use by default, for example.
46     std::fs::write("add.cwasm", &precompiled)?;
47 
48     // And we are done -- now a different Wasmtime embedding can load and run
49     // the pre-compiled Wasm program from that `add.cwasm` file!
50     Ok(())
51 }
52