Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize Vec::insert for the case where index == len. #98755

Merged
merged 1 commit into from
Jul 3, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions library/alloc/src/vec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1379,9 +1379,6 @@ impl<T, A: Allocator> Vec<T, A> {
}

let len = self.len();
if index > len {
assert_failed(index, len);
}

// space for the new element
if len == self.buf.capacity() {
Expand All @@ -1393,9 +1390,15 @@ impl<T, A: Allocator> Vec<T, A> {
// The spot to put the new value
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This "infallible" comment is now a lie and needs extra justification.

{
let p = self.as_mut_ptr().add(index);
// Shift everything over to make space. (Duplicating the
// `index`th element into two consecutive places.)
ptr::copy(p, p.offset(1), len - index);
if index < len {
// Shift everything over to make space. (Duplicating the
// `index`th element into two consecutive places.)
ptr::copy(p, p.offset(1), len - index);
} else if index == len {
// No elements need shifting.
} else {
assert_failed(index, len);
}
// Write it in, overwriting the first copy of the `index`th
// element.
ptr::write(p, element);
Expand Down