diff --git a/lib/std/mem.zig b/lib/std/mem.zig index 5c1c4f4394..99e64fac37 100644 --- a/lib/std/mem.zig +++ b/lib/std/mem.zig @@ -913,8 +913,9 @@ fn SliceTo(comptime T: type, comptime end: std.meta.Elem(T)) type { .pointer => |ptr_info| { const Elem = std.meta.Elem(T); const have_sentinel: bool = switch (ptr_info.size) { - .one, .slice, .many => if (std.meta.sentinel(T)) |s| s == end else false, - .c => false, + .one, .slice => if (std.meta.sentinel(T)) |s| s == end else false, + .many => if (std.meta.sentinel(T)) |s| s == end else true, + .c => true, }; return @Pointer(.slice, .{ .@"const" = ptr_info.is_const, @@ -961,8 +962,15 @@ test sliceTo { try testing.expectEqualSlices(u16, array[0..2], sliceTo(&array, 3)); try testing.expectEqualSlices(u16, array[0..2], sliceTo(array[0..3], 3)); + const many_ptr: [*]u16 = &array; + try testing.expectEqualSlices(u16, array[0..2], sliceTo(many_ptr, 3)); + try testing.expectEqual([:3]u16, @TypeOf(sliceTo(many_ptr, 3))); + const sentinel_ptr = @as([*:5]u16, @ptrCast(&array)); try testing.expectEqualSlices(u16, array[0..2], sliceTo(sentinel_ptr, 3)); + try testing.expectEqual([]u16, @TypeOf(sliceTo(sentinel_ptr, 3))); + try testing.expectEqualSlices(u16, array[0..4], sliceTo(sentinel_ptr, 5)); + try testing.expectEqual([:5]u16, @TypeOf(sliceTo(sentinel_ptr, 5))); try testing.expectEqualSlices(u16, array[0..4], sliceTo(sentinel_ptr, 99)); const optional_sentinel_ptr = @as(?[*:5]u16, @ptrCast(&array)); @@ -971,6 +979,7 @@ test sliceTo { const c_ptr = @as([*c]u16, &array); try testing.expectEqualSlices(u16, array[0..2], sliceTo(c_ptr, 3)); + try testing.expectEqual([:3]u16, @TypeOf(sliceTo(c_ptr, 3))); const slice: []u16 = &array; try testing.expectEqualSlices(u16, array[0..2], sliceTo(slice, 3)); @@ -1015,6 +1024,8 @@ fn lenSliceTo(ptr: anytype, comptime end: std.meta.Elem(@TypeOf(ptr))) usize { var i: usize = 0; while (ptr[i] != end and ptr[i] != s) i += 1; return i; + } else { + return indexOfSentinel(ptr_info.child, end, @ptrCast(ptr)); }, .c => { assert(ptr != null);