feature. See also
. The project being documented here (as the example) is the Zig library itself.
Allocator.reallocAdvanced
pub fn reallocAdvanced(
self: Allocator,
old_mem: anytype,
new_n: usize,
return_address: usize,
) Error!@TypeOf(old_mem)
File
Code
pub fn reallocAdvanced(
self: Allocator,
old_mem: anytype,
new_n: usize,
return_address: usize,
) Error!@TypeOf(old_mem) {
const slice_info = @typeInfo(@TypeOf(old_mem)).pointer;
comptime assert(slice_info.size == .slice);
const T = slice_info.child;
if (old_mem.len == 0) {
return self.allocAdvancedWithRetAddr(T, .fromByteUnitsOptional(slice_info.attrs.@"align"), new_n, return_address);
}
if (new_n == 0) {
self.free(old_mem);
const alignment = slice_info.attrs.@"align" orelse @alignOf(T);
const addr = comptime std.mem.alignBackward(usize, math.maxInt(usize), alignment);
const ptr: *align(alignment) [0]T = @ptrFromInt(addr);
return ptr;
}
const old_byte_slice: []u8 = @ptrCast(@constCast(mem.absorbSentinel(old_mem)));
const byte_count = math.mul(usize, @sizeOf(T), new_n) catch return error.OutOfMemory;
if (self.rawRemap(old_byte_slice, .fromByteUnits(slice_info.attrs.@"align" orelse @alignOf(T)), byte_count, return_address)) |p| {
return @ptrCast(@alignCast(p[0..byte_count]));
}
const new_mem = self.rawAlloc(byte_count, .fromByteUnits(slice_info.attrs.@"align" orelse @alignOf(T)), return_address) orelse
return error.OutOfMemory;
const copy_len = @min(byte_count, old_byte_slice.len);
@memcpy(new_mem[0..copy_len], old_byte_slice[0..copy_len]);
@memset(old_byte_slice, undefined);
self.rawFree(old_byte_slice, .fromByteUnits(slice_info.attrs.@"align" orelse @alignOf(T)), return_address);
return @ptrCast(@alignCast(new_mem[0..byte_count]));
}