authorgravatar for BarabasGitHub@users.noreply.github.comBas <BarabasGitHub@users.noreply.github.com> 2020-02-19 17:33:35+01:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2020-02-19 11:33:35-05:00
log1483ae37f2dae6a5b9db1f7851cf5dc9a86e57f3
treed2f708857c0bc220de4eb703e7ebb5bf1642ad13
parentc664692bdd62765ab444a79a8704d2161c1809f1
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

Add an appendValues method to ArrayList to append a value n times. (#4460)


1 files changed, 25 insertions(+), 0 deletions(-)

lib/std/array_list.zig+25
......@@ -188,6 +188,14 @@ pub fn AlignedArrayList(comptime T: type, comptime alignment: ?u29) type {
188188 self.len += items.len;
189189 }
190190
191 /// Append a value to the list `n` times. Allocates more memory
192 /// as necessary.
193 pub fn appendNTimes(self: *Self, value: T, n: usize) !void {
194 const old_len = self.len;
195 try self.resize(self.len + n);
196 mem.set(T, self.items[old_len..self.len], value);
197 }
198
191199 /// Adjust the list's length to `new_len`. Doesn't initialize
192200 /// added items if any.
193201 pub fn resize(self: *Self, new_len: usize) !void {
......@@ -311,6 +319,23 @@ test "std.ArrayList.basic" {
311319 testing.expect(list.pop() == 33);
312320}
313321
322test "std.ArrayList.appendNTimes" {
323 var list = ArrayList(i32).init(testing.allocator);
324 defer list.deinit();
325
326 try list.appendNTimes(2, 10);
327 testing.expectEqual(@as(usize, 10), list.len);
328 for (list.toSlice()) |element| {
329 testing.expectEqual(@as(i32, 2), element);
330 }
331}
332
333test "std.ArrayList.appendNTimes with failing allocator" {
334 var list = ArrayList(i32).init(testing.failing_allocator);
335 defer list.deinit();
336 testing.expectError(error.OutOfMemory, list.appendNTimes(2, 10));
337}
338
314339test "std.ArrayList.orderedRemove" {
315340 var list = ArrayList(i32).init(testing.allocator);
316341 defer list.deinit();