Zig 0.17.0-dev (Split by item)

Shortcut keys
?
Show these tips
S
Focus search field
Esc
Clear focus & close tips
U
Jump to source code
↑
Move up in search results
↓
Move down in search results
↵
Go to active search result
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 standard library. Public Function

reallocAdvanced

Public Function
std.mem.Allocator.reallocAdvanced
pub fn reallocAdvanced(
    self: Allocator,
    old_mem: anytype,
    new_n: usize,
    return_address: usize,
) Error!Slice(AbsorbSentinel(@TypeOf(old_mem)))

Params

  • self: Allocator
  • old_mem
  • new_n: usize
  • return_address: usize

Errors

OutOfMemory

File

mem/Allocator.zig:406
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
pub fn reallocAdvanced(
    self: Allocator,
    old_mem: anytype,
    new_n: usize,
    return_address: usize,
) Error!Slice(AbsorbSentinel(@TypeOf(old_mem))) {
    const slice_info = @typeInfo(@TypeOf(old_mem)).pointer;
    const T = if (slice_info.size != .slice) comptime T: {
        assert(slice_info.size == .one);
        break :T @typeInfo(slice_info.child).array.child;
    } else 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]));
}