@@ -1120,7 +1120,7 @@ impl<A: Array> SmallVec<A> {
1120
1120
unsafe {
1121
1121
let ( mut ptr, mut len, cap) = self . triple_mut ( ) ;
1122
1122
if * len == cap {
1123
- self . reserve ( 1 ) ;
1123
+ self . reserve_one_unchecked ( ) ;
1124
1124
let ( heap_ptr, heap_len) = self . data . heap_mut ( ) ;
1125
1125
ptr = heap_ptr;
1126
1126
len = heap_len;
@@ -1225,13 +1225,23 @@ impl<A: Array> SmallVec<A> {
1225
1225
infallible ( self . try_reserve ( additional) )
1226
1226
}
1227
1227
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
+
1228
1239
/// Reserve capacity for `additional` more elements to be inserted.
1229
1240
///
1230
1241
/// May reserve more space to avoid frequent reallocations.
1231
1242
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.
1235
1245
let ( _, & mut len, cap) = self . triple_mut ( ) ;
1236
1246
if cap - len >= additional {
1237
1247
return Ok ( ( ) ) ;
@@ -1357,10 +1367,14 @@ impl<A: Array> SmallVec<A> {
1357
1367
///
1358
1368
/// Panics if `index > len`.
1359
1369
pub fn insert ( & mut self , index : usize , element : A :: Item ) {
1360
- self . reserve ( 1 ) ;
1361
-
1362
1370
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
+ }
1364
1378
let mut ptr = ptr. as_ptr ( ) ;
1365
1379
let len = * len_ptr;
1366
1380
ptr = ptr. add ( index) ;
0 commit comments