[][src]Crate nalloc

This crate contains an allocator that can be used to wrap another allocator to turn allocation on and off. This is meant to be used in unit tests.

To use it, declare a static variable with the #[global_allocator] attribute. It can wrap any allocator implementing GlobalAlloc.

#[global_allocator]
static ALLOCATOR: nalloc::NAlloc<std::alloc::System> = {
    nalloc::NAlloc::new(std::alloc::System)
};

Allocation is allowed by default. To prevent it, call the deny method on the allocator. When allocation is attempted while a lock is alive, the process will abort.

let this_is_allowed = vec![1, 2, 3];

let _lock = ALLOCATOR.deny();
let this_will_abort = vec![4, 5, 6];

Limitations

Parallel tests

Note that by nature, the default test executor will use this allocator if you add it in your test module. This will cause issues as the test executor itself allocate memory. You can circumvent this by using cargo test -- --test-threads=1.

Aborting

If allocation is attempted while a lock is alive, the process will abort. This means the entire process will be killed, rather than a single thread, and it is not catchable with catch_unwind.

Structs

AllocationLocker

A lock that must be kept alive as long as no allocation is allowed.

NAlloc

A wrapper around an allocator to turn allocation on and off.