Skip to content

Commit c284b99

Browse files
committed
std: extend mem.{len,toSlice,toSliceConst} to take any sentinel
1 parent ba1d213 commit c284b99

File tree

1 file changed

+12
-6
lines changed

1 file changed

+12
-6
lines changed

lib/std/mem.zig

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -357,18 +357,24 @@ pub fn eql(comptime T: type, a: []const T, b: []const T) bool {
357357
return true;
358358
}
359359

360-
pub fn len(comptime T: type, ptr: [*:0]const T) usize {
360+
pub fn len(comptime T: type, ptr: var) usize {
361+
const ptrInfo = @typeInfo(@TypeOf(ptr)).Pointer;
362+
assert(ptrInfo.size == .Many);
363+
const sentinel: T = comptime ptrInfo.sentinel.?;
364+
361365
var count: usize = 0;
362-
while (ptr[count] != 0) : (count += 1) {}
366+
while (ptr[count] != sentinel) : (count += 1) {}
363367
return count;
364368
}
365369

366-
pub fn toSliceConst(comptime T: type, ptr: [*:0]const T) [:0]const T {
367-
return ptr[0..len(T, ptr) :0];
370+
pub fn toSliceConst(comptime T: type, ptr: var) [:@typeInfo(@TypeOf(ptr)).Pointer.sentinel.?]const T {
371+
const sentinel: T = comptime @typeInfo(@TypeOf(ptr)).Pointer.sentinel.?;
372+
return ptr[0..len(T, ptr) :sentinel];
368373
}
369374

370-
pub fn toSlice(comptime T: type, ptr: [*:0]T) [:0]T {
371-
return ptr[0..len(T, ptr) :0];
375+
pub fn toSlice(comptime T: type, ptr: var) [:@typeInfo(@TypeOf(ptr)).Pointer.sentinel.?]T {
376+
const sentinel: T = comptime @typeInfo(@TypeOf(ptr)).Pointer.sentinel.?;
377+
return ptr[0..len(T, ptr) :sentinel];
372378
}
373379

374380
/// Returns true if all elements in a slice are equal to the scalar value provided

0 commit comments

Comments
 (0)