Commit 33d7815813

Simon Brown <si@sjbrown.co.uk>
2024-05-13 20:43:48
Implement addManyAsSlice for BoundedArray
1 parent 28476a5
Changed files (1)
lib/std/bounded_array.zig
@@ -116,13 +116,21 @@ pub fn BoundedArrayAligned(
         }
 
         /// Resize the slice, adding `n` new elements, which have `undefined` values.
-        /// The return value is a slice pointing to the uninitialized elements.
+        /// The return value is a pointer to the array of uninitialized elements.
         pub fn addManyAsArray(self: *Self, comptime n: usize) error{Overflow}!*align(alignment) [n]T {
             const prev_len = self.len;
             try self.resize(self.len + n);
             return self.slice()[prev_len..][0..n];
         }
 
+        /// Resize the slice, adding `n` new elements, which have `undefined` values.
+        /// The return value is a slice pointing to the uninitialized elements.
+        pub fn addManyAsSlice(self: *Self, n: usize) error{Overflow}![]align(alignment) T {
+            const prev_len = self.len;
+            try self.resize(self.len + n);
+            return self.slice()[prev_len..][0..n];
+        }
+
         /// Remove and return the last element from the slice.
         /// Asserts the slice has at least one item.
         pub fn pop(self: *Self) T {
@@ -382,6 +390,10 @@ test BoundedArray {
     try testing.expectEqual(swapped, 0xdd);
     try testing.expectEqual(a.get(0), 0xee);
 
+    const added_slice = try a.addManyAsSlice(3);
+    try testing.expectEqual(added_slice.len, 3);
+    try testing.expectEqual(a.len, 36);
+
     while (a.popOrNull()) |_| {}
     const w = a.writer();
     const s = "hello, this is a test string";