std.mem.byteSwapAllFields: add suppport for nested structs (#15696)

This commit is contained in:
Cortex 2023-05-17 02:10:44 +03:00 committed by GitHub
parent 958fba0eb7
commit c269e16c3b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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