Skip to content

Commit 98dd885

Browse files
committed
std.mem: Add countScalar
1 parent 83f8441 commit 98dd885

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

build.zig

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,7 @@ pub fn build(b: *std.Build) !void {
260260
};
261261
const git_describe = mem.trim(u8, git_describe_untrimmed, " \n\r");
262262

263-
switch (mem.count(u8, git_describe, "-")) {
263+
switch (mem.countScalar(u8, git_describe, '-')) {
264264
0 => {
265265
// Tagged release version (e.g. 0.10.0).
266266
if (!mem.eql(u8, git_describe, version_string)) {

lib/std/mem.zig

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1704,6 +1704,26 @@ test count {
17041704
try testing.expect(count(u8, "owowowu", "owowu") == 1);
17051705
}
17061706

1707+
/// Returns the number of needles inside the haystack
1708+
pub fn countScalar(comptime T: type, haystack: []const T, needle: T) usize {
1709+
var i: usize = 0;
1710+
var found: usize = 0;
1711+
1712+
while (findScalarPos(T, haystack, i, needle)) |idx| {
1713+
i = idx + 1;
1714+
found += 1;
1715+
}
1716+
1717+
return found;
1718+
}
1719+
1720+
test countScalar {
1721+
try testing.expectEqual(0, countScalar(u8, "", 'h'));
1722+
try testing.expectEqual(1, countScalar(u8, "h", 'h'));
1723+
try testing.expectEqual(2, countScalar(u8, "hh", 'h'));
1724+
try testing.expectEqual(3, countScalar(u8, " abcabc abc", 'b'));
1725+
}
1726+
17071727
/// Returns true if the haystack contains expected_count or more needles
17081728
/// needle.len must be > 0
17091729
/// does not count overlapping needles

0 commit comments

Comments
 (0)