Skip to content

Commit

Permalink
add wasmer-cache to engine-dylib example and try reload the module
Browse files Browse the repository at this point in the history
  • Loading branch information
tzemanovic committed Dec 28, 2021
1 parent a662265 commit 15b980d
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ required-features = ["cranelift"]
[[example]]
name = "engine-dylib"
path = "examples/engine_dylib.rs"
required-features = ["cranelift"]
required-features = ["cranelift", "cache"]

[[example]]
name = "engine-headless"
Expand Down
23 changes: 23 additions & 0 deletions examples/engine_dylib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,13 @@
use wasmer::{imports, wat2wasm, Instance, Module, Store, Value};
use wasmer_compiler_cranelift::Cranelift;
use wasmer_engine_dylib::Dylib;
use wasmer_cache::{Cache, FileSystemCache, Hash};

fn main() -> Result<(), Box<dyn std::error::Error>> {
let dir = tempfile::tempdir()?;
// Create a new file system cache.
let mut fs_cache = FileSystemCache::new(dir.path())?;

// Let's declare the Wasm module with the text representation.
let wasm_bytes = wat2wasm(
r#"
Expand All @@ -37,6 +42,9 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
.as_bytes(),
)?;

// Compute a key for a given WebAssembly binary
let hash = Hash::generate(&wasm_bytes);

// Define a compiler configuration.
//
// In this situation, the compiler is
Expand Down Expand Up @@ -82,6 +90,21 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("Results: {:?}", results);
assert_eq!(results.to_vec(), vec![Value::I32(3)]);


// Store a module into the cache given a key
fs_cache.store(hash, &module)?;

let loaded_module = unsafe {fs_cache.load(&store, hash) }?;
let instance = Instance::new(&loaded_module, &import_object)?;

println!("Calling `sum` function from a re-loaded module...");
// The Wasm module exports a function called `sum`.
let sum = instance.exports.get_function("sum")?;
let results = sum.call(&[Value::I32(1), Value::I32(2)])?;

println!("Results: {:?}", results);
assert_eq!(results.to_vec(), vec![Value::I32(3)]);

Ok(())
}

Expand Down

0 comments on commit 15b980d

Please sign in to comment.