| 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 | pub fn naive_count_32(haystack: &[u8], needle: u8) -> usize { | 
|---|
| 12 | haystack.iter().fold(init:0, |n: u32, c: &u8| 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 | /// ``` | 
|---|
| 24 | pub fn naive_count(utf8_chars: &[u8], needle: u8) -> usize { | 
|---|
| 25 | utf8_chars | 
|---|
| 26 | .iter() | 
|---|
| 27 | .fold(init:0, |n: usize, c: &u8| n + (*c == needle) as usize) | 
|---|
| 28 | } | 
|---|
| 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 | pub fn naive_num_chars(utf8_chars: &[u8]) -> usize { | 
|---|
| 43 | utf8_charsimpl Iterator  | 
|---|
| 44 | .iter() | 
|---|
| 45 | .filter(|&&byte: u8| (byte >> 6) != 0b10) | 
|---|
| 46 | .count() | 
|---|
| 47 | } | 
|---|
| 48 |  | 
|---|