Zig 0.17.0-dev (Split by item)

This is an example of documentation generated by ZigDoc, an alternative to Zig's built-in Auto Doc feature. See also examples in other modes/formats. The project being documented here (as the example) is the Zig library itself.

reallocAdvanced

Allocator.reallocAdvanced
pub fn reallocAdvanced(
    self: Allocator,
    old_mem: anytype,
    new_n: usize,
    return_address: usize,
) Error!@TypeOf(old_mem)

File

lib/std/mem/Allocator.zig:406

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;
    // Note: can't set shrunk memory to undefined as memory shouldn't be modified on realloc failure
    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]));
}