From aa1bdb43e01318a7a2724a44e371ca575794722d Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Wed, 9 Jul 2025 19:04:21 -0700 Subject: [PATCH] std.io.Writer.writeStructEndian: fix packed structs --- lib/std/io/Writer.zig | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/lib/std/io/Writer.zig b/lib/std/io/Writer.zig index dc6d914834..9a0839c9c5 100644 --- a/lib/std/io/Writer.zig +++ b/lib/std/io/Writer.zig @@ -794,12 +794,23 @@ pub fn writeStruct(w: *Writer, value: anytype) Error!void { /// comptime-known and matches host endianness. /// TODO: make sure this value is not a reference type pub inline fn writeStructEndian(w: *Writer, value: anytype, endian: std.builtin.Endian) Error!void { - if (native_endian == endian) { - return w.writeStruct(value); - } else { - var copy = value; - std.mem.byteSwapAllFields(@TypeOf(value), ©); - return w.writeStruct(copy); + switch (@typeInfo(@TypeOf(value))) { + .@"struct" => |info| switch (info.layout) { + .auto => @compileError("ill-defined memory layout"), + .@"extern" => { + if (native_endian == endian) { + return w.writeStruct(value); + } else { + var copy = value; + std.mem.byteSwapAllFields(@TypeOf(value), ©); + return w.writeStruct(copy); + } + }, + .@"packed" => { + return writeInt(w, info.backing_integer.?, @bitCast(value), endian); + }, + }, + else => @compileError("not a struct"), } }