commit 54f774f7966e48a8419dbe2d3b37ae974ec03a83 (tree)
parent 97a2f4e7ae9c52c595841347bb0b26572b180dcf
Author: Matthew Borkowski <matthew.h.borkowski@gmail.com>
Date: Sat, 22 May 2021 14:03:06 -0400
make writeIntSlice functions work for signed integers
Diffstat:
1 file changed, 26 insertions(+), 2 deletions(-)
diff --git a/lib/std/mem.zig b/lib/std/mem.zig
@@ -1444,7 +1444,7 @@ pub fn writeIntSliceLittle(comptime T: type, buffer: []u8, value: T) void {
// TODO I want to call writeIntLittle here but comptime eval facilities aren't good enough
const uint = std.meta.Int(.unsigned, @typeInfo(T).Int.bits);
- var bits = @truncate(uint, value);
+ var bits = @bitCast(uint, value);
for (buffer) |*b| {
b.* = @truncate(u8, bits);
bits >>= 8;
@@ -1464,7 +1464,7 @@ pub fn writeIntSliceBig(comptime T: type, buffer: []u8, value: T) void {
// TODO I want to call writeIntBig here but comptime eval facilities aren't good enough
const uint = std.meta.Int(.unsigned, @typeInfo(T).Int.bits);
- var bits = @truncate(uint, value);
+ var bits = @bitCast(uint, value);
var index: usize = buffer.len;
while (index != 0) {
index -= 1;
@@ -2028,6 +2028,30 @@ fn testWriteIntImpl() !void {
0x00,
0x00,
}));
+
+ writeIntSlice(i16, bytes[0..], @as(i16, -21555), Endian.Little);
+ try testing.expect(eql(u8, &bytes, &[_]u8{
+ 0xCD,
+ 0xAB,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ }));
+
+ writeIntSlice(i16, bytes[0..], @as(i16, -21555), Endian.Big);
+ try testing.expect(eql(u8, &bytes, &[_]u8{
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0xAB,
+ 0xCD,
+ }));
}
/// Returns the smallest number in a slice. O(n).