aboutsummaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorSobeston <15335529+Sobeston@users.noreply.github.com>2020-08-24 16:47:44 +0100
committerAndrew Kelley <andrew@ziglang.org>2020-08-26 17:37:05 -0400
commit7d0bb0774e957e81fee7240d410944a0a56c303d (patch)
treeeafc09d9d2670498058901ab321a84781afbae18 /lib
parent091d693c5381a17d1de01ab372481f629b560c7c (diff)
downloadzig-7d0bb0774e957e81fee7240d410944a0a56c303d.tar.gz
zig-7d0bb0774e957e81fee7240d410944a0a56c303d.zip
std.mem.count
Diffstat (limited to 'lib')
-rw-r--r--lib/std/mem.zig29
1 files changed, 29 insertions, 0 deletions
diff --git a/lib/std/mem.zig b/lib/std/mem.zig
index 0deb178548..e5c53bbb07 100644
--- a/lib/std/mem.zig
+++ b/lib/std/mem.zig
@@ -893,6 +893,35 @@ test "mem.indexOf" {
testing.expect(lastIndexOfScalar(u8, "boo", 'o').? == 2);
}
+/// Returns the number of needles inside the haystack
+/// needle.len must be > 0
+/// does not count overlapping needles
+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;
+}
+
+test "mem.count" {
+ testing.expect(count(u8, "", "h") == 0);
+ testing.expect(count(u8, "h", "h") == 1);
+ testing.expect(count(u8, "hh", "h") == 2);
+ testing.expect(count(u8, "world!", "hello") == 0);
+ testing.expect(count(u8, "hello world!", "hello") == 1);
+ testing.expect(count(u8, " abcabc abc", "abc") == 3);
+ testing.expect(count(u8, "udexdcbvbruhasdrw", "bruh") == 1);
+ testing.expect(count(u8, "foo bar", "o bar") == 1);
+ testing.expect(count(u8, "foofoofoo", "foo") == 3);
+ testing.expect(count(u8, "fffffff", "ff") == 3);
+}
+
/// 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.