| ... | ... | @@ -893,6 +893,35 @@ test "mem.indexOf" { |
| 893 | 893 | testing.expect(lastIndexOfScalar(u8, "boo", 'o').? == 2); |
| 894 | 894 | } |
| 895 | 895 | |
| 896 | /// Returns the number of needles inside the haystack |
| 897 | /// needle.len must be > 0 |
| 898 | /// does not count overlapping needles |
| 899 | pub fn count(comptime T: type, haystack: []const T, needle: []const T) usize { |
| 900 | assert(needle.len > 0); |
| 901 | var i: usize = 0; |
| 902 | var found: usize = 0; |
| 903 | |
| 904 | while (indexOfPos(T, haystack, i, needle)) |idx| { |
| 905 | i = idx + needle.len; |
| 906 | found += 1; |
| 907 | } |
| 908 | |
| 909 | return found; |
| 910 | } |
| 911 | |
| 912 | test "mem.count" { |
| 913 | testing.expect(count(u8, "", "h") == 0); |
| 914 | testing.expect(count(u8, "h", "h") == 1); |
| 915 | testing.expect(count(u8, "hh", "h") == 2); |
| 916 | testing.expect(count(u8, "world!", "hello") == 0); |
| 917 | testing.expect(count(u8, "hello world!", "hello") == 1); |
| 918 | testing.expect(count(u8, " abcabc abc", "abc") == 3); |
| 919 | testing.expect(count(u8, "udexdcbvbruhasdrw", "bruh") == 1); |
| 920 | testing.expect(count(u8, "foo bar", "o bar") == 1); |
| 921 | testing.expect(count(u8, "foofoofoo", "foo") == 3); |
| 922 | testing.expect(count(u8, "fffffff", "ff") == 3); |
| 923 | } |
| 924 | |
| 896 | 925 | /// Reads an integer from memory with size equal to bytes.len. |
| 897 | 926 | /// T specifies the return type, which must be large enough to store |
| 898 | 927 | /// the result. |