| ... | ... | @@ -62,6 +62,10 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type { |
| 62 | 62 | return self.len; |
| 63 | 63 | } |
| 64 | 64 | |
| 65 | pub fn capacity(self: Self) usize { |
| 66 | return self.items.len; |
| 67 | } |
| 68 | |
| 65 | 69 | /// ArrayList takes ownership of the passed in slice. The slice must have been |
| 66 | 70 | /// allocated with `allocator`. |
| 67 | 71 | /// Deinitialize with `deinit` or use `toOwnedSlice`. |
| ... | ... | @@ -102,6 +106,11 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type { |
| 102 | 106 | new_item_ptr.* = item; |
| 103 | 107 | } |
| 104 | 108 | |
| 109 | pub fn appendAssumeCapacity(self: *Self, item: T) void { |
| 110 | const new_item_ptr = self.addOneAssumeCapacity(); |
| 111 | new_item_ptr.* = item; |
| 112 | } |
| 113 | |
| 105 | 114 | /// Removes the element at the specified index and returns it. |
| 106 | 115 | /// The empty slot is filled from the end of the list. |
| 107 | 116 | pub fn swapRemove(self: *Self, i: usize) T { |
| ... | ... | @@ -138,7 +147,7 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type { |
| 138 | 147 | } |
| 139 | 148 | |
| 140 | 149 | pub fn ensureCapacity(self: *Self, new_capacity: usize) !void { |
| 141 | | var better_capacity = self.items.len; |
| 150 | var better_capacity = self.capacity(); |
| 142 | 151 | if (better_capacity >= new_capacity) return; |
| 143 | 152 | while (true) { |
| 144 | 153 | better_capacity += better_capacity / 2 + 8; |
| ... | ... | @@ -150,8 +159,13 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type { |
| 150 | 159 | pub fn addOne(self: *Self) !*T { |
| 151 | 160 | const new_length = self.len + 1; |
| 152 | 161 | try self.ensureCapacity(new_length); |
| 162 | return self.addOneAssumeCapacity(); |
| 163 | } |
| 164 | |
| 165 | pub fn addOneAssumeCapacity(self: *Self) *T { |
| 166 | assert(self.count() < self.capacity()); |
| 153 | 167 | const result = &self.items[self.len]; |
| 154 | | self.len = new_length; |
| 168 | self.len += 1; |
| 155 | 169 | return result; |
| 156 | 170 | } |
| 157 | 171 | |
| ... | ... | @@ -191,6 +205,17 @@ pub fn AlignedArrayList(comptime T: type, comptime A: u29) type { |
| 191 | 205 | }; |
| 192 | 206 | } |
| 193 | 207 | |
| 208 | test "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 | |
| 194 | 219 | test "std.ArrayList.basic" { |
| 195 | 220 | var bytes: [1024]u8 = undefined; |
| 196 | 221 | const allocator = &std.heap.FixedBufferAllocator.init(bytes[0..]).allocator; |