Skip to content

Commit b233568

Browse files
nnethercotembrubeck
authored andcommitted
Optimize insert for the case where index == len.
By skipping the call to `copy` with a zero length. This makes it closer to `push`. This speeds up rustc (which uses `SmallVec` extensively) by 2% on one benchmark. Also clarify the panic condition.
1 parent bb8def4 commit b233568

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

src/lib.rs

+9-4
Original file line numberDiff line numberDiff line change
@@ -1068,17 +1068,22 @@ impl<A: Array> SmallVec<A> {
10681068

10691069
/// Insert an element at position `index`, shifting all elements after it to the right.
10701070
///
1071-
/// Panics if `index` is out of bounds.
1071+
/// Panics if `index > len`.
10721072
pub fn insert(&mut self, index: usize, element: A::Item) {
10731073
self.reserve(1);
10741074

10751075
unsafe {
10761076
let (mut ptr, len_ptr, _) = self.triple_mut();
10771077
let len = *len_ptr;
1078-
assert!(index <= len);
1079-
*len_ptr = len + 1;
10801078
ptr = ptr.add(index);
1081-
ptr::copy(ptr, ptr.add(1), len - index);
1079+
if index < len {
1080+
ptr::copy(ptr, ptr.add(1), len - index);
1081+
} else if index == len {
1082+
// No elements need shifting.
1083+
} else {
1084+
panic!("index exceeds length");
1085+
}
1086+
*len_ptr = len + 1;
10821087
ptr::write(ptr, element);
10831088
}
10841089
}

0 commit comments

Comments
 (0)