authorgravatar for BarabasGitHub@users.noreply.github.comBas van den Berg <BarabasGitHub@users.noreply.github.com> 2018-09-09 12:54:00+02:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-09-09 10:28:07-04:00
log7c9f7b72c59e7c6de38038f512ae332fc164e8d7
tree5651e9828ccc8efb091ac772c8868a559d400e1d
parent859b0aee1e2de4b85ba88a2df75ee54952fb9642

Add capacity and appendAssumeCapacity to ArrayList


1 files changed, 27 insertions(+), 2 deletions(-)

std/array_list.zig+27-2
......@@ -62,6 +62,10 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type {
6262 return self.len;
6363 }
6464
65 pub fn capacity(self: Self) usize {
66 return self.items.len;
67 }
68
6569 /// ArrayList takes ownership of the passed in slice. The slice must have been
6670 /// allocated with `allocator`.
6771 /// Deinitialize with `deinit` or use `toOwnedSlice`.
......@@ -102,6 +106,11 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type {
102106 new_item_ptr.* = item;
103107 }
104108
109 pub fn appendAssumeCapacity(self: *Self, item: T) void {
110 const new_item_ptr = self.addOneAssumeCapacity();
111 new_item_ptr.* = item;
112 }
113
105114 /// Removes the element at the specified index and returns it.
106115 /// The empty slot is filled from the end of the list.
107116 pub fn swapRemove(self: *Self, i: usize) T {
......@@ -138,7 +147,7 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type {
138147 }
139148
140149 pub fn ensureCapacity(self: *Self, new_capacity: usize) !void {
141 var better_capacity = self.items.len;
150 var better_capacity = self.capacity();
142151 if (better_capacity >= new_capacity) return;
143152 while (true) {
144153 better_capacity += better_capacity / 2 + 8;
......@@ -150,8 +159,13 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type {
150159 pub fn addOne(self: *Self) !*T {
151160 const new_length = self.len + 1;
152161 try self.ensureCapacity(new_length);
162 return self.addOneAssumeCapacity();
163 }
164
165 pub fn addOneAssumeCapacity(self: *Self) *T {
166 assert(self.count() < self.capacity());
153167 const result = &self.items[self.len];
154 self.len = new_length;
168 self.len += 1;
155169 return result;
156170 }
157171
......@@ -191,6 +205,17 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type {
191205 };
192206}
193207
208test "std.ArrayList.init" {
209 var bytes: [1024]u8 = undefined;
210 const allocator = &std.heap.FixedBufferAllocator.init(bytes[0..]).allocator;
211
212 var list = ArrayList(i32).init(allocator);
213 defer list.deinit();
214
215 assert(list.count() == 0);
216 assert(list.capacity() == 0);
217}
218
194219test "std.ArrayList.basic" {
195220 var bytes: [1024]u8 = undefined;
196221 const allocator = &std.heap.FixedBufferAllocator.init(bytes[0..]).allocator;