Skip to content

Commit

Permalink
Fix &mut invalidation in ptr::swap doctest
Browse files Browse the repository at this point in the history
Under Stacked Borrows with raw pointer tagging, the previous code was UB
because the code which creates the the second pointer borrows the array
through a tag in the borrow stacks below the Unique tag that our first
pointer is based on, thus invalidating the first pointer.

This is not definitely a bug and may never be real UB, but I desperately
want people to write code that conforms to SB with raw pointer tagging
so that I can write good diagnostics. The alternative aliasing models
aren't possible to diagnose well due to state space explosion.
Therefore, it would be super cool if the standard library nudged people
towards writing code that is valid with respect to SB with raw pointer
tagging.
  • Loading branch information
saethlin committed Apr 3, 2022
1 parent 15a242a commit f4a7ed4
Showing 1 changed file with 3 additions and 2 deletions.
5 changes: 3 additions & 2 deletions library/core/src/ptr/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -637,8 +637,9 @@ pub const fn slice_from_raw_parts_mut<T>(data: *mut T, len: usize) -> *mut [T] {
///
/// let mut array = [0, 1, 2, 3];
///
/// let x = array[0..].as_mut_ptr() as *mut [u32; 2]; // this is `array[0..2]`
/// let y = array[2..].as_mut_ptr() as *mut [u32; 2]; // this is `array[2..4]`
/// let (x, y) = array.split_at_mut(2);
/// let x = x.as_mut_ptr().cast::<[u32; 2]>(); // this is `array[0..2]`
/// let y = y.as_mut_ptr().cast::<[u32; 2]>(); // this is `array[2..4]`
///
/// unsafe {
/// ptr::swap(x, y);
Expand Down

0 comments on commit f4a7ed4

Please sign in to comment.