Skip to content

Commit f4a7ed4

Browse files
committed
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.
1 parent 15a242a commit f4a7ed4

File tree

1 file changed

+3
-2
lines changed

1 file changed

+3
-2
lines changed

library/core/src/ptr/mod.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -637,8 +637,9 @@ pub const fn slice_from_raw_parts_mut<T>(data: *mut T, len: usize) -> *mut [T] {
637637
///
638638
/// let mut array = [0, 1, 2, 3];
639639
///
640-
/// let x = array[0..].as_mut_ptr() as *mut [u32; 2]; // this is `array[0..2]`
641-
/// let y = array[2..].as_mut_ptr() as *mut [u32; 2]; // this is `array[2..4]`
640+
/// let (x, y) = array.split_at_mut(2);
641+
/// let x = x.as_mut_ptr().cast::<[u32; 2]>(); // this is `array[0..2]`
642+
/// let y = y.as_mut_ptr().cast::<[u32; 2]>(); // this is `array[2..4]`
642643
///
643644
/// unsafe {
644645
/// ptr::swap(x, y);

0 commit comments

Comments
 (0)