diff options
| author | Corey Farwell <coreyf@rwell.org> | 2017-12-06 09:35:38 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2017-12-06 09:35:38 -0500 |
| commit | 4a0647d1f99080348e6b5f5672ee1e2a1888b29b (patch) | |
| tree | 4b268b5b2f564492459b5f86370ad28a544026be | |
| parent | e5fd52bed2f51eb336fd95297ec12dc74f24fcae (diff) | |
| parent | f3662275e45271b6f0f1d30d572a21e19f3261a1 (diff) | |
| download | rust-4a0647d1f99080348e6b5f5672ee1e2a1888b29b.tar.gz rust-4a0647d1f99080348e6b5f5672ee1e2a1888b29b.zip | |
Rollup merge of #46483 - frewsxcv:frewsxcv-ptr-swap, r=BurntSushi
Document behavior of `ptr::swap` with overlapping regions of memory. Fixes https://github.com/rust-lang/rust/issues/44479.
| -rw-r--r-- | src/libcore/ptr.rs | 42 |
1 files changed, 40 insertions, 2 deletions
diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs index 5e70c8283f4..20f054f5a77 100644 --- a/src/libcore/ptr.rs +++ b/src/libcore/ptr.rs @@ -91,8 +91,12 @@ pub const fn null<T>() -> *const T { 0 as *const T } pub const fn null_mut<T>() -> *mut T { 0 as *mut T } /// Swaps the values at two mutable locations of the same type, without -/// deinitializing either. They may overlap, unlike `mem::swap` which is -/// otherwise equivalent. +/// deinitializing either. +/// +/// The values pointed at by `x` and `y` may overlap, unlike `mem::swap` which +/// is otherwise equivalent. If the values do overlap, then the overlapping +/// region of memory from `x` will be used. This is demonstrated in the +/// examples section below. /// /// # Safety /// @@ -100,6 +104,40 @@ pub const fn null_mut<T>() -> *mut T { 0 as *mut T } /// as arguments. /// /// Ensure that these pointers are valid before calling `swap`. +/// +/// # Examples +/// +/// Swapping two non-overlapping regions: +/// +/// ``` +/// use std::ptr; +/// +/// let mut array = [0, 1, 2, 3]; +/// +/// let x = array[0..].as_mut_ptr() as *mut [u32; 2]; +/// let y = array[2..].as_mut_ptr() as *mut [u32; 2]; +/// +/// unsafe { +/// ptr::swap(x, y); +/// assert_eq!([2, 3, 0, 1], array); +/// } +/// ``` +/// +/// Swapping two overlapping regions: +/// +/// ``` +/// use std::ptr; +/// +/// let mut array = [0, 1, 2, 3]; +/// +/// let x = array[0..].as_mut_ptr() as *mut [u32; 3]; +/// let y = array[1..].as_mut_ptr() as *mut [u32; 3]; +/// +/// unsafe { +/// ptr::swap(x, y); +/// assert_eq!([1, 0, 1, 2], array); +/// } +/// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn swap<T>(x: *mut T, y: *mut T) { |
