Last active
September 19, 2022 07:59
-
-
Save zxubian/f20510dca48366968e563354b4090074 to your computer and use it in GitHub Desktop.
Function to byte-swap all members of a struct in zig using reflection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const assert = std.debug.assert; | |
| // uses reflection to byte-swap all members of a packed struct | |
| // layout is preserved | |
| fn byte_swap_all_members(comptime T: type, struct_pointer: *T) void { | |
| comptime assert(@typeInfo(T).Struct.layout != .Auto); | |
| comptime assert(@mod(@bitSizeOf(T), 8) == 0); | |
| var raw_bytes = @ptrCast([*]u8, std.mem.asBytes(struct_pointer)); | |
| comptime var start_index: u32 = 0; | |
| inline for (std.meta.fields(T)) |field| { | |
| const length = @bitSizeOf(field.field_type) / 8; | |
| const slice = raw_bytes[start_index .. start_index + length]; | |
| const value_ptr = std.mem.bytesAsValue(field.field_type, slice); | |
| value_ptr.* = @byteSwap(field.field_type, value_ptr.*); | |
| start_index += length; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment