Skip to content

Commit

Permalink
Rollup merge of #90099 - SkiFire13:fix-vec-swap-remove, r=dtolnay
Browse files Browse the repository at this point in the history
Fix MIRI UB in `Vec::swap_remove`

Fixes #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
matthiaskrgr authored Oct 20, 2021
2 parents 36eba9f + 0aa68a8 commit 2c31c96
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 2c31c96

Please sign in to comment.