1pub const HEAP_START: usize = 0x8040_0000;
20
21pub const HEAP_SIZE: usize = 1024 * 1024;
23
24pub mod bump;
29#[cfg(feature = "fixed_size_allocator")]
30pub mod fixed_size_block;
31pub mod linked_list;
32
33use linked_list::LinkedListAllocator;
34
35pub struct Locked<A> {
37 inner: spin::Mutex<A>,
38}
39
40impl<A> Locked<A> {
41 pub const fn new(inner: A) -> Self {
42 Locked {
43 inner: spin::Mutex::new(inner),
44 }
45 }
46
47 pub fn lock(&self) -> spin::MutexGuard<'_, A> {
48 self.inner.lock()
49 }
50}
51
52#[global_allocator]
57static ALLOCATOR: Locked<LinkedListAllocator> = Locked::new(LinkedListAllocator::new());
58
59pub fn init_heap(
69 _frame_allocator: &mut crate::memory::SimpleFrameAllocator,
70) -> Result<(), &'static str> {
71 extern "C" {
75 static heap_start: u8;
76 static heap_end: u8;
77 }
78
79 let start = unsafe { &heap_start as *const u8 as usize };
80 let end = unsafe { &heap_end as *const u8 as usize };
81 let size = end - start;
82
83 unsafe {
84 ALLOCATOR.lock().init(start, size);
85 }
86
87 crate::serial_println!("[ALLOCATOR] Heap initialized");
88 Ok(())
89}
90
91#[cfg(test)]
99mod tests {
100 use alloc::{boxed::Box, vec::Vec};
101
102 #[test_case]
103 fn test_heap_allocation() {
104 let heap_value = Box::new(41);
105 assert_eq!(*heap_value, 41);
106 }
107
108 #[test_case]
109 fn test_large_vec() {
110 let n = 1000;
111 let mut vec = Vec::new();
112 for i in 0..n {
113 vec.push(i);
114 }
115 assert_eq!(vec.iter().sum::<u64>(), (n - 1) * n / 2);
116 }
117
118 #[test_case]
119 fn test_many_boxes() {
120 for i in 0..10000 {
121 let x = Box::new(i);
122 assert_eq!(*x, i);
123 }
124 }
125}