commit 7c39558c7cda00c19f58d33abc6e319906b7ccc0 (tree)
parent 1e9bae83f188c330975474dfe3346ccb11c7bab4
Author: Meghan Denny <hello@nektro.net>
Date: Tue, 21 Apr 2026 19:56:12 -0700
std.MultiArrayList: add a swap method
Diffstat:
1 file changed, 24 insertions(+), 0 deletions(-)
diff --git 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]);