@@ -2150,7 +2150,7 @@ pub fn byteSwapAllFields(comptime S: type, ptr: *S) void {
2150
2150
} else {
2151
2151
byteSwapAllFields (f .type , &@field (ptr , f .name ));
2152
2152
},
2153
- .array = > byteSwapAllFields (f .type , &@field (ptr , f .name )),
2153
+ .@"union" , . array = > byteSwapAllFields (f .type , &@field (ptr , f .name )),
2154
2154
.@"enum" = > {
2155
2155
@field (ptr , f .name ) = @enumFromInt (@byteSwap (@intFromEnum (@field (ptr , f .name ))));
2156
2156
},
@@ -2164,10 +2164,25 @@ pub fn byteSwapAllFields(comptime S: type, ptr: *S) void {
2164
2164
}
2165
2165
}
2166
2166
},
2167
+ .@"union" = > | union_info | {
2168
+ if (union_info .tag_type != null ) {
2169
+ @compileError ("byteSwapAllFields expects an untagged union" );
2170
+ }
2171
+
2172
+ const first_size = @bitSizeOf (union_info .fields [0 ].type );
2173
+ inline for (union_info .fields ) | field | {
2174
+ if (@bitSizeOf (field .type ) != first_size ) {
2175
+ @compileError ("Unable to byte-swap unions with varying field sizes" );
2176
+ }
2177
+ }
2178
+
2179
+ const BackingInt = std .meta .Int (.unsigned , @bitSizeOf (S ));
2180
+ ptr .* = @bitCast (@byteSwap (@as (BackingInt , @bitCast (ptr .* ))));
2181
+ },
2167
2182
.array = > {
2168
2183
for (ptr ) | * item | {
2169
2184
switch (@typeInfo (@TypeOf (item .* ))) {
2170
- .@"struct" , .array = > byteSwapAllFields (@TypeOf (item .* ), item ),
2185
+ .@"struct" , .@"union" , . array = > byteSwapAllFields (@TypeOf (item .* ), item ),
2171
2186
.@"enum" = > {
2172
2187
item .* = @enumFromInt (@byteSwap (@intFromEnum (item .* )));
2173
2188
},
@@ -2193,6 +2208,7 @@ test byteSwapAllFields {
2193
2208
f3 : [1 ]u8 ,
2194
2209
f4 : bool ,
2195
2210
f5 : f32 ,
2211
+ f6 : extern union { f0 : u16 , f1 : u16 },
2196
2212
};
2197
2213
const K = extern struct {
2198
2214
f0 : u8 ,
@@ -2209,6 +2225,7 @@ test byteSwapAllFields {
2209
2225
.f3 = .{0x12 },
2210
2226
.f4 = true ,
2211
2227
.f5 = @as (f32 , @bitCast (@as (u32 , 0x4640e400 ))),
2228
+ .f6 = .{ .f0 = 0x1234 },
2212
2229
};
2213
2230
var k = K {
2214
2231
.f0 = 0x12 ,
@@ -2227,6 +2244,7 @@ test byteSwapAllFields {
2227
2244
.f3 = .{0x12 },
2228
2245
.f4 = true ,
2229
2246
.f5 = @as (f32 , @bitCast (@as (u32 , 0x00e44046 ))),
2247
+ .f6 = .{ .f0 = 0x3412 },
2230
2248
}, s );
2231
2249
try std .testing .expectEqual (K {
2232
2250
.f0 = 0x12 ,
0 commit comments