Variable sized allocations on a stack

I wanted to have a lot of temporary allocations and deallocations on a stack, with variable sizes, but whose total size I can predict at the beginning of the computation. I could just allocate from the heap each time, but that creates unnecessary overhead for such a simple pattern where I can just get the memory from the heap once and then allocate and deallocate on a stack in constant time.

Is there a crate for this? I have seen bumpalo, but it doesn't quite match the requirement because it doesn't guarantee deallocated memory can be reused.

I wrote a little module that does this, ensuring at compile time that allocations and deallocations are done in a stack-like way, and am wondering whether it makes sense to publish.

How do you make sure that the deallocated space on the stack can be reused?

Lifetimes keep track of whether a chunk of memory has been allocated from. An allocation takes a mutable reference to a chunk of memory, and returns a new, smaller chunk of remaining memory. So you can only allocate again at the beginning of the chunk if all the allocations are no longer alive.

Ah, ok. I don't know whether bumpalo supports the allocation to be on the stack, but if you are in a situation where all the elements are destroyed when you need more elements, bumpalo should also be able to reuse the memory.

I think that's only true for bumpalo if you are careful to drop everything in the exact opposite order.

The benefit of my module is that you reuse explicitly, so you're guaranteed being able to reuse, or you get a compile error. I use it in recursive functions.

The downside is that you have to precalculate the total size at the beginning, there is no grabbing extra chunks from the heap. It would probably be possible to implement that with some interior mutability tricks, but it would partially defeat the purpose of having immediate constant-time allocations.

With bumpalo you should be able to do it if you call the reset method. Since it takes a mutable reference, you can only call it if all allocations from that Bump are gone.

What I need is a partial reset: the recursive calls are done, so they don't need their memory any more, but up-stream I still have some allocations.

Ah, fair enough. Bumpalo might not have that.