Skip to content

Commit

Permalink
fix: allocate small blocks first
Browse files Browse the repository at this point in the history
  • Loading branch information
maolonglong committed Oct 14, 2023
1 parent 56a35d1 commit 7b644bc
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/buddy2.zig
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,9 @@ pub const Buddy2 = struct {

var node_size = self.len;
while (node_size != new_len) : (node_size /= 2) {
if (self.longest(left(index)) >= new_len) {
const left_longest = self.longest(left(index));
const right_longest = self.longest(right(index));
if (left_longest >= new_len and (right_longest < new_len or right_longest >= left_longest)) {
index = left(index);
} else {
index = right(index);
Expand Down Expand Up @@ -330,4 +332,12 @@ test "Buddy2" {
try testing.expectEqual(@as(usize, 0), buddy2.alloc(16).?);
try testing.expectEqual(@as(usize, 16), buddy2.size(0));
try testing.expect(buddy2.alloc(1) == null);
buddy2.free(0);

// Allocate small blocks first.
try testing.expectEqual(@as(usize, 0), buddy2.alloc(8).?);
try testing.expectEqual(@as(usize, 8), buddy2.alloc(4).?);
buddy2.free(0);
try testing.expectEqual(@as(usize, 12), buddy2.alloc(4).?);
try testing.expectEqual(@as(usize, 0), buddy2.alloc(8).?);
}

0 comments on commit 7b644bc

Please sign in to comment.