Skip to content

Commit 95ed662

Browse files
Split into smaller blocks if the order of block size is larger than max order
Signed-off-by: bigsaltyfishes <bigsaltyfishes@gmail.com>
1 parent 95e5d6c commit 95ed662

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

src/lib.rs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,10 +88,18 @@ impl<const ORDER: usize> Heap<ORDER> {
8888

8989
while current_start + size_of::<usize>() <= end {
9090
let lowbit = current_start & (!current_start + 1);
91-
let size = min(lowbit, prev_power_of_two(end - current_start));
91+
let mut size = min(lowbit, prev_power_of_two(end - current_start));
92+
93+
// If the order of size is larger than the max order,
94+
// split it into smaller blocks.
95+
let mut order = size.trailing_zeros() as usize;
96+
if order > ORDER - 1 {
97+
order = ORDER - 1;
98+
size = 1 << order;
99+
}
92100
total += size;
93101

94-
self.free_list[size.trailing_zeros() as usize].push(current_start as *mut usize);
102+
self.free_list[order].push(current_start as *mut usize);
95103
current_start += size;
96104
}
97105

src/test.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,21 @@ fn test_heap_add() {
6060
assert!(addr.is_ok());
6161
}
6262

63+
#[test]
64+
fn test_heap_add_large() {
65+
// Max size of block is 2^7 == 128 bytes
66+
let mut heap = Heap::<8>::new();
67+
assert!(heap.alloc(Layout::from_size_align(1, 1).unwrap()).is_err());
68+
69+
// 512 bytes of space
70+
let space: [u8; 512] = [0; 512];
71+
unsafe {
72+
heap.add_to_heap(space.as_ptr() as usize, space.as_ptr().add(100) as usize);
73+
}
74+
let addr = heap.alloc(Layout::from_size_align(1, 1).unwrap());
75+
assert!(addr.is_ok());
76+
}
77+
6378
#[test]
6479
fn test_heap_oom() {
6580
let mut heap = Heap::<32>::new();

0 commit comments

Comments
 (0)