/rust/registry/src/index.crates.io-1949cf8c6b5b557f/bytecount-0.6.9/src/naive.rs
Line | Count | Source |
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 | | /// ``` |
11 | 0 | pub fn naive_count_32(haystack: &[u8], needle: u8) -> usize { |
12 | 0 | haystack.iter().fold(0, |n, c| n + (*c == needle) as u32) as usize |
13 | 0 | } |
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 | | /// ``` |
24 | 0 | pub fn naive_count(utf8_chars: &[u8], needle: u8) -> usize { |
25 | 0 | utf8_chars |
26 | 0 | .iter() |
27 | 0 | .fold(0, |n, c| n + (*c == needle) as usize) |
28 | 0 | } |
29 | | |
30 | | /// Count the number of UTF-8 encoded Unicode codepoints in a slice of bytes, simple |
31 | | /// |
32 | | /// This function is safe to use on any byte array, valid UTF-8 or not, |
33 | | /// but the output is only meaningful for well-formed UTF-8. |
34 | | /// |
35 | | /// # Example |
36 | | /// |
37 | | /// ``` |
38 | | /// let swordfish = "メカジキ"; |
39 | | /// let char_count = bytecount::naive_num_chars(swordfish.as_bytes()); |
40 | | /// assert_eq!(char_count, 4); |
41 | | /// ``` |
42 | 0 | pub fn naive_num_chars(utf8_chars: &[u8]) -> usize { |
43 | 0 | utf8_chars |
44 | 0 | .iter() |
45 | 0 | .filter(|&&byte| (byte >> 6) != 0b10) |
46 | 0 | .count() |
47 | 0 | } |