@@ -91,15 +91,53 @@ pub const fn null<T>() -> *const T { 0 as *const T }
91
91
pub const fn null_mut < T > ( ) -> * mut T { 0 as * mut T }
92
92
93
93
/// 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.
96
100
///
97
101
/// # Safety
98
102
///
99
103
/// This function copies the memory through the raw pointers passed to it
100
104
/// as arguments.
101
105
///
102
106
/// 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
+ /// ```
103
141
#[ inline]
104
142
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
105
143
pub unsafe fn swap < T > ( x : * mut T , y : * mut T ) {
0 commit comments