diff --git a/lib/std/multi_array_list.zig b/lib/std/multi_array_list.zig index fde7e93ed6..934dcfeb02 100644 --- a/lib/std/multi_array_list.zig +++ b/lib/std/multi_array_list.zig @@ -133,6 +133,13 @@ pub fn MultiArrayList(comptime T: type) type { }; } + pub fn swap(self: Slice, a: usize, b: usize) void { + inline for (@typeInfo(Field).@"enum".fields) |field| { + const its = self.items(@field(Field, field.name)); + std.mem.swap(@FieldType(T, field.name), &its[a], &its[b]); + } + } + pub fn toMultiArrayList(self: Slice) Self { if (self.ptrs.len == 0 or self.capacity == 0) { return .{}; @@ -267,6 +274,10 @@ pub fn MultiArrayList(comptime T: type) type { return self.slice().get(index); } + pub fn swap(self: Self, a: usize, b: usize) void { + return self.slice().swap(a, b); + } + /// Extend the list by 1 element. /// /// Allocates more memory as necessary. @@ -771,6 +782,19 @@ test "basic usage" { try testing.expectEqualSlices(u32, list.items(.a), &[_]u32{ 1, 2, 3 }); try testing.expectEqualSlices(u8, list.items(.c), &[_]u8{ 'a', 'b', 'c' }); + list.swap(0, 2); + try testing.expectEqualSlices(u32, list.items(.a), &[_]u32{ 3, 2, 1 }); + try testing.expectEqualSlices(u8, list.items(.c), &[_]u8{ 'c', 'b', 'a' }); + list.swap(2, 1); + try testing.expectEqualSlices(u32, list.items(.a), &[_]u32{ 3, 1, 2 }); + try testing.expectEqualSlices(u8, list.items(.c), &[_]u8{ 'c', 'a', 'b' }); + list.swap(2, 0); + try testing.expectEqualSlices(u32, list.items(.a), &[_]u32{ 2, 1, 3 }); + try testing.expectEqualSlices(u8, list.items(.c), &[_]u8{ 'b', 'a', 'c' }); + list.swap(0, 1); + try testing.expectEqualSlices(u32, list.items(.a), &[_]u32{ 1, 2, 3 }); + try testing.expectEqualSlices(u8, list.items(.c), &[_]u8{ 'a', 'b', 'c' }); + try testing.expectEqual(@as(usize, 3), list.items(.b).len); try testing.expectEqualStrings("foobar", list.items(.b)[0]); try testing.expectEqualStrings("zigzag", list.items(.b)[1]);