Skip to content

Commit 61de47d

Browse files
committed
sorted_map: make the impls of Index and get match ones from BTreeMap
1 parent 875ce5f commit 61de47d

File tree

1 file changed

+26
-12
lines changed

1 file changed

+26
-12
lines changed

src/librustc_data_structures/sorted_map.rs

+26-12
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,10 @@ impl<K: Ord, V> SortedMap<K, V> {
8282
}
8383

8484
#[inline]
85-
pub fn get(&self, key: &K) -> Option<&V> {
85+
pub fn get<Q>(&self, key: &Q) -> Option<&V>
86+
where K: Borrow<Q>,
87+
Q: Ord + ?Sized
88+
{
8689
match self.lookup_index_for(key) {
8790
Ok(index) => {
8891
unsafe {
@@ -96,7 +99,10 @@ impl<K: Ord, V> SortedMap<K, V> {
9699
}
97100

98101
#[inline]
99-
pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
102+
pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
103+
where K: Borrow<Q>,
104+
Q: Ord + ?Sized
105+
{
100106
match self.lookup_index_for(key) {
101107
Ok(index) => {
102108
unsafe {
@@ -207,8 +213,11 @@ impl<K: Ord, V> SortedMap<K, V> {
207213

208214
/// Looks up the key in `self.data` via `slice::binary_search()`.
209215
#[inline(always)]
210-
fn lookup_index_for(&self, key: &K) -> Result<usize, usize> {
211-
self.data.binary_search_by(|&(ref x, _)| x.cmp(key))
216+
fn lookup_index_for<Q>(&self, key: &Q) -> Result<usize, usize>
217+
where K: Borrow<Q>,
218+
Q: Ord + ?Sized
219+
{
220+
self.data.binary_search_by(|&(ref x, _)| x.borrow().cmp(key))
212221
}
213222

214223
#[inline]
@@ -257,18 +266,23 @@ impl<K: Ord, V> IntoIterator for SortedMap<K, V> {
257266
}
258267
}
259268

260-
impl<K: Ord, V, Q: Borrow<K>> Index<Q> for SortedMap<K, V> {
269+
impl<'a, K, Q, V> Index<&'a Q> for SortedMap<K, V>
270+
where K: Ord + Borrow<Q>,
271+
Q: Ord + ?Sized
272+
{
261273
type Output = V;
262-
fn index(&self, index: Q) -> &Self::Output {
263-
let k: &K = index.borrow();
264-
self.get(k).unwrap()
274+
275+
fn index(&self, key: &Q) -> &Self::Output {
276+
self.get(key).expect("no entry found for key")
265277
}
266278
}
267279

268-
impl<K: Ord, V, Q: Borrow<K>> IndexMut<Q> for SortedMap<K, V> {
269-
fn index_mut(&mut self, index: Q) -> &mut Self::Output {
270-
let k: &K = index.borrow();
271-
self.get_mut(k).unwrap()
280+
impl<'a, K, Q, V> IndexMut<&'a Q> for SortedMap<K, V>
281+
where K: Ord + Borrow<Q>,
282+
Q: Ord + ?Sized
283+
{
284+
fn index_mut(&mut self, key: &Q) -> &mut Self::Output {
285+
self.get_mut(key).expect("no entry found for key")
272286
}
273287
}
274288

0 commit comments

Comments
 (0)