Commit e14fcd60cb

Coleman Broaddus <coleman.broaddus@gmail.com>
2021-09-22 11:09:16
FIX resize() for non u8 element types. (#9806)
1 parent 4afe4bd
Changed files (2)
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);
 }
 
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.