| 35 | const size_t kStoreFuel = 10000; |
| 36 | |
| 37 | int main() { |
| 38 | Config config; |
| 39 | config.consume_fuel(true); |
| 40 | Engine engine(std::move(config)); |
| 41 | Store store(engine); |
| 42 | store.context().set_fuel(kStoreFuel).unwrap(); |
| 43 | |
| 44 | auto wat = readFile("examples/fuel.wat"); |
| 45 | Module module = Module::compile(engine, wat).unwrap(); |
| 46 | Instance instance = Instance::create(store, module, {}).unwrap(); |
| 47 | Func fib = std::get<Func>(*instance.get(store, "fibonacci")); |
| 48 | |
| 49 | // Call it repeatedly until it fails |
| 50 | for (int32_t n = 1;; n++) { |
| 51 | auto result = fib.call(store, {n}); |
| 52 | if (!result) { |
| 53 | std::cout << "Exhausted fuel computing fib(" << n << ")\n"; |
| 54 | break; |
| 55 | } |
| 56 | uint64_t consumed = kStoreFuel - store.context().get_fuel().unwrap(); |
| 57 | auto fib_result = std::move(result).unwrap()[0].i32(); |
| 58 | |
| 59 | std::cout << "fib(" << n << ") = " << fib_result << " [consumed " |
| 60 | << consumed << " fuel]\n"; |
| 61 | store.context().set_fuel(kStoreFuel).unwrap(); |
| 62 | } |
| 63 | } |