ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
33.8k stars 2.47k forks source link

slicing sentinel-terminated array or pointer with `..` as end index should give a sentinel-terminated slice #3766

Open andrewrk opened 4 years ago

andrewrk commented 4 years ago

Follow-up from #3728. Depends on #863.

test "slice to the end of a null terminated pointer" {
    const string_literal = "hello, world";
    comptime expect(@typeOf(string_literal[5..]) == *const [7:0]u8);
    const slice: [:0]const u8 = string_literal;
    comptime expect(@typeOf(slice[5..]) == [*:0]const u8);
}
N00byEdge commented 8 months ago

Should it? ptr[std.mem.len(ptr) + 1..] could definitely be an unterminated pointer, while ptr[std.mem.len(ptr) + 1..:0] clearly is terminated, and only two characters longer to write.

mikdusan commented 8 months ago

wait, title asks for sentinel-terminated slice but the OP example tests for a sentinel-terminated pointer and current master produces a sentinel-terminated slice

so.... maybe OP example actually intended to test for sentinel-terminated slice and master is already there?

const std = @import("std");

pub fn main() void {
    const string_literal = "hello, world";
    //comptime expect(@typeOf(string_literal[5..]) == *const [7:0]u8);
    std.log.debug("A: {}", .{@TypeOf(string_literal)});

    const slice: [:0]const u8 = string_literal;
    //comptime expect(@typeOf(slice[5..]) == [*:0]const u8);
    std.log.debug("B: {}", .{@TypeOf(slice)});

    std.log.debug("C: {}", .{@TypeOf(slice[5..])});

    rtime(slice);
}

fn rtime(s: [:0]const u8) void {
    std.log.debug("D: {}", .{@TypeOf(s[5..])});
}

output:

debug: A: *const [12:0]u8
debug: B: [:0]const u8
debug: C: *const [7:0]u8
debug: D: [:0]const u8