Optimize Vec::insert for the case where index == len. · rust-lang/rust@679c5ee (original) (raw)

Original file line number Diff line number Diff line change
@@ -1379,9 +1379,6 @@ impl<T, A: Allocator> Vec<T, A> {
1379 1379 }
1380 1380
1381 1381 let len = self.len();
1382 -if index > len {
1383 -assert_failed(index, len);
1384 -}
1385 1382
1386 1383 // space for the new element
1387 1384 if len == self.buf.capacity() {
@@ -1393,9 +1390,15 @@ impl<T, A: Allocator> Vec<T, A> {
1393 1390 // The spot to put the new value
1394 1391 {
1395 1392 let p = self.as_mut_ptr().add(index);
1396 -// Shift everything over to make space. (Duplicating the
1397 -// `index`th element into two consecutive places.)
1398 - ptr::copy(p, p.offset(1), len - index);
1393 +if index < len {
1394 +// Shift everything over to make space. (Duplicating the
1395 +// `index`th element into two consecutive places.)
1396 + ptr::copy(p, p.offset(1), len - index);
1397 +} else if index == len {
1398 +// No elements need shifting.
1399 +} else {
1400 +assert_failed(index, len);
1401 +}
1399 1402 // Write it in, overwriting the first copy of the `index`th
1400 1403 // element.
1401 1404 ptr::write(p, element);