remap
Request to modify the size of an allocation, allowing relocation.
A non-null return value indicates the resize was successful. The
allocation may have same address, or may have been relocated. In either
case, the allocation now has size of new_len. A null return value
indicates that the resize would be equivalent to allocating new memory,
copying the bytes from the old memory, and then freeing the old memory.
In such case, it is more efficient for the caller to perform those
operations.
allocation may be an empty slice, in which case null is returned,
unless new_len is also 0, in which case allocation is returned.
new_len may be zero, in which case the allocation is freed.
If the allocation's elements' type is zero bytes sized, allocation.len is set to new_len.
Function parameters
Parameters
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 remap(self: Allocator, allocation: anytype, new_len: usize) t: {
const Slice = @typeInfo(@TypeOf(allocation)).pointer;
break :t ?[]align(Slice.alignment) Slice.child;
} {
const Slice = @typeInfo(@TypeOf(allocation)).pointer;
const T = Slice.child;
const alignment = Slice.alignment;
if (new_len == 0) {
self.free(allocation);
return allocation[0..0];
}
if (allocation.len == 0) {
return null;
}
if (@sizeOf(T) == 0) {
var new_memory = allocation;
new_memory.len = new_len;
return new_memory;
}
const old_memory = mem.sliceAsBytes(allocation);
// I would like to use saturating multiplication here, but LLVM cannot lower it
// on WebAssembly: https://github.com/ziglang/zig/issues/9660
//const new_len_bytes = new_len *| @sizeOf(T);
const new_len_bytes = math.mul(usize, @sizeOf(T), new_len) catch return null;
const new_ptr = self.rawRemap(old_memory, .fromByteUnits(alignment), new_len_bytes, @returnAddress()) orelse return null;
const new_memory: []align(alignment) u8 = @alignCast(new_ptr[0..new_len_bytes]);
return mem.bytesAsSlice(T, new_memory);
}