logoalt Hacker News

tialaramex • yesterday at 11:50 AM • 1 reply • view on HN

> If you are writing in C you can write a bump allocator in 10 minutes if you know how to do it. It is basically impossible to do that in rust.

Your bump allocator is just a type with a "how much is left?" usize and a blob of reserved memory it owns, plus an implementation of the Allocator trait which has two (unsafe) functions.

The first one is easy, we're a bump allocator, deallocation is a no-op:

  deallocate(&self, _ptr: NonNull<u8>, _layout: Layout) {}
So that just leaves implementing

  allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> { todo!() }
In our bump allocator that's just not very much work. Decide if there's enough space, if there isn't fail early, otherwise make a NonNull<[u8]> and decrease our "How much is left" counter.

Is it slightly more work than in C? Yeah, I guess so, but not much.


Replies

ozgrakkurt • yesterday at 11:58 AM

You have to manage the lifetimes too, also you need to be able to set_offset() on bump allocator to use it effectively in my experience. You can't just increment/increment then drop it. Having a way of rolling it back to point x makes it a lot better.