Skip to content

Commit

Permalink
Prevent get and get_mut from panicking
Browse files Browse the repository at this point in the history
In contrast to direct indexing, the use of get and get_mut is generally
expected not to panic (as practiced by std collections).
  • Loading branch information
V02460 authored and havarnov committed May 19, 2022
1 parent 3c4eb75 commit 190756c
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@ where
K: Borrow<Q>,
Q: Eq + Hash,
{
self.inner.get(k).map(|v| &v[0])
self.inner.get(k)?.get(0)
}

/// Returns a mutable reference to the first item in the vector corresponding to
Expand All @@ -351,7 +351,7 @@ where
K: Borrow<Q>,
Q: Eq + Hash,
{
self.inner.get_mut(k).map(|v| v.get_mut(0).unwrap())
self.inner.get_mut(k)?.get_mut(0)
}

/// Returns a reference to the vector corresponding to the key.
Expand Down Expand Up @@ -1077,6 +1077,14 @@ mod tests {
assert_eq!(m.get(&1), Some(&42));
}

#[test]
fn get_empty() {
let mut m: MultiMap<usize, usize> = MultiMap::new();
m.insert(1, 42);
m.get_vec_mut(&1).and_then(Vec::pop);
assert_eq!(m.get(&1), None);
}

#[test]
fn get_vec_not_present() {
let m: MultiMap<usize, usize> = MultiMap::new();
Expand Down Expand Up @@ -1140,6 +1148,14 @@ mod tests {
assert_eq!(m.get_vec(&1), Some(&vec![5, 10]))
}

#[test]
fn get_mut_empty() {
let mut m: MultiMap<usize, usize> = MultiMap::new();
m.insert(1, 42);
m.get_vec_mut(&1).and_then(Vec::pop);
assert_eq!(m.get_mut(&1), None);
}

#[test]
fn keys() {
let mut m: MultiMap<usize, usize> = MultiMap::new();
Expand Down

0 comments on commit 190756c

Please sign in to comment.