@@ -1120,7 +1120,7 @@ impl<A: Array> SmallVec<A> {
11201120 unsafe {
11211121 let ( mut ptr, mut len, cap) = self . triple_mut ( ) ;
11221122 if * len == cap {
1123- self . reserve ( 1 ) ;
1123+ self . reserve_one_unchecked ( ) ;
11241124 let ( heap_ptr, heap_len) = self . data . heap_mut ( ) ;
11251125 ptr = heap_ptr;
11261126 len = heap_len;
@@ -1225,13 +1225,23 @@ impl<A: Array> SmallVec<A> {
12251225 infallible ( self . try_reserve ( additional) )
12261226 }
12271227
1228+ /// Internal method used to grow in push() and insert(), where we know already we have to grow.
1229+ #[ cold]
1230+ fn reserve_one_unchecked ( & mut self ) {
1231+ debug_assert_eq ! ( self . len( ) , self . capacity( ) ) ;
1232+ let new_cap = self . len ( )
1233+ . checked_add ( 1 )
1234+ . and_then ( usize:: checked_next_power_of_two)
1235+ . expect ( "capacity overflow" ) ;
1236+ infallible ( self . try_grow ( new_cap) )
1237+ }
1238+
12281239 /// Reserve capacity for `additional` more elements to be inserted.
12291240 ///
12301241 /// May reserve more space to avoid frequent reallocations.
12311242 pub fn try_reserve ( & mut self , additional : usize ) -> Result < ( ) , CollectionAllocErr > {
1232- // prefer triple_mut() even if triple() would work
1233- // so that the optimizer removes duplicated calls to it
1234- // from callers like insert()
1243+ // prefer triple_mut() even if triple() would work so that the optimizer removes duplicated
1244+ // calls to it from callers.
12351245 let ( _, & mut len, cap) = self . triple_mut ( ) ;
12361246 if cap - len >= additional {
12371247 return Ok ( ( ) ) ;
@@ -1357,10 +1367,14 @@ impl<A: Array> SmallVec<A> {
13571367 ///
13581368 /// Panics if `index > len`.
13591369 pub fn insert ( & mut self , index : usize , element : A :: Item ) {
1360- self . reserve ( 1 ) ;
1361-
13621370 unsafe {
1363- let ( ptr, len_ptr, _) = self . triple_mut ( ) ;
1371+ let ( mut ptr, mut len_ptr, cap) = self . triple_mut ( ) ;
1372+ if * len_ptr == cap {
1373+ self . reserve_one_unchecked ( ) ;
1374+ let ( heap_ptr, heap_len_ptr) = self . data . heap_mut ( ) ;
1375+ ptr = heap_ptr;
1376+ len_ptr = heap_len_ptr;
1377+ }
13641378 let mut ptr = ptr. as_ptr ( ) ;
13651379 let len = * len_ptr;
13661380 ptr = ptr. add ( index) ;
0 commit comments