core_dev/collections/
counter.rs1
2
3
4
5use core::fmt;
6use std::collections::HashMap;
7use std::fmt::Display;
8use std::fmt::Formatter;
9use std::fmt::Result;
10use std::hash::Hash;
11use std::str::Chars;
12
13
14
15pub struct Counter {
16 _counter_char: HashMap<char, i32>,
17 chars: bool,
18 _counter_int: HashMap<i32, i32>,
19}
20
21
22impl Counter {
23 fn create_hashmap_from_chars(_char_iter: Chars<'_>) -> HashMap<char, i32> {
24 let mut _counter = HashMap::new();
25 for _char in _char_iter {
26 *_counter.entry(_char).or_insert(0) += 1;
27 }
28 _counter
29 }
30
31 pub fn from_str(_static_string: &str) -> Counter {
32 Counter {
33 _counter_char: Counter::create_hashmap_from_chars(_static_string.chars()),
34 chars: true,
35 _counter_int: HashMap::new(),
36 }
37 }
38
39 pub fn from_string(_string: String) -> Counter {
40 Counter {
41 _counter_char: Counter::create_hashmap_from_chars(_string.chars()),
42 chars: true,
43 _counter_int: HashMap::new()
44 }
45 }
46
47 pub fn from_string_ref(_string_ref: &String) -> Counter {
48 Counter {
49 _counter_char: Counter::create_hashmap_from_chars(_string_ref.chars()),
50 chars: true,
51 _counter_int: HashMap::new()
52 }
53 }
54
55 pub fn from_i32(_i32_number: i32) -> Counter {
56 let mut __i32_number: i32 = _i32_number;
57 let mut _counter: HashMap<i32, i32> = HashMap::new();
58
59 while __i32_number != 0 {
60 let digit = __i32_number % 10;
61 *_counter.entry(digit).or_insert(0) += 1;
62 __i32_number /= 10;
63 }
64
65 Counter {
66 _counter_char: HashMap::new(),
67 chars: false,
68 _counter_int: _counter,
69 }
70 }
71}
72
73
74impl Display for Counter {
75 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
76 if self.chars {
77 write!(f, "{:?}", self._counter_char)
78 } else {
79 write!(f, "{:?}", self._counter_int)
80 }
81 }
82}
83
84