authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-07-16 13:08:33-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-07-16 17:20:03-07:00
log73cfba4d0d0ed00de8f5fbb83257d703ba284d61
tree773197139a7de182bcaf05d923836ef6c1e6a5a9
parente7a639967e91c8408ae281a97966e3dd67dd5565

std.Io.Writer: fix writeStruct


1 files changed, 28 insertions(+), 4 deletions(-)

lib/std/Io/Writer.zig+28-4
......@@ -483,7 +483,7 @@ pub fn writeSplatAll(w: *Writer, data: [][]const u8, splat: usize) Error!void {
483483
484484 // Deal with any left over splats
485485 if (data.len != 0 and truncate < data[index].len * splat) {
486 std.debug.assert(index == data.len - 1);
486 assert(index == data.len - 1);
487487 var remaining_splat = splat;
488488 while (true) {
489489 remaining_splat -= truncate / data[index].len;
......@@ -840,11 +840,11 @@ pub inline fn writeStruct(w: *Writer, value: anytype, endian: std.builtin.Endian
840840 .auto => @compileError("ill-defined memory layout"),
841841 .@"extern" => {
842842 if (native_endian == endian) {
843 return w.writeStruct(value);
843 return w.writeAll(@ptrCast((&value)[0..1]));
844844 } else {
845845 var copy = value;
846846 std.mem.byteSwapAllFields(@TypeOf(value), &copy);
847 return w.writeStruct(copy);
847 return w.writeAll(@ptrCast((&copy)[0..1]));
848848 }
849849 },
850850 .@"packed" => {
......@@ -2606,8 +2606,32 @@ test "allocating sendFile" {
26062606 var file_reader = file_writer.moveToReader();
26072607 try file_reader.seekTo(0);
26082608
2609 var allocating: std.io.Writer.Allocating = .init(std.testing.allocator);
2609 var allocating: std.io.Writer.Allocating = .init(testing.allocator);
26102610 defer allocating.deinit();
26112611
26122612 _ = try file_reader.interface.streamRemaining(&allocating.writer);
26132613}
2614
2615test writeStruct {
2616 var buffer: [16]u8 = undefined;
2617 const S = extern struct { a: u64, b: u32, c: u32 };
2618 const s: S = .{ .a = 1, .b = 2, .c = 3 };
2619 {
2620 var w: Writer = .fixed(&buffer);
2621 try w.writeStruct(s, .little);
2622 try testing.expectEqualSlices(u8, &.{
2623 1, 0, 0, 0, 0, 0, 0, 0, //
2624 2, 0, 0, 0, //
2625 3, 0, 0, 0, //
2626 }, &buffer);
2627 }
2628 {
2629 var w: Writer = .fixed(&buffer);
2630 try w.writeStruct(s, .big);
2631 try testing.expectEqualSlices(u8, &.{
2632 0, 0, 0, 0, 0, 0, 0, 1, //
2633 0, 0, 0, 2, //
2634 0, 0, 0, 3, //
2635 }, &buffer);
2636 }
2637}