allocation-counter
A Rust library that runs code while counting heap allocations, for profiling and allocation-budget assertions.
Repository Health
Technical Analysis
allocation-counter is a small Rust library for measuring how many heap allocations a piece of code performs. It installs a custom global allocator that increments a thread-local counter on every allocation before delegating to the system allocator, so you can inspect exactly how much memory work your code triggers.
It is most valuable in tests: you can assert that a hot path performs zero (or a bounded number of) allocations, turning allocation regressions into failing tests rather than silent performance drift.
What You Get
- A
measure()function that runs any closure and returns detailed allocation statistics - An
AllocationInfostruct reporting total and peak allocation counts plus byte totals - A custom
#[global_allocator]that transparently delegates to the system allocator - An
opt_out()helper to exclude specific regions from being counted - Nested-measurement support up to a fixed depth for measuring inner scopes independently
Common Use Cases
- Asserting in a unit test that a hot code path performs zero heap allocations
- Setting an allocation budget and failing CI when code exceeds it
- Profiling how much memory allocation a given operation triggers during development
- Catching allocation regressions introduced by refactors or dependency upgrades
Under The Hood
Architecture - The crate has two files: allocator.rs defines a CountingAllocator implementing GlobalAlloc that, on each alloc/dealloc, updates a thread-local AllocationInfoStack (a fixed 64-entry depth stack) before delegating to std::alloc::System; lib.rs exposes measure, opt_out, and the AllocationInfo result type, and installs the counting allocator via #[global_allocator]. A DO_COUNT thread-local flag lets counting be temporarily suppressed. Tech Stack - Pure Rust (edition 2021) with zero external runtime dependencies, relying only on std::alloc primitives and thread-local storage. Code Quality - The code is compact (~330 lines) and carries several inline #[test] cases exercising nested measurement and opt-out behavior; the unsafe allocator impl is minimal and clearly bounded. API Design - The public surface is a single measure(closure) -> AllocationInfo call plus an opt_out escape hatch, making it trivial to add an allocation assertion to an existing test with one line.