Skip to content

Commit

Permalink
Auto merge of #94342 - ibraheemdev:swap-regression, r=Dylan-DPC
Browse files Browse the repository at this point in the history
Revert implementation of `slice::swap`

Due to the perf regressions noticed here, possible due to inlining? #88540 (comment)

r? `@kennytm`
  • Loading branch information
bors committed Feb 25, 2022
2 parents d3ad51b + 072d35d commit d973b35
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions library/core/src/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -587,11 +587,17 @@ impl<T> [T] {
#[inline]
#[track_caller]
pub const fn swap(&mut self, a: usize, b: usize) {
let _ = &self[a];
let _ = &self[b];

// SAFETY: we just checked that both `a` and `b` are in bounds
unsafe { self.swap_unchecked(a, b) }
// FIXME: use swap_unchecked here (https://github.com/rust-lang/rust/pull/88540#issuecomment-944344343)
// Can't take two mutable loans from one vector, so instead use raw pointers.
let pa = ptr::addr_of_mut!(self[a]);
let pb = ptr::addr_of_mut!(self[b]);
// SAFETY: `pa` and `pb` have been created from safe mutable references and refer
// to elements in the slice and therefore are guaranteed to be valid and aligned.
// Note that accessing the elements behind `a` and `b` is checked and will
// panic when out of bounds.
unsafe {
ptr::swap(pa, pb);
}
}

/// Swaps two elements in the slice, without doing bounds checking.
Expand Down

0 comments on commit d973b35

Please sign in to comment.