aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorNatasha Moongrave <natasha@256phi.eu>2026-04-01 20:03:09 +0200
committerNatasha Moongrave <natasha@256phi.eu>2026-04-01 20:03:09 +0200
commitaef9730a5ec7740f8c9753f64c5a757cccc44f82 (patch)
treee6904a0acf6e5c4667b827b6b4c8ba5e1425e30f
parentdbb6185594fcb34e1861f09d2358bc17029fd70a (diff)
implemented a bump allocator
-rw-r--r--StrixKernel/src/allocator/bump.rs61
1 files changed, 61 insertions, 0 deletions
diff --git a/StrixKernel/src/allocator/bump.rs b/StrixKernel/src/allocator/bump.rs
new file mode 100644
index 0000000..d6d2885
--- /dev/null
+++ b/StrixKernel/src/allocator/bump.rs
@@ -0,0 +1,61 @@
+use super::{Locked, align_up};
+use alloc::alloc::{GlobalAlloc, Layout};
+use core::ptr;
+
+pub struct BumpAllocator {
+ heap_start: usize,
+ heap_end: usize,
+ next: usize,
+ allocations: usize,
+}
+
+impl BumpAllocator {
+ /// Creates a new empty bump allocator.
+ pub const fn new() -> Self {
+ BumpAllocator {
+ heap_start: 0,
+ heap_end: 0,
+ next: 0,
+ allocations: 0,
+ }
+ }
+
+ /// Initializes the bump allocator with the given heap bounds.
+ ///
+ /// This method is unsafe because the caller must ensure that the given
+ /// memory range is unused. Also, this method must be called only once.
+ pub unsafe fn init(&mut self, heap_start: usize, heap_size: usize) {
+ self.heap_start = heap_start;
+ self.heap_end = heap_start.saturating_add(heap_size);
+ self.next = heap_start;
+ }
+}
+
+unsafe impl GlobalAlloc for Locked<BumpAllocator> {
+ unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
+ let mut bump = self.lock(); // get a mutable reference
+
+ let alloc_start = align_up(bump.next, layout.align());
+ let alloc_end = match alloc_start.checked_add(layout.size()) {
+ Some(end) => end,
+ None => return ptr::null_mut(),
+ };
+
+ if alloc_end > bump.heap_end {
+ ptr::null_mut() // out of memory
+ } else {
+ bump.next = alloc_end;
+ bump.allocations += 1;
+ alloc_start as *mut u8
+ }
+ }
+
+ unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {
+ let mut bump = self.lock(); // get a mutable reference
+
+ bump.allocations -= 1;
+ if bump.allocations == 0 {
+ bump.next = bump.heap_start;
+ }
+ }
+} \ No newline at end of file