refactor reallocate

This commit is contained in:
Folkert 2021-05-01 22:15:34 +02:00
parent 040375a80f
commit b79230c069
3 changed files with 31 additions and 17 deletions

View file

@ -88,23 +88,8 @@ pub const RocList = extern struct {
) RocList {
if (self.bytes) |source_ptr| {
if (self.isUnique()) {
const align_width: usize = blk: {
if (alignment > 8) {
break :blk (2 * @sizeOf(usize));
} else {
break :blk @sizeOf(usize);
}
};
const new_source = utils.unsafeReallocate(source_ptr, allocator, alignment, self.len(), new_length, element_width);
const old_width = align_width + self.len() * element_width;
const new_width = align_width + new_length * element_width;
// TODO handle out of memory
// NOTE realloc will dealloc the original allocation
const old_allocation = (source_ptr - align_width)[0..old_width];
const new_allocation = allocator.realloc(old_allocation, new_width) catch unreachable;
const new_source = @ptrCast([*]u8, new_allocation) + align_width;
return RocList{ .bytes = new_source, .length = new_length };
}
}

View file

@ -140,6 +140,34 @@ pub fn allocateWithRefcount(
}
}
pub fn unsafeReallocate(
source_ptr: [*]u8,
allocator: *Allocator,
alignment: usize,
old_length: usize,
new_length: usize,
element_width: usize,
) [*]u8 {
const align_width: usize = blk: {
if (alignment > 8) {
break :blk (2 * @sizeOf(usize));
} else {
break :blk @sizeOf(usize);
}
};
const old_width = align_width + old_length * element_width;
const new_width = align_width + new_length * element_width;
// TODO handle out of memory
// NOTE realloc will dealloc the original allocation
const old_allocation = (source_ptr - align_width)[0..old_width];
const new_allocation = allocator.realloc(old_allocation, new_width) catch unreachable;
const new_source = @ptrCast([*]u8, new_allocation) + align_width;
return new_source;
}
pub const RocResult = extern struct {
bytes: ?[*]u8,