Skip to content

Commit

Permalink
Add K: Borrow<Q>
Browse files Browse the repository at this point in the history
  • Loading branch information
Manishearth committed Feb 22, 2021
1 parent 40663dd commit 2a5cd63
Showing 1 changed file with 25 additions and 8 deletions.
33 changes: 25 additions & 8 deletions utils/litemap/src/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/master/LICENSE ).

use std::borrow::Borrow;
use std::mem;
use std::ops::{Index, IndexMut};

Expand Down Expand Up @@ -53,8 +54,12 @@ impl<K: Ord, V> LiteMap<K, V> {
/// assert_eq!(map.get(&1), Some(&"one"));
/// assert_eq!(map.get(&3), None);
/// ```
pub fn get(&self, key: &K) -> Option<&V> {
match self.values.binary_search_by(|k| k.0.cmp(&key)) {
pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
where
K: Borrow<Q>,
Q: Ord,
{
match self.values.binary_search_by(|k| k.0.borrow().cmp(&key)) {
Ok(found) => Some(&self.values[found].1),
Err(_) => None,
}
Expand All @@ -71,8 +76,12 @@ impl<K: Ord, V> LiteMap<K, V> {
/// assert_eq!(map.contains_key(&1), true);
/// assert_eq!(map.contains_key(&3), false);
/// ```
pub fn contains_key(&self, key: &K) -> bool {
self.values.binary_search_by(|k| k.0.cmp(&key)).is_ok()
pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
where
K: Borrow<Q>,
Q: Ord,
{
self.values.binary_search_by(|k| k.0.borrow().cmp(&key)).is_ok()
}

/// Get the value associated with `key`, if it exists, as a mutable reference.
Expand All @@ -88,8 +97,12 @@ impl<K: Ord, V> LiteMap<K, V> {
/// }
/// assert_eq!(map.get(&1), Some(&"uno"));
/// ```
pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
match self.values.binary_search_by(|k| k.0.cmp(&key)) {
pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
where
K: Borrow<Q>,
Q: Ord,
{
match self.values.binary_search_by(|k| k.0.borrow().cmp(&key)) {
Ok(found) => Some(&mut self.values[found].1),
Err(_) => None,
}
Expand Down Expand Up @@ -154,8 +167,12 @@ impl<K: Ord, V> LiteMap<K, V> {
/// assert_eq!(map.remove(&1), Some("one"));
/// assert_eq!(map.get(&1), None);
/// ```
pub fn remove(&mut self, key: &K) -> Option<V> {
match self.values.binary_search_by(|k| k.0.cmp(key)) {
pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
where
K: Borrow<Q>,
Q: Ord,
{
match self.values.binary_search_by(|k| k.0.borrow().cmp(key)) {
Ok(found) => Some(self.values.remove(found).1),
Err(_) => None,
}
Expand Down

0 comments on commit 2a5cd63

Please sign in to comment.