Skip to content

Commit 632239f

Browse files
committed
mem.sliceTo on C pointers should return an optional slice
1 parent 36da8d0 commit 632239f

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

lib/std/mem.zig

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -654,6 +654,7 @@ fn SliceTo(comptime T: type, comptime end: meta.Elem(T)) type {
654654
new_ptr_info.sentinel = null;
655655
}
656656
}
657+
return @Type(std.builtin.TypeInfo{ .Pointer = new_ptr_info });
657658
},
658659
else => {},
659660
},
@@ -668,15 +669,16 @@ fn SliceTo(comptime T: type, comptime end: meta.Elem(T)) type {
668669
new_ptr_info.sentinel = null;
669670
}
670671
}
672+
return @Type(std.builtin.TypeInfo{ .Pointer = new_ptr_info });
671673
},
672674
.C => {
673675
new_ptr_info.sentinel = end;
674676
// C pointers are always allowzero, but we don't want the return type to be.
675677
assert(new_ptr_info.is_allowzero);
676678
new_ptr_info.is_allowzero = false;
679+
return ?@Type(std.builtin.TypeInfo{ .Pointer = new_ptr_info });
677680
},
678681
}
679-
return @Type(std.builtin.TypeInfo{ .Pointer = new_ptr_info });
680682
},
681683
else => {},
682684
}
@@ -689,13 +691,12 @@ fn SliceTo(comptime T: type, comptime end: meta.Elem(T)) type {
689691
/// If the pointer type is sentinel terminated and `end` matches that terminator, the
690692
/// resulting slice is also sentinel terminated.
691693
/// Pointer properties such as mutability and alignment are preserved.
692-
/// C pointers are assumed to be non-null.
693694
pub fn sliceTo(ptr: anytype, comptime end: meta.Elem(@TypeOf(ptr))) SliceTo(@TypeOf(ptr), end) {
694-
if (@typeInfo(@TypeOf(ptr)) == .Optional) {
695+
const Result = SliceTo(@TypeOf(ptr), end);
696+
if (@typeInfo(Result) == .Optional) {
695697
const non_null = ptr orelse return null;
696698
return sliceTo(non_null, end);
697699
}
698-
const Result = SliceTo(@TypeOf(ptr), end);
699700
const length = lenSliceTo(ptr, end);
700701
if (@typeInfo(Result).Pointer.sentinel) |s| {
701702
return ptr[0..length :s];
@@ -723,7 +724,9 @@ test "sliceTo" {
723724
try testing.expectEqualSlices(u16, array[0..4], sliceTo(optional_sentinel_ptr, 99).?);
724725

725726
const c_ptr = @as([*c]u16, &array);
726-
try testing.expectEqualSlices(u16, array[0..2], sliceTo(c_ptr, 3));
727+
try testing.expectEqualSlices(u16, array[0..2], sliceTo(c_ptr, 3).?);
728+
const null_c_ptr = @as(?[*c]u16, null);
729+
try testing.expect(@as([]u16, null), sliceTo(null_c_ptr, 3));
727730

728731
const slice: []u16 = &array;
729732
try testing.expectEqualSlices(u16, array[0..2], sliceTo(slice, 3));

0 commit comments

Comments
 (0)