Commit c269e16c3b

Cortex <protoss2017@mail.ru>
2023-05-17 01:10:44
std.mem.byteSwapAllFields: add suppport for nested structs (#15696)
1 parent 958fba0
Changed files (1)
lib
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