Repository navigation
Closed
Description
Moved from #3731.
const std = @import("std");
const assert = std.debug.assert;
test "obtaining a null terminated slice" {
// here we have a normal array
var buf: [50]u8 = undefined;
buf[0] = 'a';
buf[1] = 'b';
buf[2] = 'c';
buf[3] = 0;
// now we obtain a null terminated slice:
const ptr = buf[0..3 :0];
// ptr is a pointer to null-terminated array,
// because the len was comptime known (See #863)
comptime assert(@typeOf(ptr) == *[3:0]u8);
var runtime_len: usize = 3;
const ptr2 = buf[0..runtime_len :0];
// ptr2 is a null-terminated slice
comptime assert(@typeOf(ptr2) == [:0]u8);
buf[3] += 1;
_ = buf[0..3 :0]; // safety panic: slice sentinel assertion failed
}Along with this:
- slicing a sentinel-terminated pointer without this syntax should yield a non-sentinel-terminated result.
-
index of a sentinel-terminated array which is comptime-known to be len, is a comptime-known value when loading. no-op with safety check when storing.extracted to improved handling of index of a sentinel-terminated array which is comptime-known to be len #3962 -
compile error for incorrect sentinel when doing sentinel slicingextracted to add compile error for sentinel assertion failed #3963
There are already quite a few places this would be handy:
../lib/std/fs.zig: // TODO avoid @ptrCast here using slice syntax with https://github.com/ziglang/zig/issues/3731
../lib/std/os.zig: // TODO avoid @ptrCast here using slice syntax with https://github.com/ziglang/zig/issues/3731
../lib/std/os.zig: // TODO avoid @ptrCast using slice syntax with https://github.com/ziglang/zig/issues/3731
../lib/std/os.zig: // TODO avoid @ptrCast here using slice syntax with https://github.com/ziglang/zig/issues/3731
../lib/std/os.zig: // TODO avoid @ptrCast here using slice syntax with https://github.com/ziglang/zig/issues/3731
../lib/std/os.zig: // TODO avoid @ptrCast here using slice syntax with https://github.com/ziglang/zig/issues/3731
Activity
JesseRMeyer commentedon Nov 25, 2019
Nit:
Should be:
fix std.mem.addNullByte and implement sentinel slicing
daurnimator commentedon Dec 19, 2019
Would be interesting to use this for e.g. newline terminated strings.
fix std.mem.addNullByte and implement sentinel slicing