Skip to main content

data_structures_lib/
hashing.rs

1use std::collections::{HashMap as StdMap, HashSet as StdSet};
2
3/// A hash map.
4#[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    /// Creates a new HashMap.
14    pub fn new() -> Self {
15        Self {
16            data: StdMap::new(),
17        }
18    }
19
20    /// Sets a key-value pair.
21    pub fn set(&mut self, key: K, value: V) {
22        self.data.insert(key, value);
23    }
24
25    /// Gets a reference to the value for a key.
26    pub fn get(&self, key: &K) -> Option<&V> {
27        self.data.get(key)
28    }
29
30    /// Returns true if the key exists.
31    pub fn has(&self, key: &K) -> bool {
32        self.data.contains_key(key)
33    }
34
35    /// Removes a key.
36    pub fn delete(&mut self, key: &K) -> Option<V> {
37        self.data.remove(key)
38    }
39
40    /// Returns the number of pairs.
41    pub fn len(&self) -> usize {
42        self.data.len()
43    }
44
45    /// Returns true if the map is empty.
46    pub fn is_empty(&self) -> bool {
47        self.data.is_empty()
48    }
49
50    /// Returns a Vec of all keys.
51    pub fn keys(&self) -> Vec<&K> {
52        self.data.keys().collect()
53    }
54
55    /// Returns a Vec of all values.
56    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/// A hash set.
71#[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    /// Creates a new HashSet.
81    pub fn new() -> Self {
82        Self {
83            data: StdSet::new(),
84        }
85    }
86
87    /// Adds a value.
88    pub fn add(&mut self, value: T) {
89        self.data.insert(value);
90    }
91
92    /// Removes a value.
93    pub fn remove(&mut self, value: &T) -> bool {
94        self.data.remove(value)
95    }
96
97    /// Returns true if the value is in the set.
98    pub fn has(&self, value: &T) -> bool {
99        self.data.contains(value)
100    }
101
102    /// Returns the number of values.
103    pub fn len(&self) -> usize {
104        self.data.len()
105    }
106
107    /// Returns true if the set is empty.
108    pub fn is_empty(&self) -> bool {
109        self.data.is_empty()
110    }
111
112    /// Returns a Vec of all values.
113    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}