Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ pub fn build(b: *std.Build) !void {
};
const git_describe = mem.trim(u8, git_describe_untrimmed, " \n\r");

switch (mem.count(u8, git_describe, "-")) {
switch (mem.countScalar(u8, git_describe, '-')) {
0 => {
// Tagged release version (e.g. 0.10.0).
if (!mem.eql(u8, git_describe, version_string)) {
Expand Down
41 changes: 39 additions & 2 deletions lib/std/mem.zig
Original file line number Diff line number Diff line change
Expand Up @@ -1602,12 +1602,10 @@ pub fn count(comptime T: type, haystack: []const T, needle: []const T) usize {
assert(needle.len > 0);
var i: usize = 0;
var found: usize = 0;

while (indexOfPos(T, haystack, i, needle)) |idx| {
i = idx + needle.len;
found += 1;
}

return found;
}

Expand All @@ -1625,6 +1623,45 @@ test count {
try testing.expect(count(u8, "owowowu", "owowu") == 1);
}

/// Returns the number of needles inside the haystack
pub fn countScalar(comptime T: type, haystack: []const T, needle: T) usize {
var found: usize = 0;
for (haystack) |item| {
if (item == needle) found += 1;
}
return found;
}

test countScalar {
try testing.expect(countScalar(u8, "", 'h') == 0);
try testing.expect(countScalar(u8, "h", 'h') == 1);
try testing.expect(countScalar(u8, "hh", 'h') == 2);
try testing.expect(countScalar(u8, "fffffff", 'f') == 7);
try testing.expect(countScalar(u8, "owowowu", 'w') == 3);
}

/// Returns the number of any of the needles inside the haystack
pub fn countAny(comptime T: type, haystack: []const T, needle: []const T) usize {
assert(needle.len > 0);
var i: usize = 0;
var found: usize = 0;
while (indexOfAnyPos(T, haystack, i, needle)) |idx| {
i = idx + 1;
found += 1;
}
return found;
}

test countAny {
try testing.expect(countAny(u8, "", "h") == 0);
try testing.expect(countAny(u8, "h", "h") == 1);
try testing.expect(countAny(u8, "hh", "h") == 2);
try testing.expect(countAny(u8, "fffffff", "f") == 7);
try testing.expect(countAny(u8, "owowowu", "wo") == 6);
try testing.expect(countAny(u8, "foofoofoo", "foo") == 9);
try testing.expect(countAny(u8, "foobarfoo", "bar") == 3);
}

/// Returns true if the haystack contains expected_count or more needles
/// needle.len must be > 0
/// does not count overlapping needles
Expand Down