Skip to content

Commit fc26686

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

File tree

3 files changed

+11
-8
lines changed

3 files changed

+11
-8
lines changed

lib/std/cstr.zig

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ test "cstr fns" {
2828

2929
fn testCStrFnsImpl() void {
3030
testing.expect(cmp("aoeu", "aoez") == -1);
31-
testing.expect(mem.len(u8, "123456789") == 9);
31+
testing.expect(mem.len(u8, "123456789".*) == 9);
3232
}
3333

3434
/// Returns a mutable, null-terminated slice with the same length as `slice`.

lib/std/mem.zig

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -357,18 +357,21 @@ 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 sentinel: T = comptime meta.Sentinel(@TypeOf(ptr));
361362
var count: usize = 0;
362-
while (ptr[count] != 0) : (count += 1) {}
363+
while (ptr[count] != sentinel) : (count += 1) {}
363364
return count;
364365
}
365366

366-
pub fn toSliceConst(comptime T: type, ptr: [*:0]const T) [:0]const T {
367-
return ptr[0..len(T, ptr) :0];
367+
pub fn toSliceConst(comptime T: type, ptr: var) [:meta.Sentinel(@TypeOf(ptr))]const T {
368+
const sentinel: T = comptime meta.Sentinel(@TypeOf(ptr));
369+
return ptr[0..len(T, ptr) :sentinel];
368370
}
369371

370-
pub fn toSlice(comptime T: type, ptr: [*:0]T) [:0]T {
371-
return ptr[0..len(T, ptr) :0];
372+
pub fn toSlice(comptime T: type, ptr: var) [:meta.Sentinel(@TypeOf(ptr))]T {
373+
const sentinel: T = comptime meta.Sentinel(@TypeOf(ptr));
374+
return ptr[0..len(T, ptr) :sentinel];
372375
}
373376

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

test/stage1/behavior/misc.zig

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -365,7 +365,7 @@ test "string concatenation" {
365365
comptime expect(@TypeOf(a) == *const [12:0]u8);
366366
comptime expect(@TypeOf(b) == *const [12:0]u8);
367367

368-
const len = mem.len(u8, b);
368+
const len = mem.len(u8, b.*);
369369
const len_with_null = len + 1;
370370
{
371371
var i: u32 = 0;

0 commit comments

Comments
 (0)