Skip to content

Commit 4a0647d

Browse files
authored
Rollup merge of #46483 - frewsxcv:frewsxcv-ptr-swap, r=BurntSushi
Document behavior of `ptr::swap` with overlapping regions of memory. Fixes #44479.
2 parents e5fd52b + f366227 commit 4a0647d

File tree

1 file changed

+40
-2
lines changed

1 file changed

+40
-2
lines changed

src/libcore/ptr.rs

+40-2
Original file line numberDiff line numberDiff line change
@@ -91,15 +91,53 @@ pub const fn null<T>() -> *const T { 0 as *const T }
9191
pub const fn null_mut<T>() -> *mut T { 0 as *mut T }
9292

9393
/// Swaps the values at two mutable locations of the same type, without
94-
/// deinitializing either. They may overlap, unlike `mem::swap` which is
95-
/// otherwise equivalent.
94+
/// deinitializing either.
95+
///
96+
/// The values pointed at by `x` and `y` may overlap, unlike `mem::swap` which
97+
/// is otherwise equivalent. If the values do overlap, then the overlapping
98+
/// region of memory from `x` will be used. This is demonstrated in the
99+
/// examples section below.
96100
///
97101
/// # Safety
98102
///
99103
/// This function copies the memory through the raw pointers passed to it
100104
/// as arguments.
101105
///
102106
/// Ensure that these pointers are valid before calling `swap`.
107+
///
108+
/// # Examples
109+
///
110+
/// Swapping two non-overlapping regions:
111+
///
112+
/// ```
113+
/// use std::ptr;
114+
///
115+
/// let mut array = [0, 1, 2, 3];
116+
///
117+
/// let x = array[0..].as_mut_ptr() as *mut [u32; 2];
118+
/// let y = array[2..].as_mut_ptr() as *mut [u32; 2];
119+
///
120+
/// unsafe {
121+
/// ptr::swap(x, y);
122+
/// assert_eq!([2, 3, 0, 1], array);
123+
/// }
124+
/// ```
125+
///
126+
/// Swapping two overlapping regions:
127+
///
128+
/// ```
129+
/// use std::ptr;
130+
///
131+
/// let mut array = [0, 1, 2, 3];
132+
///
133+
/// let x = array[0..].as_mut_ptr() as *mut [u32; 3];
134+
/// let y = array[1..].as_mut_ptr() as *mut [u32; 3];
135+
///
136+
/// unsafe {
137+
/// ptr::swap(x, y);
138+
/// assert_eq!([1, 0, 1, 2], array);
139+
/// }
140+
/// ```
103141
#[inline]
104142
#[stable(feature = "rust1", since = "1.0.0")]
105143
pub unsafe fn swap<T>(x: *mut T, y: *mut T) {

0 commit comments

Comments
 (0)