authorgravatar for squeek502@hotmail.comRyan Liptak <squeek502@hotmail.com> 2025-10-03 14:22:11-07:00
committergravatar for squeek502@hotmail.comRyan Liptak <squeek502@hotmail.com> 2025-10-03 16:29:09-07:00
log98dd8856ef901b99f198d992146abd0545adb5b2
treeddbb200658e3411840cb08dcf668997e48201d8b
parent83f8441c4f26bdc2ca630aa6225512f9d3927a66

std.mem: Add `countScalar`


2 files changed, 21 insertions(+), 1 deletions(-)

build.zig+1-1
...@@ -260,7 +260,7 @@ pub fn build(b: *std.Build) !void {...@@ -260,7 +260,7 @@ pub fn build(b: *std.Build) !void {
260 };260 };
261 const git_describe = mem.trim(u8, git_describe_untrimmed, " \n\r");261 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, '-')) {
264 0 => {264 0 => {
265 // Tagged release version (e.g. 0.10.0).265 // Tagged release version (e.g. 0.10.0).
266 if (!mem.eql(u8, git_describe, version_string)) {266 if (!mem.eql(u8, git_describe, version_string)) {
lib/std/mem.zig+20
...@@ -1704,6 +1704,26 @@ test count {...@@ -1704,6 +1704,26 @@ test count {
1704 try testing.expect(count(u8, "owowowu", "owowu") == 1);1704 try testing.expect(count(u8, "owowowu", "owowu") == 1);
1705}1705}
17061706
1707/// Returns the number of needles inside the haystack
1708pub 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
1720test 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
1707/// Returns true if the haystack contains expected_count or more needles1727/// Returns true if the haystack contains expected_count or more needles
1708/// needle.len must be > 01728/// needle.len must be > 0
1709/// does not count overlapping needles1729/// does not count overlapping needles