Crate allocation_counter
source ·Expand description
This crate provides a method to count and test the number of allocations while running some code.
Example
Add as a dependency - since including the trait replaces the global memory allocator, you most likely want it gated behind a feature.
[features]
count-allocations = ["allocation-counter"]
[dependencies]
allocation-counter = { version = "0", optional = true }
Tests can now be written to assert that the number of desired memory allocations are not exceeded.
#[cfg(feature = "count-allocations")]
#[test]
pub fn no_memory_allocations() {
let allocations = allocation_counter::count(|| {
code_that_should_not_allocate_memory();
});
assert_eq!(allocations, 0);
// Or use this utility method in this case:
allocation_counter::assert_no_allocations(|| {
code_that_should_not_allocate_memory();
});
// Can also allow a certain number of allocations:
allocation_counter::assert_max_allocations(10 || {
code_that_should_not_allocate_much();
});
// Can also assert on a range, useful to adjust
// test expectations over time:
allocation_counter::assert_num_allocations(500..600 || {
code_that_should_not_allocate_much();
});
// It's possible to opt out of counting allocations
// for certain parts of the code flow:
allocation_counter::assert_no_allocations(|| {
code_that_should_not_allocate();
allocation_counter::avoid_counting(|| {
external_code_that_should_not_be_tested();
});
code_that_should_not_allocate();
});
}
Run the tests with the necessary feature enabled.
cargo test --features count-allocations
Functions
- Run a closure and assert that the number of memory allocations are below a limit.
- Run a closure and assert that no memory allocations were made.
- Run a closure and assert that the number of memory allocations are inside a range.
- Opt out of counting allocations while running some code.
- Run a closure while counting the performed memory allocations.