authorgravatar for 78876133+IOKG04@users.noreply.github.comRue <78876133+IOKG04@users.noreply.github.com> 2025-08-26 09:25:25+02:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2025-08-26 00:25:25-07:00
logd57b1e3552bae31c535a39d165608127579b9b08
tree28b8bb95b5d4db324747f135cb8542aae7b079b7
parentff859088e409f3fcf7c4f52e58ec4e6e9f7f1c4e
signaturebadge-check Signed by PGP key B5690EEEBB952194

`std.ArrayList`: add `insertSliceAssumeCapacity()` and `insertSliceBounded()` (#24978)

closes #24929

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

lib/std/array_list.zig+48
......@@ -828,6 +828,35 @@ pub fn Aligned(comptime T: type, comptime alignment: ?mem.Alignment) type {
828828 @memcpy(dst, items);
829829 }
830830
831 /// Insert slice `items` at index `i` by moving `list[i .. list.len]` to make room.
832 /// This operation is O(N).
833 /// Invalidates pre-existing pointers to elements at and after `index`.
834 /// Asserts that the list has capacity for the additional items.
835 /// Asserts that the index is in bounds or equal to the length.
836 pub fn insertSliceAssumeCapacity(
837 self: *Self,
838 index: usize,
839 items: []const T,
840 ) void {
841 const dst = self.addManyAtAssumeCapacity(index, items.len);
842 @memcpy(dst, items);
843 }
844
845 /// Insert slice `items` at index `i` by moving `list[i .. list.len]` to make room.
846 /// This operation is O(N).
847 /// Invalidates pre-existing pointers to elements at and after `index`.
848 /// If the list lacks unused capacity for the additional items, returns
849 /// `error.OutOfMemory`.
850 /// Asserts that the index is in bounds or equal to the length.
851 pub fn insertSliceBounded(
852 self: *Self,
853 index: usize,
854 items: []const T,
855 ) error{OutOfMemory}!void {
856 const dst = try self.addManyAtBounded(index, items.len);
857 @memcpy(dst, items);
858 }
859
831860 /// Grows or shrinks the list as necessary.
832861 /// Invalidates element pointers if additional capacity is allocated.
833862 /// Asserts that the range is in bounds.
......@@ -2462,3 +2491,22 @@ test "orderedRemoveMany" {
24622491 list.orderedRemoveMany(&.{0});
24632492 try testing.expectEqualSlices(usize, &.{}, list.items);
24642493}
2494
2495test "insertSlice*" {
2496 var buf: [10]u8 = undefined;
2497 var list: ArrayList(u8) = .initBuffer(&buf);
2498
2499 list.appendSliceAssumeCapacity("abcd");
2500
2501 list.insertSliceAssumeCapacity(2, "ef");
2502 try testing.expectEqualStrings("abefcd", list.items);
2503
2504 try list.insertSliceBounded(4, "gh");
2505 try testing.expectEqualStrings("abefghcd", list.items);
2506
2507 try testing.expectError(error.OutOfMemory, list.insertSliceBounded(6, "ijkl"));
2508 try testing.expectEqualStrings("abefghcd", list.items); // ensure no elements were changed before the return of error.OutOfMemory
2509
2510 list.insertSliceAssumeCapacity(6, "ij");
2511 try testing.expectEqualStrings("abefghijcd", list.items);
2512}