rune::runtime::budget

Function with

Source
pub fn with<T>(budget: usize, value: T) -> Budget<T> 
Expand description

Wrap the given value with a budget.

Budgeting is only performed on a per-instruction basis in the virtual machine. What exactly constitutes an instruction might be a bit vague. But important to note is that without explicit co-operation from native functions the budget cannot be enforced. So care must be taken with the native functions that you provide to Rune to ensure that the limits you impose cannot be circumvented.

The following things can be wrapped:

  • A FnOnce closure, like with(|| println!("Hello World")).call().
  • A Future, like with(async { /* async work */ }).await;

It’s also possible to wrap other wrappers which implement Callable.

§Examples

use rune::runtime::budget;
use rune::Vm;

let mut vm: Vm = todo!();
// The virtual machine and any tasks associated with it is only allowed to execute 100 budget.
budget::with(100, || vm.call(&["main"], ())).call()?;

This budget can be conveniently combined with the memory limit module due to both wrappers implementing Callable.

use rune::runtime::budget;
use rune::alloc::{limit, Vec};

#[derive(Debug, PartialEq)]
struct Marker;

// Limit the given closure to run one instruction and allocate 1024 bytes.
let f = budget::with(1, limit::with(1024, || {
    let mut budget = budget::acquire();
    assert!(budget.take());
    assert!(!budget.take());
    assert!(Vec::<u8>::try_with_capacity(1).is_ok());
    assert!(Vec::<u8>::try_with_capacity(1024).is_ok());
    assert!(Vec::<u8>::try_with_capacity(1025).is_err());
    Marker
}));

assert_eq!(f.call(), Marker);