<[T]>::reverse: Fix pointer provenance rules

This commit is contained in:
Giacomo Stevanato 2020-11-06 20:01:27 +01:00
parent dc06a36074
commit 23d82761f7

View File

@ -605,8 +605,9 @@ impl<T> [T] {
// many bytes away from the end of `self`. // many bytes away from the end of `self`.
// - Any initialized memory is valid `usize`. // - Any initialized memory is valid `usize`.
unsafe { unsafe {
let pa: *mut T = self.get_unchecked_mut(i); let ptr = self.as_mut_ptr();
let pb: *mut T = self.get_unchecked_mut(ln - i - chunk); let pa = ptr.add(i);
let pb = ptr.add(ln - i - chunk);
let va = ptr::read_unaligned(pa as *mut usize); let va = ptr::read_unaligned(pa as *mut usize);
let vb = ptr::read_unaligned(pb as *mut usize); let vb = ptr::read_unaligned(pb as *mut usize);
ptr::write_unaligned(pa as *mut usize, vb.swap_bytes()); ptr::write_unaligned(pa as *mut usize, vb.swap_bytes());
@ -635,8 +636,9 @@ impl<T> [T] {
// always respected, ensuring the `pb` pointer can be used // always respected, ensuring the `pb` pointer can be used
// safely. // safely.
unsafe { unsafe {
let pa: *mut T = self.get_unchecked_mut(i); let ptr = self.as_mut_ptr();
let pb: *mut T = self.get_unchecked_mut(ln - i - chunk); let pa = ptr.add(i);
let pb = ptr.add(ln - i - chunk);
let va = ptr::read_unaligned(pa as *mut u32); let va = ptr::read_unaligned(pa as *mut u32);
let vb = ptr::read_unaligned(pb as *mut u32); let vb = ptr::read_unaligned(pb as *mut u32);
ptr::write_unaligned(pa as *mut u32, vb.rotate_left(16)); ptr::write_unaligned(pa as *mut u32, vb.rotate_left(16));
@ -654,8 +656,9 @@ impl<T> [T] {
// aligned, and can be read from and written to. // aligned, and can be read from and written to.
unsafe { unsafe {
// Unsafe swap to avoid the bounds check in safe swap. // Unsafe swap to avoid the bounds check in safe swap.
let pa: *mut T = self.get_unchecked_mut(i); let ptr = self.as_mut_ptr();
let pb: *mut T = self.get_unchecked_mut(ln - i - 1); let pa = ptr.add(i);
let pb = ptr.add(ln - i - 1);
ptr::swap(pa, pb); ptr::swap(pa, pb);
} }
i += 1; i += 1;