Skip to content

Commit

Permalink
Split into smaller blocks if the order of block size is larger than m…
Browse files Browse the repository at this point in the history
…ax order

Signed-off-by: bigsaltyfishes <[email protected]>
  • Loading branch information
bigsaltyfishes committed Sep 21, 2024
1 parent 95e5d6c commit 95ed662
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,18 @@ impl<const ORDER: usize> Heap<ORDER> {

while current_start + size_of::<usize>() <= end {
let lowbit = current_start & (!current_start + 1);
let size = min(lowbit, prev_power_of_two(end - current_start));
let mut size = min(lowbit, prev_power_of_two(end - current_start));

// If the order of size is larger than the max order,
// split it into smaller blocks.
let mut order = size.trailing_zeros() as usize;
if order > ORDER - 1 {
order = ORDER - 1;
size = 1 << order;
}
total += size;

self.free_list[size.trailing_zeros() as usize].push(current_start as *mut usize);
self.free_list[order].push(current_start as *mut usize);
current_start += size;
}

Expand Down
15 changes: 15 additions & 0 deletions src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,21 @@ fn test_heap_add() {
assert!(addr.is_ok());
}

#[test]
fn test_heap_add_large() {
// Max size of block is 2^7 == 128 bytes
let mut heap = Heap::<8>::new();
assert!(heap.alloc(Layout::from_size_align(1, 1).unwrap()).is_err());

// 512 bytes of space
let space: [u8; 512] = [0; 512];
unsafe {
heap.add_to_heap(space.as_ptr() as usize, space.as_ptr().add(100) as usize);
}
let addr = heap.alloc(Layout::from_size_align(1, 1).unwrap());
assert!(addr.is_ok());
}

#[test]
fn test_heap_oom() {
let mut heap = Heap::<32>::new();
Expand Down

0 comments on commit 95ed662

Please sign in to comment.