|
| 1 | +//! A one-shot allocator. |
| 2 | +//! |
| 3 | +//! This is a simple allocator design which can only allocate once. |
| 4 | +
|
| 5 | +use core::cell::Cell; |
| 6 | +use core::mem::MaybeUninit; |
| 7 | +use core::ptr::NonNull; |
| 8 | + |
| 9 | +use allocator_api2::alloc::{AllocError, Allocator, Layout}; |
| 10 | + |
| 11 | +/// A simple, `!Sync` implementation of a one-shot allocator. |
| 12 | +/// |
| 13 | +/// This allocator manages the provided memory. |
| 14 | +pub struct OneshotAllocator { |
| 15 | + mem: Cell<*mut u8>, |
| 16 | +} |
| 17 | + |
| 18 | +unsafe impl Allocator for OneshotAllocator { |
| 19 | + fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> { |
| 20 | + assert!(layout.align() <= 8); |
| 21 | + // `mem` is already aligned. |
| 22 | + |
| 23 | + match NonNull::new(self.mem.take()) { |
| 24 | + None => return Err(AllocError), |
| 25 | + Some(mem) => { |
| 26 | + let mid = layout.size(); |
| 27 | + if mid >= (isize::MAX / 2) { |
| 28 | + self.mem.set(mem); |
| 29 | + Err(AllocError) |
| 30 | + } else { |
| 31 | + Ok(mem) |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) { |
| 38 | + if self.mem.get().is_null() { |
| 39 | + self.mem.set(ptr); |
| 40 | + } else { |
| 41 | + #[cfg(debug_assertions)] |
| 42 | + panic!("Tried to deallocate pointer that was allocated from a different allocator"); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + unsafe fn grow( |
| 47 | + &self, |
| 48 | + ptr: NonNull<u8>, |
| 49 | + old_layout: Layout, |
| 50 | + new_layout: Layout, |
| 51 | + ) -> Result<NonNull<[u8]>, AllocError> { |
| 52 | + assert!(new_layout.align() <= 8); |
| 53 | + Ok(ptr) |
| 54 | + } |
| 55 | + |
| 56 | + unsafe fn grow_zeroed( |
| 57 | + &self, |
| 58 | + ptr: NonNull<u8>, |
| 59 | + old_layout: Layout, |
| 60 | + new_layout: Layout, |
| 61 | + ) -> Result<NonNull<[u8]>, AllocError> { |
| 62 | + assert!( |
| 63 | + new_layout.size() >= old_layout.size(), |
| 64 | + "`new_layout.size()` must be greater than or equal to `old_layout.size()`" |
| 65 | + ); |
| 66 | + assert!(new_layout.align() <= 8); |
| 67 | + |
| 68 | + unsafe { |
| 69 | + ptr.add(old_layout.size()) |
| 70 | + .as_ptr() |
| 71 | + .write_bytes(0, new_layout.size() - old_layout.size()) |
| 72 | + }; |
| 73 | + |
| 74 | + Ok(ptr) |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +impl BumpAllocator { |
| 79 | + pub fn new(ptr: NonNull<u8>) -> Self { |
| 80 | + let align_offset = ptr.align_offset(8); |
| 81 | + Self { |
| 82 | + mem: Cell::new(ptr.add(align_offset)), |
| 83 | + } |
| 84 | + } |
| 85 | +} |
0 commit comments