Skip to content

Commit 8489bab

Browse files
committed
std.Io.Writer: add missing writeSliceSwap
1 parent bd64bf0 commit 8489bab

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

lib/std/Io/Writer.zig

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -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)`.
854857
pub 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)`.
873+
pub 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+
2652+
test 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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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
}

0 commit comments

Comments
 (0)