Skip to content

Commit 43c6b13

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

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

lib/std/mem.zig

Lines changed: 8 additions & 4 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
}
@@ -691,11 +693,11 @@ fn SliceTo(comptime T: type, comptime end: meta.Elem(T)) type {
691693
/// Pointer properties such as mutability and alignment are preserved.
692694
/// C pointers are assumed to be non-null.
693695
pub fn sliceTo(ptr: anytype, comptime end: meta.Elem(@TypeOf(ptr))) SliceTo(@TypeOf(ptr), end) {
694-
if (@typeInfo(@TypeOf(ptr)) == .Optional) {
696+
const Result = SliceTo(@TypeOf(ptr), end);
697+
if (@typeInfo(Result) == .Optional) {
695698
const non_null = ptr orelse return null;
696699
return sliceTo(non_null, end);
697700
}
698-
const Result = SliceTo(@TypeOf(ptr), end);
699701
const length = lenSliceTo(ptr, end);
700702
if (@typeInfo(Result).Pointer.sentinel) |s| {
701703
return ptr[0..length :s];
@@ -723,7 +725,9 @@ test "sliceTo" {
723725
try testing.expectEqualSlices(u16, array[0..4], sliceTo(optional_sentinel_ptr, 99).?);
724726

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

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

0 commit comments

Comments
 (0)