data_structures_lib/
hashing.rs1use std::collections::{HashMap as StdMap, HashSet as StdSet};
2
3#[derive(Debug, Clone)]
5pub struct HashMap<K, V> {
6 data: StdMap<K, V>,
7}
8
9impl<K, V> HashMap<K, V>
10where
11 K: Eq + std::hash::Hash,
12{
13 pub fn new() -> Self {
15 Self {
16 data: StdMap::new(),
17 }
18 }
19
20 pub fn set(&mut self, key: K, value: V) {
22 self.data.insert(key, value);
23 }
24
25 pub fn get(&self, key: &K) -> Option<&V> {
27 self.data.get(key)
28 }
29
30 pub fn has(&self, key: &K) -> bool {
32 self.data.contains_key(key)
33 }
34
35 pub fn delete(&mut self, key: &K) -> Option<V> {
37 self.data.remove(key)
38 }
39
40 pub fn len(&self) -> usize {
42 self.data.len()
43 }
44
45 pub fn is_empty(&self) -> bool {
47 self.data.is_empty()
48 }
49
50 pub fn keys(&self) -> Vec<&K> {
52 self.data.keys().collect()
53 }
54
55 pub fn values(&self) -> Vec<&V> {
57 self.data.values().collect()
58 }
59}
60
61impl<K, V> Default for HashMap<K, V>
62where
63 K: Eq + std::hash::Hash,
64{
65 fn default() -> Self {
66 Self::new()
67 }
68}
69
70#[derive(Debug, Clone)]
72pub struct HashSet<T> {
73 data: StdSet<T>,
74}
75
76impl<T> HashSet<T>
77where
78 T: Eq + std::hash::Hash,
79{
80 pub fn new() -> Self {
82 Self {
83 data: StdSet::new(),
84 }
85 }
86
87 pub fn add(&mut self, value: T) {
89 self.data.insert(value);
90 }
91
92 pub fn remove(&mut self, value: &T) -> bool {
94 self.data.remove(value)
95 }
96
97 pub fn has(&self, value: &T) -> bool {
99 self.data.contains(value)
100 }
101
102 pub fn len(&self) -> usize {
104 self.data.len()
105 }
106
107 pub fn is_empty(&self) -> bool {
109 self.data.is_empty()
110 }
111
112 pub fn to_vec(&self) -> Vec<&T> {
114 self.data.iter().collect()
115 }
116}
117
118impl<T> Default for HashSet<T>
119where
120 T: Eq + std::hash::Hash,
121{
122 fn default() -> Self {
123 Self::new()
124 }
125}