diff --git a/lib/std/mem.zig b/lib/std/mem.zig index 512a3d7ca3..8cb2c00a3a 100644 --- a/lib/std/mem.zig +++ b/lib/std/mem.zig @@ -1887,7 +1887,11 @@ test "writeIntBig and writeIntLittle" { pub fn byteSwapAllFields(comptime S: type, ptr: *S) void { if (@typeInfo(S) != .Struct) @compileError("byteSwapAllFields expects a struct as the first argument"); inline for (std.meta.fields(S)) |f| { - @field(ptr, f.name) = @byteSwap(@field(ptr, f.name)); + if (@typeInfo(f.type) == .Struct) { + byteSwapAllFields(f.type, &@field(ptr, f.name)); + } else { + @field(ptr, f.name) = @byteSwap(@field(ptr, f.name)); + } } } @@ -1897,17 +1901,33 @@ test "byteSwapAllFields" { f1: u16, f2: u32, }; + const K = extern struct { + f0: u8, + f1: T, + f2: u16, + }; var s = T{ .f0 = 0x12, .f1 = 0x1234, .f2 = 0x12345678, }; + var k = K{ + .f0 = 0x12, + .f1 = s, + .f2 = 0x1234, + }; byteSwapAllFields(T, &s); + byteSwapAllFields(K, &k); try std.testing.expectEqual(T{ .f0 = 0x12, .f1 = 0x3412, .f2 = 0x78563412, }, s); + try std.testing.expectEqual(K{ + .f0 = 0x12, + .f1 = s, + .f2 = 0x3412, + }, k); } /// Returns an iterator that iterates over the slices of `buffer` that are not