11//! A variant of `SortedMap` that preserves insertion order.
22
3- use std:: borrow:: Borrow ;
43use std:: hash:: { Hash , Hasher } ;
54use std:: iter:: FromIterator ;
65
@@ -76,11 +75,7 @@ impl<I: Idx, K: Ord, V> SortedIndexMultiMap<I, K, V> {
7675 ///
7776 /// If there are multiple items that are equivalent to `key`, they will be yielded in
7877 /// insertion order.
79- pub fn get_by_key < Q : ' a > ( & ' a self , key : & Q ) -> impl ' a + Iterator < Item = & ' a V >
80- where
81- Q : Ord + ?Sized ,
82- K : Borrow < Q > ,
83- {
78+ pub fn get_by_key ( & ' a self , key : K ) -> impl ' a + Iterator < Item = & ' a V > {
8479 self . get_by_key_enumerated ( key) . map ( |( _, v) | v)
8580 }
8681
@@ -89,35 +84,12 @@ impl<I: Idx, K: Ord, V> SortedIndexMultiMap<I, K, V> {
8984 ///
9085 /// If there are multiple items that are equivalent to `key`, they will be yielded in
9186 /// insertion order.
92- pub fn get_by_key_enumerated < Q > ( & self , key : & Q ) -> impl ' _ + Iterator < Item = ( I , & V ) >
93- where
94- Q : Ord + ?Sized ,
95- K : Borrow < Q > ,
96- {
97- match self . binary_search_idx ( key) {
98- Err ( _) => self . idxs_to_items_enumerated ( & [ ] ) ,
99-
100- Ok ( idx) => {
101- let start = self . idx_sorted_by_item_key [ ..idx]
102- . partition_point ( |& i| self . items [ i] . 0 . borrow ( ) != key) ;
103- let end = idx
104- + self . idx_sorted_by_item_key [ idx..]
105- . partition_point ( |& i| self . items [ i] . 0 . borrow ( ) == key) ;
106- self . idxs_to_items_enumerated ( & self . idx_sorted_by_item_key [ start..end] )
107- }
108- }
109- }
110-
111- fn binary_search_idx < Q > ( & self , key : & Q ) -> Result < usize , usize >
112- where
113- Q : Ord + ?Sized ,
114- K : Borrow < Q > ,
115- {
116- self . idx_sorted_by_item_key . binary_search_by ( |& idx| self . items [ idx] . 0 . borrow ( ) . cmp ( key) )
117- }
118-
119- fn idxs_to_items_enumerated ( & ' a self , idxs : & ' a [ I ] ) -> impl ' a + Iterator < Item = ( I , & ' a V ) > {
120- idxs. iter ( ) . map ( move |& idx| ( idx, & self . items [ idx] . 1 ) )
87+ pub fn get_by_key_enumerated ( & ' a self , key : K ) -> impl ' _ + Iterator < Item = ( I , & V ) > {
88+ let lower_bound = self . idx_sorted_by_item_key . partition_point ( |& i| self . items [ i] . 0 < key) ;
89+ self . idx_sorted_by_item_key [ lower_bound..]
90+ . iter ( )
91+ . take_while ( move |& & i| self . items [ i] . 0 . eq ( & key) )
92+ . map ( move |& idx| ( idx, & self . items [ idx] . 1 ) )
12193 }
12294}
12395
0 commit comments