with

Function with 

Source
pub fn with<F, O>(f: F) -> O
where F: FnOnce(&Default<'_>) -> O,
Expand description

Call the given closure with the default allocator.

This is useful if you want to write application which are agnostic to whether the alloc feature is or isn’t enabled.

  • If the alloc feature is enabled, this is the System allocator.
  • If the alloc feature is disabled, this is the Stack allocator with DEFAULT_STACK_BUFFER bytes allocated on the stack.

§Examples

use musli::{Allocator, Buf};

musli_allocator::with(|alloc| {
    let mut a = alloc.alloc().expect("allocation a failed");
    let mut b = alloc.alloc().expect("allocation b failed");

    b.write(b"He11o");
    a.write(b.as_slice());

    assert_eq!(a.as_slice(), b"He11o");
    assert_eq!(a.len(), 5);

    a.write(b" W0rld");

    assert_eq!(a.as_slice(), b"He11o W0rld");
    assert_eq!(a.len(), 11);

    let mut c = alloc.alloc().expect("allocation c failed");
    c.write(b"!");
    a.write(c.as_slice());

    assert_eq!(a.as_slice(), b"He11o W0rld!");
    assert_eq!(a.len(), 12);
});