| ... | ... | @@ -828,6 +828,35 @@ pub fn Aligned(comptime T: type, comptime alignment: ?mem.Alignment) type { |
| 828 | 828 | @memcpy(dst, items); |
| 829 | 829 | } |
| 830 | 830 | |
| 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 | |
| 831 | 860 | /// Grows or shrinks the list as necessary. |
| 832 | 861 | /// Invalidates element pointers if additional capacity is allocated. |
| 833 | 862 | /// Asserts that the range is in bounds. |
| ... | ... | @@ -2462,3 +2491,22 @@ test "orderedRemoveMany" { |
| 2462 | 2491 | list.orderedRemoveMany(&.{0}); |
| 2463 | 2492 | try testing.expectEqualSlices(usize, &.{}, list.items); |
| 2464 | 2493 | } |
| 2494 | |
| 2495 | test "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 | } |