Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

std: add containsAtLeastScalar to mem #22826

Merged
merged 6 commits into from
Feb 15, 2025
Merged
Changes from 4 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
28 changes: 28 additions & 0 deletions lib/std/mem.zig
Original file line number Diff line number Diff line change
Expand Up @@ -1610,6 +1610,8 @@ test count {
/// Returns true if the haystack contains expected_count or more needles
/// needle.len must be > 0
/// does not count overlapping needles
//
/// See also: `containsAtLeastScalar`
pub fn containsAtLeast(comptime T: type, haystack: []const T, expected_count: usize, needle: []const T) bool {
assert(needle.len > 0);
if (expected_count == 0) return true;
Expand Down Expand Up @@ -1641,6 +1643,32 @@ test containsAtLeast {
try testing.expect(!containsAtLeast(u8, " radar radar ", 3, "radar"));
}

/// Returns true if the haystack contains expected_count or more needles
//
/// See also: `containsAtLeast`
pub fn containsAtLeastScalar(comptime T: type, haystack: []const T, expected_count: usize, needle: T) bool {
if (expected_count == 0) return true;

var found: usize = 0;

for (0..haystack.len) |i| {
if (haystack[i] == needle) found += 1;
if (found == expected_count) return true;
}
LmanTW marked this conversation as resolved.
Show resolved Hide resolved

return false;
}

test containsAtLeastScalar {
try testing.expect(containsAtLeastScalar(u8, "aa", 0, 'a'));
try testing.expect(containsAtLeastScalar(u8, "aa", 1, 'a'));
try testing.expect(containsAtLeastScalar(u8, "aa", 2, 'a'));
try testing.expect(!containsAtLeastScalar(u8, "aa", 3, 'a'));

try testing.expect(containsAtLeastScalar(u8, "adadda", 3, 'd'));
try testing.expect(!containsAtLeastScalar(u8, "adadda", 4, 'd'));
}

/// Reads an integer from memory with size equal to bytes.len.
/// T specifies the return type, which must be large enough to store
/// the result.
Expand Down
Loading