@@ -275,18 +275,14 @@ impl<K, V> IndexMapCore<K, V> {
275
275
}
276
276
}
277
277
278
- /// Append a key-value pair, *without* checking whether it already exists,
279
- /// and return the pair's new index.
280
- fn push ( & mut self , hash : HashValue , key : K , value : V ) -> usize {
281
- let i = self . entries . len ( ) ;
282
- self . indices . insert ( hash. get ( ) , i, get_hash ( & self . entries ) ) ;
283
- if i == self . entries . capacity ( ) {
278
+ /// Append a key-value pair to `entries`, *without* checking whether it already exists.
279
+ fn push_entry ( & mut self , hash : HashValue , key : K , value : V ) {
280
+ if self . entries . len ( ) == self . entries . capacity ( ) {
284
281
// Reserve our own capacity synced to the indices,
285
282
// rather than letting `Vec::push` just double it.
286
283
self . reserve_entries ( 1 ) ;
287
284
}
288
285
self . entries . push ( Bucket { hash, key, value } ) ;
289
- i
290
286
}
291
287
292
288
/// Return the index in `entries` where an equivalent key can be found
@@ -302,9 +298,13 @@ impl<K, V> IndexMapCore<K, V> {
302
298
where
303
299
K : Eq ,
304
300
{
305
- match self . get_index_of ( hash, & key) {
306
- Some ( i) => ( i, Some ( mem:: replace ( & mut self . entries [ i] . value , value) ) ) ,
307
- None => ( self . push ( hash, key, value) , None ) ,
301
+ match self . find_or_insert ( hash, & key) {
302
+ Ok ( i) => ( i, Some ( mem:: replace ( & mut self . entries [ i] . value , value) ) ) ,
303
+ Err ( i) => {
304
+ debug_assert_eq ! ( i, self . entries. len( ) ) ;
305
+ self . push_entry ( hash, key, value) ;
306
+ ( i, None )
307
+ }
308
308
}
309
309
}
310
310
@@ -712,14 +712,18 @@ impl<'a, K, V> VacantEntry<'a, K, V> {
712
712
713
713
/// Return the index where the key-value pair will be inserted.
714
714
pub fn index ( & self ) -> usize {
715
- self . map . len ( )
715
+ self . map . indices . len ( )
716
716
}
717
717
718
718
/// Inserts the entry's key and the given value into the map, and returns a mutable reference
719
719
/// to the value.
720
720
pub fn insert ( self , value : V ) -> & ' a mut V {
721
- let i = self . map . push ( self . hash , self . key , value) ;
722
- & mut self . map . entries [ i] . value
721
+ let i = self . index ( ) ;
722
+ let Self { map, hash, key } = self ;
723
+ map. indices . insert ( hash. get ( ) , i, get_hash ( & map. entries ) ) ;
724
+ debug_assert_eq ! ( i, map. entries. len( ) ) ;
725
+ map. push_entry ( hash, key, value) ;
726
+ & mut map. entries [ i] . value
723
727
}
724
728
}
725
729
0 commit comments