Skip to content

Commit 12510ab

Browse files
committed
Implement contains_key and contains_key_alt
Implement functions to check if a key exists in the map
1 parent 4d7a3f6 commit 12510ab

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

src/lib.rs

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,60 @@ impl<K1: Eq + Hash + Clone, K2: Eq + Hash + Clone, V> MultiMap<K1, K2, V> {
149149
result
150150
}
151151

152+
/// Returns true if the map contains a value for the specified key. The key may be any borrowed
153+
/// form of the map's key type, but Hash and Eq on the borrowed form must match those for the
154+
/// key type
155+
///
156+
/// ## Example
157+
/// ```
158+
/// #[macro_use]
159+
/// extern crate multi_map;
160+
/// use multi_map::MultiMap;
161+
/// # fn main() {
162+
/// let map = multimap! {
163+
/// 1, "One" => String::from("Eins"),
164+
/// 2, "Two" => String::from("Zwei"),
165+
/// 3, "Three" => String::from("Drei"),
166+
/// };
167+
/// assert!(map.contains_key(&1));
168+
/// assert!(!map.contains_key(&4));
169+
/// # }
170+
/// ```
171+
pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
172+
where
173+
K1: Borrow<Q>,
174+
Q: Hash + Eq,
175+
{
176+
self.value_map.contains_key(key)
177+
}
178+
179+
/// Returns true if the map contains a value for the specified alternative key. The key may be
180+
/// any borrowed form of the map's key type, but Hash and Eq on the borrowed form must match
181+
/// those for the key type
182+
///
183+
/// ## Example
184+
/// ```
185+
/// #[macro_use]
186+
/// extern crate multi_map;
187+
/// use multi_map::MultiMap;
188+
/// # fn main() {
189+
/// let map = multimap! {
190+
/// 1, "One" => String::from("Eins"),
191+
/// 2, "Two" => String::from("Zwei"),
192+
/// 3, "Three" => String::from("Drei"),
193+
/// };
194+
/// assert!(map.contains_key_alt(&"One"));
195+
/// assert!(!map.contains_key_alt(&"Four"));
196+
/// # }
197+
/// ```
198+
pub fn contains_key_alt<Q: ?Sized>(&self, key: &Q) -> bool
199+
where
200+
K2: Borrow<Q>,
201+
Q: Hash + Eq,
202+
{
203+
self.key_map.contains_key(key)
204+
}
205+
152206
/// Remove an item from the HashMap using the secondary key. The value for
153207
/// the given key is returned (if it exists). Ordinary HashMaps can't do
154208
/// this. This removes an item from both the main HashMap and the second
@@ -251,6 +305,10 @@ mod test {
251305
assert!(*map.get(&1).unwrap() == String::from("Ein"));
252306
assert!(*map.get(&2).unwrap() == String::from("Zwei"));
253307
assert!(*map.get(&3).unwrap() == String::from("Drei"));
308+
assert!(map.contains_key(&1));
309+
assert!(!map.contains_key(&4));
310+
assert!(map.contains_key_alt(&"One"));
311+
assert!(!map.contains_key_alt(&"Four"));
254312

255313
map.get_mut_alt(&"One").unwrap().push_str("s");
256314

0 commit comments

Comments
 (0)