authorgravatar for samy2014@free.frsamy007 <samy2014@free.fr> 2025-03-24 22:05:57+01:00
committergravatar for samy2014@free.frsamy007 <samy2014@free.fr> 2025-03-24 22:05:57+01:00
logbe483dabc8fade06ad21b1e45c2bc731c4c4dd4f
treeb8e95591c17afdd822eb61ef6fe48dbaf6983b79
parent539f3effd38fac03cacd81338949650297071491

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


2 files changed, 20 insertions(+), 0 deletions(-)

lib/std/mem.zig+12
......@@ -228,6 +228,18 @@ test "Allocator.resize" {
228228 }
229229}
230230
231test "Allocator alloc and remap with zero-bit type" {
232 var values = try testing.allocator.alloc(void, 10);
233 defer testing.allocator.free(values);
234
235 try testing.expectEqual(10, values.len);
236 const remaped = testing.allocator.remap(values, 200);
237 try testing.expect(remaped != null);
238
239 values = remaped.?;
240 try testing.expectEqual(200, values.len);
241}
242
231243/// Copy all of source into dest at position 0.
232244/// dest.len must be >= source.len.
233245/// If the slices overlap, dest.ptr must be <= src.ptr.
lib/std/mem/Allocator.zig+8
......@@ -311,12 +311,15 @@ pub fn resize(self: Allocator, allocation: anytype, new_len: usize) bool {
311311/// `allocation` may be an empty slice, in which case a new allocation is made.
312312///
313313/// `new_len` may be zero, in which case the allocation is freed.
314///
315/// If the allocation's elements' type is zero bytes sized, `allocation.len` is set to `new_len`.
314316pub fn remap(self: Allocator, allocation: anytype, new_len: usize) t: {
315317 const Slice = @typeInfo(@TypeOf(allocation)).pointer;
316318 break :t ?[]align(Slice.alignment) Slice.child;
317319} {
318320 const Slice = @typeInfo(@TypeOf(allocation)).pointer;
319321 const T = Slice.child;
322
320323 const alignment = Slice.alignment;
321324 if (new_len == 0) {
322325 self.free(allocation);
......@@ -325,6 +328,11 @@ pub fn remap(self: Allocator, allocation: anytype, new_len: usize) t: {
325328 if (allocation.len == 0) {
326329 return null;
327330 }
331 if (@sizeOf(T) == 0) {
332 var new_memory = allocation;
333 new_memory.len = new_len;
334 return new_memory;
335 }
328336 const old_memory = mem.sliceAsBytes(allocation);
329337 // I would like to use saturating multiplication here, but LLVM cannot lower it
330338 // on WebAssembly: https://github.com/ziglang/zig/issues/9660