authorgravatar for 82919705+LmanTW@users.noreply.github.comLmanTW <82919705+LmanTW@users.noreply.github.com> 2025-02-15 10:40:55+08:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2025-02-15 03:40:55+01:00
log13ad984b1f403c240ee677c32c2b43980d098be3
tree3639c0ebb8073cfde079426a614abd64f831d418
parent8a3aebaee0a68d037a6f311bc5c1b426e8e1884c
signaturebadge-check Signed by PGP key B5690EEEBB952194

std: add containsAtLeastScalar to mem (#22826)


1 files changed, 30 insertions(+), 0 deletions(-)

lib/std/mem.zig+30
......@@ -1611,6 +1611,8 @@ test count {
16111611/// Returns true if the haystack contains expected_count or more needles
16121612/// needle.len must be > 0
16131613/// does not count overlapping needles
1614//
1615/// See also: `containsAtLeastScalar`
16141616pub fn containsAtLeast(comptime T: type, haystack: []const T, expected_count: usize, needle: []const T) bool {
16151617 assert(needle.len > 0);
16161618 if (expected_count == 0) return true;
......@@ -1642,6 +1644,34 @@ test containsAtLeast {
16421644 try testing.expect(!containsAtLeast(u8, " radar radar ", 3, "radar"));
16431645}
16441646
1647/// Returns true if the haystack contains expected_count or more needles
1648//
1649/// See also: `containsAtLeast`
1650pub fn containsAtLeastScalar(comptime T: type, haystack: []const T, expected_count: usize, needle: T) bool {
1651 if (expected_count == 0) return true;
1652
1653 var found: usize = 0;
1654
1655 for (haystack) |item| {
1656 if (item == needle) {
1657 found += 1;
1658 if (found == expected_count) return true;
1659 }
1660 }
1661
1662 return false;
1663}
1664
1665test containsAtLeastScalar {
1666 try testing.expect(containsAtLeastScalar(u8, "aa", 0, 'a'));
1667 try testing.expect(containsAtLeastScalar(u8, "aa", 1, 'a'));
1668 try testing.expect(containsAtLeastScalar(u8, "aa", 2, 'a'));
1669 try testing.expect(!containsAtLeastScalar(u8, "aa", 3, 'a'));
1670
1671 try testing.expect(containsAtLeastScalar(u8, "adadda", 3, 'd'));
1672 try testing.expect(!containsAtLeastScalar(u8, "adadda", 4, 'd'));
1673}
1674
16451675/// Reads an integer from memory with size equal to bytes.len.
16461676/// T specifies the return type, which must be large enough to store
16471677/// the result.