authorgravatar for hello@nektro.netMeghan Denny <hello@nektro.net> 2026-04-21 19:56:12-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2026-05-01 06:31:11+02:00
log7c39558c7cda00c19f58d33abc6e319906b7ccc0
tree653d39d93539cbb1066587952cc709c7a54c7631
parent1e9bae83f188c330975474dfe3346ccb11c7bab4

std.MultiArrayList: add a swap method


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

lib/std/multi_array_list.zig+24
......@@ -133,6 +133,13 @@ pub fn MultiArrayList(comptime T: type) type {
133133 };
134134 }
135135
136 pub fn swap(self: Slice, a: usize, b: usize) void {
137 inline for (@typeInfo(Field).@"enum".fields) |field| {
138 const its = self.items(@field(Field, field.name));
139 std.mem.swap(@FieldType(T, field.name), &its[a], &its[b]);
140 }
141 }
142
136143 pub fn toMultiArrayList(self: Slice) Self {
137144 if (self.ptrs.len == 0 or self.capacity == 0) {
138145 return .{};
......@@ -267,6 +274,10 @@ pub fn MultiArrayList(comptime T: type) type {
267274 return self.slice().get(index);
268275 }
269276
277 pub fn swap(self: Self, a: usize, b: usize) void {
278 return self.slice().swap(a, b);
279 }
280
270281 /// Extend the list by 1 element.
271282 ///
272283 /// Allocates more memory as necessary.
......@@ -771,6 +782,19 @@ test "basic usage" {
771782 try testing.expectEqualSlices(u32, list.items(.a), &[_]u32{ 1, 2, 3 });
772783 try testing.expectEqualSlices(u8, list.items(.c), &[_]u8{ 'a', 'b', 'c' });
773784
785 list.swap(0, 2);
786 try testing.expectEqualSlices(u32, list.items(.a), &[_]u32{ 3, 2, 1 });
787 try testing.expectEqualSlices(u8, list.items(.c), &[_]u8{ 'c', 'b', 'a' });
788 list.swap(2, 1);
789 try testing.expectEqualSlices(u32, list.items(.a), &[_]u32{ 3, 1, 2 });
790 try testing.expectEqualSlices(u8, list.items(.c), &[_]u8{ 'c', 'a', 'b' });
791 list.swap(2, 0);
792 try testing.expectEqualSlices(u32, list.items(.a), &[_]u32{ 2, 1, 3 });
793 try testing.expectEqualSlices(u8, list.items(.c), &[_]u8{ 'b', 'a', 'c' });
794 list.swap(0, 1);
795 try testing.expectEqualSlices(u32, list.items(.a), &[_]u32{ 1, 2, 3 });
796 try testing.expectEqualSlices(u8, list.items(.c), &[_]u8{ 'a', 'b', 'c' });
797
774798 try testing.expectEqual(@as(usize, 3), list.items(.b).len);
775799 try testing.expectEqualStrings("foobar", list.items(.b)[0]);
776800 try testing.expectEqualStrings("zigzag", list.items(.b)[1]);