authorgravatar for Modernwarfare3Minecraft64@gmail.comMCRusher <Modernwarfare3Minecraft64@gmail.com> 2019-11-23 22:54:33-05:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2019-11-23 22:54:33-05:00
log10e6cde083cf9ddd1ae72850d45c25b1258d0d7e
treeb38f84bf63cf00f3fb5c2beae445a09f0ecdf50f
parent29d7b5a80c9faf640c3db0de14cd229e90b2d8c3
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

Added initCapacity and relevant test

Added ArrayList.initCapcity() as a way to preallocate a block of memory to reduce future allocations. Added a test "std.ArrayList.initCapacity" that ensures initCapacity adds no elements and increases capacity by at least the requested amount

1 files changed, 17 insertions(+), 0 deletions(-)

lib/std/array_list.zig+17
......@@ -40,6 +40,14 @@ pub fn AlignedArrayList(comptime T: type, comptime alignment: ?u29) type {
4040 .allocator = allocator,
4141 };
4242 }
43
44 /// Initialize with capacity to hold at least num elements.
45 /// Deinitialize with `deinit` or use `toOwnedSlice`.
46 pub fn initCapacity(allocator: *Allocator, num: usize) !Self {
47 var self = Self.init(allocator);
48 try self.ensureCapacity(num);
49 return self;
50 }
4351
4452 /// Release all allocated memory.
4553 pub fn deinit(self: Self) void {
......@@ -271,6 +279,15 @@ test "std.ArrayList.init" {
271279 testing.expect(list.capacity() == 0);
272280}
273281
282test "std.ArrayList.initCapacity" {
283 var bytes: [1024]u8 = undefined;
284 const allocator = &std.heap.FixedBufferAllocator.init(bytes[0..]).allocator;
285 var list = try ArrayList(i8).initCapacity(allocator, 200);
286 defer list.deinit();
287 testing.expect(list.count() == 0);
288 testing.expect(list.capacity() >= 200);
289}
290
274291test "std.ArrayList.basic" {
275292 var bytes: [1024]u8 = undefined;
276293 const allocator = &std.heap.FixedBufferAllocator.init(bytes[0..]).allocator;