|
| 1 | +use core::alloc::{GlobalAlloc, Layout}; |
| 2 | +use core::cell::UnsafeCell; |
| 3 | + |
| 4 | +#[global_allocator] |
| 5 | +static ALLOCATOR: ArenaAllocator = ArenaAllocator::new(); |
| 6 | + |
| 7 | +/// Very simple allocator which never deallocates memory |
| 8 | +/// |
| 9 | +/// Based on the example from |
| 10 | +/// https://doc.rust-lang.org/stable/std/alloc/trait.GlobalAlloc.html |
| 11 | +pub struct ArenaAllocator { |
| 12 | + arena: UnsafeCell<Arena>, |
| 13 | +} |
| 14 | + |
| 15 | +impl ArenaAllocator { |
| 16 | + pub const fn new() -> Self { |
| 17 | + Self { |
| 18 | + arena: UnsafeCell::new(Arena::new()), |
| 19 | + } |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +/// Safe because we are singlethreaded |
| 24 | +unsafe impl Sync for ArenaAllocator {} |
| 25 | + |
| 26 | +unsafe impl GlobalAlloc for ArenaAllocator { |
| 27 | + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { |
| 28 | + let arena = &mut *self.arena.get(); |
| 29 | + arena.alloc(layout) |
| 30 | + } |
| 31 | + |
| 32 | + unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {} |
| 33 | +} |
| 34 | + |
| 35 | +const ARENA_SIZE: usize = 64 * 1024; // more than enough |
| 36 | + |
| 37 | +#[repr(C, align(4096))] |
| 38 | +struct Arena { |
| 39 | + buf: [u8; ARENA_SIZE], // aligned at 4096 |
| 40 | + allocated: usize, |
| 41 | +} |
| 42 | + |
| 43 | +impl Arena { |
| 44 | + pub const fn new() -> Self { |
| 45 | + Self { |
| 46 | + buf: [0x55; ARENA_SIZE], |
| 47 | + allocated: 0, |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + pub unsafe fn alloc(&mut self, layout: Layout) -> *mut u8 { |
| 52 | + if layout.align() > 4096 || layout.size() > ARENA_SIZE { |
| 53 | + return core::ptr::null_mut(); |
| 54 | + } |
| 55 | + |
| 56 | + let align_minus_one = layout.align() - 1; |
| 57 | + let start = (self.allocated + align_minus_one) & !align_minus_one; // round up |
| 58 | + let new_cursor = start + layout.size(); |
| 59 | + |
| 60 | + if new_cursor >= ARENA_SIZE { |
| 61 | + return core::ptr::null_mut(); |
| 62 | + } |
| 63 | + |
| 64 | + self.allocated = new_cursor; |
| 65 | + self.buf.as_mut_ptr().add(start) |
| 66 | + } |
| 67 | +} |
0 commit comments