Skip to content

Commit

Permalink
Rollup merge of rust-lang#90099 - SkiFire13:fix-vec-swap-remove, r=dt…
Browse files Browse the repository at this point in the history
…olnay

Fix MIRI UB in `Vec::swap_remove`

Fixes rust-lang#90055

I find it weird that `Vec::swap_remove` read the last element to the stack just to immediately put it back in the `Vec` in place of the one at index `index`. It seems much more natural to me to just read the element at position `index` and then move the last element in its place. I guess this might also slightly improve codegen.
  • Loading branch information
GuillaumeGomez committed Oct 20, 2021
2 parents 77a5781 + 0aa68a8 commit 0794293
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions library/alloc/src/vec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1305,10 +1305,11 @@ impl<T, A: Allocator> Vec<T, A> {
// We replace self[index] with the last element. Note that if the
// bounds check above succeeds there must be a last element (which
// can be self[index] itself).
let last = ptr::read(self.as_ptr().add(len - 1));
let hole = self.as_mut_ptr().add(index);
let value = ptr::read(self.as_ptr().add(index));
let base_ptr = self.as_mut_ptr();
ptr::copy(base_ptr.add(len - 1), base_ptr.add(index), 1);
self.set_len(len - 1);
ptr::replace(hole, last)
value
}
}

Expand Down

0 comments on commit 0794293

Please sign in to comment.