authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-07-09 19:04:21-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-07-09 20:01:15-07:00
logaa1bdb43e01318a7a2724a44e371ca575794722d
treed0086f39b80954f038becc4f9bf0907280418e0e
parentdce08d9a5714a98510bdd08994b19f43ef8499d9

std.io.Writer.writeStructEndian: fix packed structs


1 files changed, 17 insertions(+), 6 deletions(-)

lib/std/io/Writer.zig+17-6
......@@ -794,12 +794,23 @@ pub fn writeStruct(w: *Writer, value: anytype) Error!void {
794794/// comptime-known and matches host endianness.
795795/// TODO: make sure this value is not a reference type
796796pub inline fn writeStructEndian(w: *Writer, value: anytype, endian: std.builtin.Endian) Error!void {
797 if (native_endian == endian) {
798 return w.writeStruct(value);
799 } else {
800 var copy = value;
801 std.mem.byteSwapAllFields(@TypeOf(value), &copy);
802 return w.writeStruct(copy);
797 switch (@typeInfo(@TypeOf(value))) {
798 .@"struct" => |info| switch (info.layout) {
799 .auto => @compileError("ill-defined memory layout"),
800 .@"extern" => {
801 if (native_endian == endian) {
802 return w.writeStruct(value);
803 } else {
804 var copy = value;
805 std.mem.byteSwapAllFields(@TypeOf(value), &copy);
806 return w.writeStruct(copy);
807 }
808 },
809 .@"packed" => {
810 return writeInt(w, info.backing_integer.?, @bitCast(value), endian);
811 },
812 },
813 else => @compileError("not a struct"),
803814 }
804815}
805816