Skip to content

Instantly share code, notes, and snippets.

@syrusakbary
Last active February 14, 2019 20:13
Show Gist options
  • Save syrusakbary/fde50e5631458af5f8479ff8999a670d to your computer and use it in GitHub Desktop.
Save syrusakbary/fde50e5631458af5f8479ff8999a670d to your computer and use it in GitHub Desktop.
Wasmer cache example
// This is an example on how a cache system could work.
// It enforces a very useful pattern for caching:
// - serializing (cache.save)
// - deserializing (cache.load)
// This abstracts the responsibility on how to load or how to save
// outside, so it can be a FileSystem, a HashMap in memory, ...
// We get the hash from the binary
let hash: WasmHash = get_wasm_hash(&wasm_binary);
// We create a new cache instance.
// It could be possible to use any other kinds of caching, as long as they
// implement the Cache trait (with save and load functions)
let cache = FileSystemCache::new(WASMER_CACHE_DIR);
// cache.load will return the Module if it's able to deserialize it properly, and an error if:
// * The file is not found
// * The file exists, but it's corrupted or can't be converted to a module
let module = cache.load(hash).unwrap_or_else(|err| {
let module = webassembly::compile(&wasm_binary[..])
.map_err(|e| format!("Can't compile module: {:?}", e))?;
// We save the module into a cache file
cache.save(hash, module).unwrap();
module
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment