shrinkAndFree
Reduce allocated capacity to new_len.
May invalidate element pointers.
Asserts that the new length is less than or equal to the previous length.
Function parameters
Parameters
Deprecated.
Functions
- Managed
- Deprecated.
- AlignedManaged
- Deprecated.
- Aligned
- A contiguous, growable list of arbitrarily aligned items in memory.
Source
Implementation
pub fn shrinkAndFree(self: *Self, gpa: Allocator, new_len: usize) void {
assert(new_len <= self.items.len);
if (@sizeOf(T) == 0) {
self.items.len = new_len;
return;
}
const old_memory = self.allocatedSlice();
if (gpa.remap(old_memory, new_len)) |new_items| {
self.capacity = new_items.len;
self.items = new_items;
return;
}
const new_memory = gpa.alignedAlloc(T, alignment, new_len) catch |e| switch (e) {
error.OutOfMemory => {
// No problem, capacity is still correct then.
self.items.len = new_len;
return;
},
};
@memcpy(new_memory, self.items[0..new_len]);
gpa.free(old_memory);
self.items = new_memory;
self.capacity = new_memory.len;
}