fix: Allocator.remap now handles zero-bytes sized types

This commit is contained in:
samy007 2025-03-24 22:05:57 +01:00
parent 539f3effd3
commit be483dabc8
2 changed files with 20 additions and 0 deletions

View File

@ -228,6 +228,18 @@ test "Allocator.resize" {
} }
} }
test "Allocator alloc and remap with zero-bit type" {
var values = try testing.allocator.alloc(void, 10);
defer testing.allocator.free(values);
try testing.expectEqual(10, values.len);
const remaped = testing.allocator.remap(values, 200);
try testing.expect(remaped != null);
values = remaped.?;
try testing.expectEqual(200, values.len);
}
/// Copy all of source into dest at position 0. /// Copy all of source into dest at position 0.
/// dest.len must be >= source.len. /// dest.len must be >= source.len.
/// If the slices overlap, dest.ptr must be <= src.ptr. /// If the slices overlap, dest.ptr must be <= src.ptr.

View File

@ -311,12 +311,15 @@ pub fn resize(self: Allocator, allocation: anytype, new_len: usize) bool {
/// `allocation` may be an empty slice, in which case a new allocation is made. /// `allocation` may be an empty slice, in which case a new allocation is made.
/// ///
/// `new_len` may be zero, in which case the allocation is freed. /// `new_len` may be zero, in which case the allocation is freed.
///
/// If the allocation's elements' type is zero bytes sized, `allocation.len` is set to `new_len`.
pub fn remap(self: Allocator, allocation: anytype, new_len: usize) t: { pub fn remap(self: Allocator, allocation: anytype, new_len: usize) t: {
const Slice = @typeInfo(@TypeOf(allocation)).pointer; const Slice = @typeInfo(@TypeOf(allocation)).pointer;
break :t ?[]align(Slice.alignment) Slice.child; break :t ?[]align(Slice.alignment) Slice.child;
} { } {
const Slice = @typeInfo(@TypeOf(allocation)).pointer; const Slice = @typeInfo(@TypeOf(allocation)).pointer;
const T = Slice.child; const T = Slice.child;
const alignment = Slice.alignment; const alignment = Slice.alignment;
if (new_len == 0) { if (new_len == 0) {
self.free(allocation); self.free(allocation);
@ -325,6 +328,11 @@ pub fn remap(self: Allocator, allocation: anytype, new_len: usize) t: {
if (allocation.len == 0) { if (allocation.len == 0) {
return null; return null;
} }
if (@sizeOf(T) == 0) {
var new_memory = allocation;
new_memory.len = new_len;
return new_memory;
}
const old_memory = mem.sliceAsBytes(allocation); const old_memory = mem.sliceAsBytes(allocation);
// I would like to use saturating multiplication here, but LLVM cannot lower it // I would like to use saturating multiplication here, but LLVM cannot lower it
// on WebAssembly: https://github.com/ziglang/zig/issues/9660 // on WebAssembly: https://github.com/ziglang/zig/issues/9660