mirror of
https://github.com/ziglang/zig.git
synced 2026-02-19 15:58:50 +00:00
std.mem.byteSwapAllFields: add suppport for nested structs (#15696)
This commit is contained in:
parent
958fba0eb7
commit
c269e16c3b
@ -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
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user