From f4a7ed433834e8ea2775097a9bf433880d6e34a3 Mon Sep 17 00:00:00 2001 From: Ben Kimock Date: Sun, 3 Apr 2022 13:23:27 -0400 Subject: [PATCH] Fix &mut invalidation in ptr::swap doctest 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. --- library/core/src/ptr/mod.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index e2a19c1b5818e..91e2bd7953f73 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -637,8 +637,9 @@ pub const fn slice_from_raw_parts_mut(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);