Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bytecodealliance
GitHub Repository: bytecodealliance/wasmtime
Path: blob/main/examples/fuel.rs
1685 views
1
//! Example of limiting a WebAssembly function's runtime using "fuel consumption".
2
3
// You can execute this example with `cargo run --example fuel`
4
5
use wasmtime::*;
6
7
fn main() -> Result<()> {
8
let mut config = Config::new();
9
config.consume_fuel(true);
10
let engine = Engine::new(&config)?;
11
let mut store = Store::new(&engine, ());
12
store.set_fuel(10_000)?;
13
let module = Module::from_file(store.engine(), "examples/fuel.wat")?;
14
let instance = Instance::new(&mut store, &module, &[])?;
15
16
// Invoke `fibonacci` export with higher and higher numbers until we exhaust our fuel.
17
let fibonacci = instance.get_typed_func::<i32, i32>(&mut store, "fibonacci")?;
18
for n in 1.. {
19
let fuel_before = store.get_fuel().unwrap();
20
let output = match fibonacci.call(&mut store, n) {
21
Ok(v) => v,
22
Err(e) => {
23
assert_eq!(e.downcast::<Trap>()?, Trap::OutOfFuel);
24
println!("Exhausted fuel computing fib({n})");
25
break;
26
}
27
};
28
let fuel_consumed = fuel_before - store.get_fuel().unwrap();
29
println!("fib({n}) = {output} [consumed {fuel_consumed} fuel]");
30
store.set_fuel(10_000)?;
31
}
32
Ok(())
33
}
34
35