rune::alloc::limit

Function with

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

Wrap the given value with a memory limit. Using a value of usize::MAX effectively disables the memory limit.

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.

See the module level documentation for more details.

§Examples

use rune::alloc::limit;
use rune::alloc::Vec;

let f = limit::with(1024, || {
    let mut vec = Vec::<u32>::try_with_capacity(256)?;

    for n in 0..256u32 {
        vec.try_push(n)?;
    }

    Ok::<_, rune::alloc::Error>(vec.into_iter().sum::<u32>())
});

let sum = f.call()?;
assert_eq!(sum, 32640);

Breaching the limit. Note that this happens because while the vector is growing it might both over-allocate, and hold onto two allocations simultaneously.

use rune::alloc::limit;
use rune::alloc::Vec;

let f = limit::with(1024, || {
    let mut vec = Vec::<u32>::new();

    for n in 0..256u32 {
        vec.try_push(n)?;
    }

    Ok::<_, rune::alloc::Error>(vec.into_iter().sum::<u32>())
});

assert!(f.call().is_err());