default

Function default 

Source
pub fn default<O>(
    body: impl FnOnce(&DefaultAllocator<'_, DEFAULT_ARRAY_BUFFER>) -> O,
) -> O
Expand description

Call the given block body with an instance of the DefaultAllocator.

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 Slice allocator with DEFAULT_ARRAY_BUFFER bytes allocated on the stack. The second parameters allows for this to be tweaked.

Note that the DEFAULT_ARRAY_BUFFER parameter is always present since it is necessary to make the type generic over all default allocators.

§Examples

use musli::alloc::{AllocError, Vec};

musli::alloc::default(|alloc| {
    let mut a = Vec::new_in(alloc);
    let mut b = Vec::new_in(alloc);

    b.extend_from_slice(b"He11o")?;
    a.extend_from_slice(b.as_slice())?;

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

    a.extend_from_slice(b" W0rld")?;

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

    let mut c = Vec::new_in(alloc);
    c.extend_from_slice(b"!")?;
    a.extend_from_slice(c.as_slice())?;

    assert_eq!(a.as_slice(), b"He11o W0rld!");
    assert_eq!(a.len(), 12);
    Ok::<_, AllocError>(())
});