std.mem: add byteSwapAllElements

This commit is contained in:
Andrew Kelley 2025-07-18 10:42:24 -07:00
parent 83d1f88ac5
commit bd64bf0e47

View file

@ -2179,22 +2179,8 @@ pub fn byteSwapAllFields(comptime S: type, ptr: *S) void {
const BackingInt = std.meta.Int(.unsigned, @bitSizeOf(S));
ptr.* = @bitCast(@byteSwap(@as(BackingInt, @bitCast(ptr.*))));
},
.array => {
for (ptr) |*item| {
switch (@typeInfo(@TypeOf(item.*))) {
.@"struct", .@"union", .array => byteSwapAllFields(@TypeOf(item.*), item),
.@"enum" => {
item.* = @enumFromInt(@byteSwap(@intFromEnum(item.*)));
},
.bool => {},
.float => |float_info| {
item.* = @bitCast(@byteSwap(@as(std.meta.Int(.unsigned, float_info.bits), @bitCast(item.*))));
},
else => {
item.* = @byteSwap(item.*);
},
}
}
.array => |info| {
byteSwapAllElements(info.child, ptr);
},
else => {
ptr.* = @byteSwap(ptr.*);
@ -2258,6 +2244,24 @@ test byteSwapAllFields {
}, k);
}
pub fn byteSwapAllElements(comptime Elem: type, slice: []Elem) void {
for (slice) |*elem| {
switch (@typeInfo(@TypeOf(elem.*))) {
.@"struct", .@"union", .array => byteSwapAllFields(@TypeOf(elem.*), elem),
.@"enum" => {
elem.* = @enumFromInt(@byteSwap(@intFromEnum(elem.*)));
},
.bool => {},
.float => |float_info| {
elem.* = @bitCast(@byteSwap(@as(std.meta.Int(.unsigned, float_info.bits), @bitCast(elem.*))));
},
else => {
elem.* = @byteSwap(elem.*);
},
}
}
}
/// Returns an iterator that iterates over the slices of `buffer` that are not
/// any of the items in `delimiters`.
///