Making Arenas Memory-Safe Via New Standard Trait?

Starting to learn about and applying more advanced Rust patterns I discovered arenas, specialized memory allocators that allow you to batch deallocation of objects with similar lifetimes.

One issue however I've been encountering using popular arena creates like bumpalo is the fact that if you're not careful it's quite easy to leak memory with these libraries.

This is because a big part of the savings when it comes to using arenas is the idea that you don't need to individually drop objects anymore, the arena drops everything at once without running each object's drop implementation.

This is a problem for types like Vec, String, etc. that manage their own heap allocation. Skipping drop leaks memory.

However if there was some trait like HandlesOwnHeap or RequiresDrop for Vec then e.g. bumpalo's Bump arena could have a trait bound on its alloc method that prevents you from accidentally using it with such a struct.

There is needs_drop in std::mem - Rust. You could write a wrapper and check it in a const block. That wouldn't be as nice a trait bounds but you still get a compile time error.

2 Likes

I haven't used const much yet, do const panics show up at compile time?

This is false.

However: bumpalo::boxed::Box can be used to wrap T values allocated in the Bump arena, and calls T’s Drop implementation when the Box wrapper goes out of scope.

It's actually not, from bumpalo's own docs:

This makes mass deallocation extremely fast, but allocated objects' Drop implementations are not invoked.

Yes you can use their box but this does not solve the key problem I was laying out: that by default usage of arenas like bumpalo are not memory safe and that you have to actively think about this.

While I get what you’re saying, leaking memory is a memory safe (but often undesirable) operation.