diff options
| author | Andrew Kelley <superjoe30@gmail.com> | 2018-09-10 12:30:57 -0400 |
|---|---|---|
| committer | Andrew Kelley <superjoe30@gmail.com> | 2018-09-10 12:30:57 -0400 |
| commit | c9474faa4e6cfd6480c1bd24216c26f4320e3c29 (patch) | |
| tree | 4bf022698f229cd276b598ed95aa30a61e882674 /std/array_list.zig | |
| parent | f27d82fe90e1d0007bf2d3ef52eac8cdbc381e0d (diff) | |
| parent | 7c9f7b72c59e7c6de38038f512ae332fc164e8d7 (diff) | |
| download | zig-c9474faa4e6cfd6480c1bd24216c26f4320e3c29.tar.gz zig-c9474faa4e6cfd6480c1bd24216c26f4320e3c29.zip | |
Merge remote-tracking branch 'origin/master' into llvm7
Diffstat (limited to 'std/array_list.zig')
| -rw-r--r-- | std/array_list.zig | 29 |
1 files changed, 27 insertions, 2 deletions
diff --git a/std/array_list.zig b/std/array_list.zig index 298026d11c..dda6f176eb 100644 --- a/std/array_list.zig +++ b/std/array_list.zig @@ -62,6 +62,10 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type { return self.len; } + pub fn capacity(self: Self) usize { + return self.items.len; + } + /// ArrayList takes ownership of the passed in slice. The slice must have been /// allocated with `allocator`. /// Deinitialize with `deinit` or use `toOwnedSlice`. @@ -102,6 +106,11 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type { new_item_ptr.* = item; } + pub fn appendAssumeCapacity(self: *Self, item: T) void { + const new_item_ptr = self.addOneAssumeCapacity(); + new_item_ptr.* = item; + } + /// Removes the element at the specified index and returns it. /// The empty slot is filled from the end of the list. pub fn swapRemove(self: *Self, i: usize) T { @@ -138,7 +147,7 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type { } pub fn ensureCapacity(self: *Self, new_capacity: usize) !void { - var better_capacity = self.items.len; + var better_capacity = self.capacity(); if (better_capacity >= new_capacity) return; while (true) { better_capacity += better_capacity / 2 + 8; @@ -150,8 +159,13 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type { pub fn addOne(self: *Self) !*T { const new_length = self.len + 1; try self.ensureCapacity(new_length); + return self.addOneAssumeCapacity(); + } + + pub fn addOneAssumeCapacity(self: *Self) *T { + assert(self.count() < self.capacity()); const result = &self.items[self.len]; - self.len = new_length; + self.len += 1; return result; } @@ -191,6 +205,17 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type { }; } +test "std.ArrayList.init" { + var bytes: [1024]u8 = undefined; + const allocator = &std.heap.FixedBufferAllocator.init(bytes[0..]).allocator; + + var list = ArrayList(i32).init(allocator); + defer list.deinit(); + + assert(list.count() == 0); + assert(list.capacity() == 0); +} + test "std.ArrayList.basic" { var bytes: [1024]u8 = undefined; const allocator = &std.heap.FixedBufferAllocator.init(bytes[0..]).allocator; |
