Skip to content

Instantly share code, notes, and snippets.

@zxubian
Last active September 19, 2022 07:59
Show Gist options
  • Select an option

  • Save zxubian/f20510dca48366968e563354b4090074 to your computer and use it in GitHub Desktop.

Select an option

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