adventurous/
strings.rs

1use std::collections::HashMap;
2
3/// A trait for counting the number of occurrences of each character in a string.
4pub trait CharCounts {
5    /// Returns a [`HashMap`] containing the number of occurrences
6    /// of each character in the string.
7    fn char_counts(&self) -> HashMap<char, usize>;
8}
9
10impl CharCounts for str {
11    fn char_counts(&self) -> HashMap<char, usize> {
12        let mut counts = HashMap::new();
13
14        for character in self.chars() {
15            *counts.entry(character).or_insert(0) += 1;
16        }
17
18        counts
19    }
20}
21
22#[cfg(test)]
23mod tests {
24    use super::*;
25
26    #[test]
27    fn test_char_counts() {
28        let mut expected = HashMap::new();
29        expected.insert('h', 1);
30        expected.insert('e', 1);
31        expected.insert('l', 3);
32        expected.insert('o', 2);
33        expected.insert(' ', 1);
34        expected.insert('w', 1);
35        expected.insert('r', 1);
36        expected.insert('d', 1);
37
38        assert_eq!("hello world".char_counts(), expected);
39        assert_eq!(String::from("hello world").char_counts(), expected)
40    }
41}