Implement addManyAsSlice for BoundedArray

This commit is contained in:
Simon Brown 2024-05-13 19:43:48 +01:00 committed by Veikka Tuominen
parent 28476a5ee9
commit 33d7815813

View File

@ -116,13 +116,21 @@ pub fn BoundedArrayAligned(
} }
/// Resize the slice, adding `n` new elements, which have `undefined` values. /// 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 { pub fn addManyAsArray(self: *Self, comptime n: usize) error{Overflow}!*align(alignment) [n]T {
const prev_len = self.len; const prev_len = self.len;
try self.resize(self.len + n); try self.resize(self.len + n);
return self.slice()[prev_len..][0..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. /// Remove and return the last element from the slice.
/// Asserts the slice has at least one item. /// Asserts the slice has at least one item.
pub fn pop(self: *Self) T { pub fn pop(self: *Self) T {
@ -382,6 +390,10 @@ test BoundedArray {
try testing.expectEqual(swapped, 0xdd); try testing.expectEqual(swapped, 0xdd);
try testing.expectEqual(a.get(0), 0xee); 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()) |_| {} while (a.popOrNull()) |_| {}
const w = a.writer(); const w = a.writer();
const s = "hello, this is a test string"; const s = "hello, this is a test string";