From b2335682bcaf6d0b33d6c0caeb077d9aaa608b6d Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 23 Jun 2022 14:03:50 +1000 Subject: [PATCH] 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. --- src/lib.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index d721789..64b45de 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1068,17 +1068,22 @@ impl SmallVec { /// 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); } }