1
1
//! A variant of `SortedMap` that preserves insertion order.
2
2
3
- use std:: borrow:: Borrow ;
4
3
use std:: hash:: { Hash , Hasher } ;
5
4
use std:: iter:: FromIterator ;
6
5
@@ -76,11 +75,7 @@ impl<I: Idx, K: Ord, V> SortedIndexMultiMap<I, K, V> {
76
75
///
77
76
/// If there are multiple items that are equivalent to `key`, they will be yielded in
78
77
/// 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 > {
84
79
self . get_by_key_enumerated ( key) . map ( |( _, v) | v)
85
80
}
86
81
@@ -89,35 +84,12 @@ impl<I: Idx, K: Ord, V> SortedIndexMultiMap<I, K, V> {
89
84
///
90
85
/// If there are multiple items that are equivalent to `key`, they will be yielded in
91
86
/// 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..] . iter ( ) . map_while ( move |& i| {
90
+ let ( k, v) = & self . items [ i] ;
91
+ ( k == & key) . then_some ( ( i, v) )
92
+ } )
121
93
}
122
94
}
123
95
0 commit comments