Skip to content

Commit 3680ecd

Browse files
authored
Rollup merge of #90099 - SkiFire13:fix-vec-swap-remove, r=dtolnay
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.
2 parents 68a5680 + 0aa68a8 commit 3680ecd

File tree

1 file changed

+4
-3
lines changed

1 file changed

+4
-3
lines changed

library/alloc/src/vec/mod.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -1305,10 +1305,11 @@ impl<T, A: Allocator> Vec<T, A> {
13051305
// We replace self[index] with the last element. Note that if the
13061306
// bounds check above succeeds there must be a last element (which
13071307
// can be self[index] itself).
1308-
let last = ptr::read(self.as_ptr().add(len - 1));
1309-
let hole = self.as_mut_ptr().add(index);
1308+
let value = ptr::read(self.as_ptr().add(index));
1309+
let base_ptr = self.as_mut_ptr();
1310+
ptr::copy(base_ptr.add(len - 1), base_ptr.add(index), 1);
13101311
self.set_len(len - 1);
1311-
ptr::replace(hole, last)
1312+
value
13121313
}
13131314
}
13141315

0 commit comments

Comments
 (0)