authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-07-18 10:43:02-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-07-19 19:57:37-07:00
log8489bab1f46ef7a5cdcf598b10f1150a9e0c2f0d
tree8c89211024c91a85714390097d981a0d673f15fb
parentbd64bf0e47e75481569dcc3ba519e3d2e7f7b276

std.Io.Writer: add missing writeSliceSwap


2 files changed, 29 insertions(+), 1 deletions(-)

lib/std/Io/Writer.zig+27-1
......@@ -851,6 +851,9 @@ pub inline fn writeStruct(w: *Writer, value: anytype, endian: std.builtin.Endian
851851 }
852852}
853853
854/// If, `endian` is not native,
855/// * Asserts that the buffer storage capacity is at least enough to store `@sizeOf(Elem)`
856/// * Asserts that the buffer is aligned enough for `@alignOf(Elem)`.
854857pub inline fn writeSliceEndian(
855858 w: *Writer,
856859 Elem: type,
......@@ -860,7 +863,22 @@ pub inline fn writeSliceEndian(
860863 if (native_endian == endian) {
861864 return writeAll(w, @ptrCast(slice));
862865 } else {
863 return w.writeArraySwap(w, Elem, slice);
866 return writeSliceSwap(w, Elem, slice);
867 }
868}
869
870/// Asserts that the buffer storage capacity is at least enough to store `@sizeOf(Elem)`
871///
872/// Asserts that the buffer is aligned enough for `@alignOf(Elem)`.
873pub fn writeSliceSwap(w: *Writer, Elem: type, slice: []const Elem) Error!void {
874 var i: usize = 0;
875 while (i < slice.len) {
876 const dest_bytes = try w.writableSliceGreedy(@sizeOf(Elem));
877 const dest: []Elem = @alignCast(@ptrCast(dest_bytes[0 .. dest_bytes.len - dest_bytes.len % @sizeOf(Elem)]));
878 const copy_len = @min(dest.len, slice.len - i);
879 @memcpy(dest[0..copy_len], slice[i..][0..copy_len]);
880 i += copy_len;
881 std.mem.byteSwapAllElements(Elem, dest);
864882 }
865883}
866884
......@@ -2630,3 +2648,11 @@ test writeStruct {
26302648 }, &buffer);
26312649 }
26322650}
2651
2652test writeSliceEndian {
2653 var buffer: [4]u8 align(2) = undefined;
2654 var w: Writer = .fixed(&buffer);
2655 const array: [2]u16 = .{ 0x1234, 0x5678 };
2656 try writeSliceEndian(&w, u16, &array, .big);
2657 try testing.expectEqualSlices(u8, &.{ 0x12, 0x34, 0x56, 0x78 }, &buffer);
2658}
lib/std/zig/Server.zig+2
......@@ -118,6 +118,8 @@ pub fn init(options: Options) !Server {
118118 .in = options.in,
119119 .out = options.out,
120120 };
121 assert(s.out.buffer.len >= 4);
122 std.debug.assertAligned(s.out.buffer.ptr, .@"4");
121123 try s.serveStringMessage(.zig_version, options.zig_version);
122124 return s;
123125}