@@ -1120,10 +1120,8 @@ 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 ) ;
1124
- let ( heap_ptr, heap_len) = self . data . heap_mut ( ) ;
1125
- ptr = heap_ptr;
1126
- len = heap_len;
1123
+ self . reserve_one_unchecked ( ) ;
1124
+ ( ptr, len) = self . data . heap_mut ( ) ;
1127
1125
}
1128
1126
ptr:: write ( ptr. as_ptr ( ) . add ( * len) , value) ;
1129
1127
* len += 1 ;
@@ -1225,13 +1223,23 @@ impl<A: Array> SmallVec<A> {
1225
1223
infallible ( self . try_reserve ( additional) )
1226
1224
}
1227
1225
1226
+ /// Internal method used to grow in push() and insert(), where we know already we have to grow.
1227
+ #[ cold]
1228
+ fn reserve_one_unchecked ( & mut self ) {
1229
+ debug_assert_eq ! ( self . len( ) , self . capacity( ) ) ;
1230
+ let new_cap = self . len ( )
1231
+ . checked_add ( 1 )
1232
+ . and_then ( usize:: checked_next_power_of_two)
1233
+ . expect ( "capacity overflow" ) ;
1234
+ infallible ( self . try_grow ( new_cap) )
1235
+ }
1236
+
1228
1237
/// Reserve capacity for `additional` more elements to be inserted.
1229
1238
///
1230
1239
/// May reserve more space to avoid frequent reallocations.
1231
1240
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()
1241
+ // prefer triple_mut() even if triple() would work so that the optimizer removes duplicated
1242
+ // calls to it from callers.
1235
1243
let ( _, & mut len, cap) = self . triple_mut ( ) ;
1236
1244
if cap - len >= additional {
1237
1245
return Ok ( ( ) ) ;
@@ -1357,10 +1365,12 @@ impl<A: Array> SmallVec<A> {
1357
1365
///
1358
1366
/// Panics if `index > len`.
1359
1367
pub fn insert ( & mut self , index : usize , element : A :: Item ) {
1360
- self . reserve ( 1 ) ;
1361
-
1362
1368
unsafe {
1363
- let ( ptr, len_ptr, _) = self . triple_mut ( ) ;
1369
+ let ( mut ptr, mut len_ptr, cap) = self . triple_mut ( ) ;
1370
+ if * len_ptr == cap {
1371
+ self . reserve_one_unchecked ( ) ;
1372
+ ( ptr, len_ptr) = self . data . heap_mut ( ) ;
1373
+ }
1364
1374
let mut ptr = ptr. as_ptr ( ) ;
1365
1375
let len = * len_ptr;
1366
1376
ptr = ptr. add ( index) ;
0 commit comments