#allocator #off #allocation #turn #alive #lock #alloc

no-std nalloc

An allocator wrapper that can be turned on and off

3 releases

0.1.2 Jun 5, 2020
0.1.1 Jun 5, 2020
0.1.0 Jun 5, 2020

#401 in Memory management

MIT/Apache

8KB
71 lines

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.

# extern crate std;
#[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.

No runtime deps