| ... | ... | @@ -991,6 +991,40 @@ test "mem.count" { |
| 991 | 991 | testing.expect(count(u8, "owowowu", "owowu") == 1); |
| 992 | 992 | } |
| 993 | 993 | |
| 994 | /// Returns true if the haystack contains expected_count or more needles |
| 995 | /// needle.len must be > 0 |
| 996 | /// does not count overlapping needles |
| 997 | pub fn containsAtLeast(comptime T: type, haystack: []const T, expected_count: usize, needle: []const T) bool { |
| 998 | assert(needle.len > 0); |
| 999 | if (expected_count == 0) return true; |
| 1000 | |
| 1001 | var i: usize = 0; |
| 1002 | var found: usize = 0; |
| 1003 | |
| 1004 | while (indexOfPos(T, haystack, i, needle)) |idx| { |
| 1005 | i = idx + needle.len; |
| 1006 | found += 1; |
| 1007 | if (found == expected_count) return true; |
| 1008 | } |
| 1009 | return false; |
| 1010 | } |
| 1011 | |
| 1012 | test "mem.containsAtLeast" { |
| 1013 | testing.expect(containsAtLeast(u8, "aa", 0, "a")); |
| 1014 | testing.expect(containsAtLeast(u8, "aa", 1, "a")); |
| 1015 | testing.expect(containsAtLeast(u8, "aa", 2, "a")); |
| 1016 | testing.expect(!containsAtLeast(u8, "aa", 3, "a")); |
| 1017 | |
| 1018 | testing.expect(containsAtLeast(u8, "radaradar", 1, "radar")); |
| 1019 | testing.expect(!containsAtLeast(u8, "radaradar", 2, "radar")); |
| 1020 | |
| 1021 | testing.expect(containsAtLeast(u8, "radarradaradarradar", 3, "radar")); |
| 1022 | testing.expect(!containsAtLeast(u8, "radarradaradarradar", 4, "radar")); |
| 1023 | |
| 1024 | testing.expect(containsAtLeast(u8, " radar radar ", 2, "radar")); |
| 1025 | testing.expect(!containsAtLeast(u8, " radar radar ", 3, "radar")); |
| 1026 | } |
| 1027 | |
| 994 | 1028 | /// Reads an integer from memory with size equal to bytes.len. |
| 995 | 1029 | /// T specifies the return type, which must be large enough to store |
| 996 | 1030 | /// the result. |