From 10e6cde083cf9ddd1ae72850d45c25b1258d0d7e Mon Sep 17 00:00:00 2001 From: MCRusher Date: Sat, 23 Nov 2019 22:54:33 -0500 Subject: [PATCH] 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 --- lib/std/array_list.zig | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/lib/std/array_list.zig b/lib/std/array_list.zig index 59fd2a10e5..d7da5f7f8a 100644 --- a/lib/std/array_list.zig +++ b/lib/std/array_list.zig @@ -40,6 +40,14 @@ pub fn AlignedArrayList(comptime T: type, comptime alignment: ?u29) type { .allocator = allocator, }; } + + /// Initialize with capacity to hold at least num elements. + /// Deinitialize with `deinit` or use `toOwnedSlice`. + pub fn initCapacity(allocator: *Allocator, num: usize) !Self { + var self = Self.init(allocator); + try self.ensureCapacity(num); + return self; + } /// Release all allocated memory. pub fn deinit(self: Self) void { @@ -271,6 +279,15 @@ test "std.ArrayList.init" { testing.expect(list.capacity() == 0); } +test "std.ArrayList.initCapacity" { + var bytes: [1024]u8 = undefined; + const allocator = &std.heap.FixedBufferAllocator.init(bytes[0..]).allocator; + var list = try ArrayList(i8).initCapacity(allocator, 200); + defer list.deinit(); + testing.expect(list.count() == 0); + testing.expect(list.capacity() >= 200); +} + test "std.ArrayList.basic" { var bytes: [1024]u8 = undefined; const allocator = &std.heap.FixedBufferAllocator.init(bytes[0..]).allocator;