authorgravatar for jahe788@gmail.comIntegratedQuantum <jahe788@gmail.com> 2022-11-09 16:33:48+01:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2023-01-09 13:56:20-07:00
log11c1ddfc977957e3ef9fd10512fffab768b4922a
tree40706c7dbba09bbe42a3cfc7becd3c6ddba6215f
parentc1fc15f9138610353bf53e0c10c27619c7dbab70

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 }