mirror of
https://codeberg.org/ziglang/zig.git
synced 2026-05-03 16:22:55 +03:00
std.MultiArrayList: add a swap method
This commit is contained in:
committed by
Andrew Kelley
parent
1e9bae83f1
commit
7c39558c7c
@@ -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]);
|
||||
|
||||
Reference in New Issue
Block a user