authorgravatar for jahe788@gmail.comIntegratedQuantum <jahe788@gmail.com> 2022-11-09 16:33:48+01:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2022-11-09 17:33:48+02:00
logd1e7be0bd190e1d93a6375b051a180f739990191
treecb7c036233176d7fc0956ed25c58eccbf2e25dc4
parent61842da9f7d7fdbfdc76b135335a685da1de8789
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

Handle sentinel slices in `std.mem.zeroes`

Fixes #13256

1 files changed, 10 insertions(+), 1 deletions(-)

lib/std/mem.zig+10-1
......@@ -285,7 +285,14 @@ pub fn zeroes(comptime T: type) T {
285285 .Pointer => |ptr_info| {
286286 switch (ptr_info.size) {
287287 .Slice => {
288 return &[_]ptr_info.child{};
288 if (ptr_info.sentinel) |sentinel| {
289 if (ptr_info.child == u8 and @ptrCast(*const u8, sentinel).* == 0) {
290 return ""; // A special case for the most common use-case: null-terminated strings.
291 }
292 @compileError("Can't set a sentinel slice to zero. This would require allocating memory.");
293 } else {
294 return &[_]ptr_info.child{};
295 }
289296 },
290297 .C => {
291298 return null;
......@@ -373,6 +380,7 @@ test "zeroes" {
373380 optional: ?*u8,
374381 c_pointer: [*c]u8,
375382 slice: []u8,
383 nullTerminatedString: [:0]const u8,
376384 },
377385
378386 array: [2]u32,
......@@ -403,6 +411,7 @@ test "zeroes" {
403411 try testing.expectEqual(@as(?*u8, null), b.pointers.optional);
404412 try testing.expectEqual(@as([*c]u8, null), b.pointers.c_pointer);
405413 try testing.expectEqual(@as([]u8, &[_]u8{}), b.pointers.slice);
414 try testing.expectEqual(@as([:0]const u8, ""), b.pointers.nullTerminatedString);
406415 for (b.array) |e| {
407416 try testing.expectEqual(@as(u32, 0), e);
408417 }