commit 10e6cde083cf9ddd1ae72850d45c25b1258d0d7e (tree)
parent 29d7b5a80c9faf640c3db0de14cd229e90b2d8c3
Author: MCRusher <Modernwarfare3Minecraft64@gmail.com>
Date: Sat, 23 Nov 2019 22:54:33 -0500
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
Diffstat:
1 file changed, 17 insertions(+), 0 deletions(-)
diff --git 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;