bytecount/naive.rs
1/// Count up to `(2^32)-1` occurrences of a byte in a slice
2/// of bytes, simple
3///
4/// # Example
5///
6/// ```
7/// let s = b"This is yet another Text with spaces";
8/// let number_of_spaces = bytecount::naive_count_32(s, b' ');
9/// assert_eq!(number_of_spaces, 6);
10/// ```
11pub fn naive_count_32(haystack: &[u8], needle: u8) -> usize {
12 haystack.iter().fold(0, |n, c| n + (*c == needle) as u32) as usize
13}
14
15/// Count occurrences of a byte in a slice of bytes, simple
16///
17/// # Example
18///
19/// ```
20/// let s = b"This is yet another Text with spaces";
21/// let number_of_spaces = bytecount::naive_count(s, b' ');
22/// assert_eq!(number_of_spaces, 6);
23/// ```
24pub fn naive_count(utf8_chars: &[u8], needle: u8) -> usize {
25 utf8_chars.iter().fold(0, |n, c| n + (*c == needle) as usize)
26}
27
28/// Count the number of UTF-8 encoded Unicode codepoints in a slice of bytes, simple
29///
30/// This function is safe to use on any byte array, valid UTF-8 or not,
31/// but the output is only meaningful for well-formed UTF-8.
32///
33/// # Example
34///
35/// ```
36/// let swordfish = "メカジキ";
37/// let char_count = bytecount::naive_num_chars(swordfish.as_bytes());
38/// assert_eq!(char_count, 4);
39/// ```
40pub fn naive_num_chars(utf8_chars: &[u8]) -> usize {
41 utf8_chars.iter().filter(|&&byte| (byte >> 6) != 0b10).count()
42}