Skip to content

Commit

Permalink
Optimize insert for the case where index == len.
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
nnethercote authored and mbrubeck committed Jun 24, 2022
1 parent bb8def4 commit b233568
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1068,17 +1068,22 @@ impl<A: Array> SmallVec<A> {

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

unsafe {
let (mut ptr, len_ptr, _) = self.triple_mut();
let len = *len_ptr;
assert!(index <= len);
*len_ptr = len + 1;
ptr = ptr.add(index);
ptr::copy(ptr, ptr.add(1), len - index);
if index < len {
ptr::copy(ptr, ptr.add(1), len - index);
} else if index == len {
// No elements need shifting.
} else {
panic!("index exceeds length");
}
*len_ptr = len + 1;
ptr::write(ptr, element);
}
}
Expand Down

0 comments on commit b233568

Please sign in to comment.