From e14fcd60cb11d731ca19f97e5b0b6247aa7cf07b Mon Sep 17 00:00:00 2001 From: Coleman Broaddus Date: Wed, 22 Sep 2021 05:09:16 -0400 Subject: [PATCH] FIX resize() for non u8 element types. (#9806) --- lib/std/mem.zig | 40 +++++++++++++++++++++++++++++++++++++++ lib/std/mem/Allocator.zig | 2 +- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/lib/std/mem.zig b/lib/std/mem.zig index 95d4c919db..b3d0755adc 100644 --- a/lib/std/mem.zig +++ b/lib/std/mem.zig @@ -147,6 +147,46 @@ test "mem.Allocator basics" { try testing.expectError(error.OutOfMemory, failAllocator.allocSentinel(u8, 1, 0)); } +test "Allocator.resize" { + const primitiveIntTypes = .{ + i8, + u8, + i16, + u16, + i32, + u32, + i64, + u64, + i128, + u128, + isize, + usize, + }; + inline for (primitiveIntTypes) |T| { + var values = try testing.allocator.alloc(T, 100); + defer testing.allocator.free(values); + + for (values) |*v, i| v.* = @intCast(T, i); + values = try testing.allocator.resize(values, values.len + 10); + try testing.expect(values.len == 110); + } + + const primitiveFloatTypes = .{ + f16, + f32, + f64, + f128, + }; + inline for (primitiveFloatTypes) |T| { + var values = try testing.allocator.alloc(T, 100); + defer testing.allocator.free(values); + + for (values) |*v, i| v.* = @intToFloat(T, i); + values = try testing.allocator.resize(values, values.len + 10); + try testing.expect(values.len == 110); + } +} + /// Copy all of source into dest at position 0. /// dest.len must be >= source.len. /// If the slices overlap, dest.ptr must be <= src.ptr. diff --git a/lib/std/mem/Allocator.zig b/lib/std/mem/Allocator.zig index 9ea7aeb90e..a76c27f5a0 100644 --- a/lib/std/mem/Allocator.zig +++ b/lib/std/mem/Allocator.zig @@ -313,7 +313,7 @@ pub fn resize(self: *Allocator, old_mem: anytype, new_n: usize) Error!@TypeOf(ol const new_byte_count = math.mul(usize, @sizeOf(T), new_n) catch return Error.OutOfMemory; const rc = try self.resizeFn(self, old_byte_slice, Slice.alignment, new_byte_count, 0, @returnAddress()); assert(rc == new_byte_count); - const new_byte_slice = old_mem.ptr[0..new_byte_count]; + const new_byte_slice = old_byte_slice.ptr[0..new_byte_count]; return mem.bytesAsSlice(T, new_byte_slice); }