pub const HEAP_START: usize = 0x8040_0000;
pub const HEAP_SIZE: usize = 1024 * 1024;
pub mod bump;
#[cfg(feature = "fixed_size_allocator")]
pub mod fixed_size_block;
pub mod linked_list;
use linked_list::LinkedListAllocator;
pub struct Locked<A> {
inner: spin::Mutex<A>,
}
impl<A> Locked<A> {
pub const fn new(inner: A) -> Self {
Locked {
inner: spin::Mutex::new(inner),
}
}
pub fn lock(&self) -> spin::MutexGuard<'_, A> {
self.inner.lock()
}
}
#[global_allocator]
static ALLOCATOR: Locked<LinkedListAllocator> = Locked::new(LinkedListAllocator::new());
pub fn init_heap(
_frame_allocator: &mut crate::memory::SimpleFrameAllocator,
) -> Result<(), &'static str> {
extern "C" {
static heap_start: u8;
static heap_end: u8;
}
let start = unsafe { &heap_start as *const u8 as usize };
let end = unsafe { &heap_end as *const u8 as usize };
let size = end - start;
unsafe {
ALLOCATOR.lock().init(start, size);
}
crate::serial_println!("[ALLOCATOR] Heap initialized");
Ok(())
}
#[cfg(test)]
mod tests {
use alloc::{boxed::Box, vec::Vec};
#[test_case]
fn test_heap_allocation() {
let heap_value = Box::new(41);
assert_eq!(*heap_value, 41);
}
#[test_case]
fn test_large_vec() {
let n = 1000;
let mut vec = Vec::new();
for i in 0..n {
vec.push(i);
}
assert_eq!(vec.iter().sum::<u64>(), (n - 1) * n / 2);
}
#[test_case]
fn test_many_boxes() {
for i in 0..10000 {
let x = Box::new(i);
assert_eq!(*x, i);
}
}
}