DoxigAlpha

reallocAdvanced

Function parameters

Parameters

#
old_mem:anytype
new_n:usize
return_address:usize

Type definitions in this namespace

Types

#

Functions in this namespace

Functions

#
rawAlloc
This function is not intended to be called except from within the
rawResize
This function is not intended to be called except from within the
rawRemap
This function is not intended to be called except from within the
rawFree
This function is not intended to be called except from within the
create
Returns a pointer to undefined memory.
destroy
`ptr` should be the return value of `create`, or otherwise
alloc
Allocates an array of `n` items of type `T` and sets all the
allocSentinel
Allocates an array of `n + 1` items of type `T` and sets the first `n`
resize
Request to modify the size of an allocation.
remap
Request to modify the size of an allocation, allowing relocation.
realloc
This function requests a new size for an existing allocation, which
free
Free an array allocated with `alloc`.
dupe
Copies `m` to newly allocated memory.
dupeZ
Copies `m` to newly allocated memory, with a null-terminated element.

Error sets in this namespace

Error Sets

#

Source

Implementation

#
pub fn reallocAdvanced(
    self: Allocator,
    old_mem: anytype,
    new_n: usize,
    return_address: usize,
) t: {
    const Slice = @typeInfo(@TypeOf(old_mem)).pointer;
    break :t Error![]align(Slice.alignment) Slice.child;
} {
    const Slice = @typeInfo(@TypeOf(old_mem)).pointer;
    const T = Slice.child;
    if (old_mem.len == 0) {
        return self.allocAdvancedWithRetAddr(T, .fromByteUnits(Slice.alignment), new_n, return_address);
    }
    if (new_n == 0) {
        self.free(old_mem);
        const ptr = comptime std.mem.alignBackward(usize, math.maxInt(usize), Slice.alignment);
        return @as([*]align(Slice.alignment) T, @ptrFromInt(ptr))[0..0];
    }

    const old_byte_slice = mem.sliceAsBytes(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.alignment), byte_count, return_address)) |p| {
        const new_bytes: []align(Slice.alignment) u8 = @alignCast(p[0..byte_count]);
        return mem.bytesAsSlice(T, new_bytes);
    }

    const new_mem = self.rawAlloc(byte_count, .fromByteUnits(Slice.alignment), 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.alignment), return_address);

    const new_bytes: []align(Slice.alignment) u8 = @alignCast(new_mem[0..byte_count]);
    return mem.bytesAsSlice(T, new_bytes);
}