Skip to content

Commit bd64bf0

Browse files
committed
std.mem: add byteSwapAllElements
1 parent 83d1f88 commit bd64bf0

File tree

1 file changed

+20
-16
lines changed

1 file changed

+20
-16
lines changed

lib/std/mem.zig

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2179,22 +2179,8 @@ pub fn byteSwapAllFields(comptime S: type, ptr: *S) void {
21792179
const BackingInt = std.meta.Int(.unsigned, @bitSizeOf(S));
21802180
ptr.* = @bitCast(@byteSwap(@as(BackingInt, @bitCast(ptr.*))));
21812181
},
2182-
.array => {
2183-
for (ptr) |*item| {
2184-
switch (@typeInfo(@TypeOf(item.*))) {
2185-
.@"struct", .@"union", .array => byteSwapAllFields(@TypeOf(item.*), item),
2186-
.@"enum" => {
2187-
item.* = @enumFromInt(@byteSwap(@intFromEnum(item.*)));
2188-
},
2189-
.bool => {},
2190-
.float => |float_info| {
2191-
item.* = @bitCast(@byteSwap(@as(std.meta.Int(.unsigned, float_info.bits), @bitCast(item.*))));
2192-
},
2193-
else => {
2194-
item.* = @byteSwap(item.*);
2195-
},
2196-
}
2197-
}
2182+
.array => |info| {
2183+
byteSwapAllElements(info.child, ptr);
21982184
},
21992185
else => {
22002186
ptr.* = @byteSwap(ptr.*);
@@ -2258,6 +2244,24 @@ test byteSwapAllFields {
22582244
}, k);
22592245
}
22602246

2247+
pub fn byteSwapAllElements(comptime Elem: type, slice: []Elem) void {
2248+
for (slice) |*elem| {
2249+
switch (@typeInfo(@TypeOf(elem.*))) {
2250+
.@"struct", .@"union", .array => byteSwapAllFields(@TypeOf(elem.*), elem),
2251+
.@"enum" => {
2252+
elem.* = @enumFromInt(@byteSwap(@intFromEnum(elem.*)));
2253+
},
2254+
.bool => {},
2255+
.float => |float_info| {
2256+
elem.* = @bitCast(@byteSwap(@as(std.meta.Int(.unsigned, float_info.bits), @bitCast(elem.*))));
2257+
},
2258+
else => {
2259+
elem.* = @byteSwap(elem.*);
2260+
},
2261+
}
2262+
}
2263+
}
2264+
22612265
/// Returns an iterator that iterates over the slices of `buffer` that are not
22622266
/// any of the items in `delimiters`.
22632267
///

0 commit comments

Comments
 (0)