zig

fork of https://codeberg.org/ziglang/zig
Log | Files | Refs | README | LICENSE

commit 11c1ddfc977957e3ef9fd10512fffab768b4922a (tree)
parent c1fc15f9138610353bf53e0c10c27619c7dbab70
Author: IntegratedQuantum <43880493+IntegratedQuantum@users.noreply.github.com>
Date:   Wed,  9 Nov 2022 16:33:48 +0100

Handle sentinel slices in `std.mem.zeroes`

Fixes #13256
Diffstat:
Mlib/std/mem.zig | 11++++++++++-
1 file changed, 10 insertions(+), 1 deletion(-)

diff --git a/lib/std/mem.zig b/lib/std/mem.zig @@ -285,7 +285,14 @@ pub fn zeroes(comptime T: type) T { .Pointer => |ptr_info| { switch (ptr_info.size) { .Slice => { - return &[_]ptr_info.child{}; + if (ptr_info.sentinel) |sentinel| { + if (ptr_info.child == u8 and @ptrCast(*const u8, sentinel).* == 0) { + return ""; // A special case for the most common use-case: null-terminated strings. + } + @compileError("Can't set a sentinel slice to zero. This would require allocating memory."); + } else { + return &[_]ptr_info.child{}; + } }, .C => { return null; @@ -373,6 +380,7 @@ test "zeroes" { optional: ?*u8, c_pointer: [*c]u8, slice: []u8, + nullTerminatedString: [:0]const u8, }, array: [2]u32, @@ -403,6 +411,7 @@ test "zeroes" { try testing.expectEqual(@as(?*u8, null), b.pointers.optional); try testing.expectEqual(@as([*c]u8, null), b.pointers.c_pointer); try testing.expectEqual(@as([]u8, &[_]u8{}), b.pointers.slice); + try testing.expectEqual(@as([:0]const u8, ""), b.pointers.nullTerminatedString); for (b.array) |e| { try testing.expectEqual(@as(u32, 0), e); }