core/slice/rotate.rs
1use crate::mem::{MaybeUninit, SizedTypeProperties};
2use crate::ptr;
3
4type BufType = [usize; 32];
5
6/// Rotates the range `[mid-left, mid+right)` such that the element at `mid` becomes the first
7/// element. Equivalently, rotates the range `left` elements to the left or `right` elements to the
8/// right.
9///
10/// # Safety
11///
12/// The specified range must be valid for reading and writing.
13#[inline]
14#[ferrocene::prevalidated]
15pub(super) const unsafe fn ptr_rotate<T>(left: usize, mid: *mut T, right: usize) {
16 if T::IS_ZST {
17 return;
18 }
19 // abort early if the rotate is a no-op
20 if (left == 0) || (right == 0) {
21 return;
22 }
23
24 // For huge slices, GCD has poor locality because it jumps by large element-sized
25 // strides and carries a large temporary. Since rotation only permutes raw storage,
26 // a large element whose size/alignment permits it can instead be viewed as multiple
27 // `MaybeUninit<usize>` words. This makes dispatch choose the contiguous swap algorithm,
28 // which has much better cache/TLB locality.
29 if !cfg!(feature = "optimize_for_size")
30 && size_of::<T>() > size_of::<[usize; 4]>()
31 && size_of::<T>() % size_of::<usize>() == 0
32 && align_of::<T>() >= align_of::<usize>()
33 {
34 let ratio = size_of::<T>() / size_of::<usize>();
35
36 // SAFETY: this covers exactly the same bytes as `[mid-left, mid+right)` because
37 // `ratio * size_of::<usize>() == size_of::<T>()`. The check above guarantees
38 // `mid` is aligned for `usize`, and preserving the total byte length introduces
39 // no new overflow.
40 unsafe { ptr_rotate_dispatch(left * ratio, mid as *mut MaybeUninit<usize>, right * ratio) }
41 } else {
42 // SAFETY: guaranteed by the caller
43 unsafe { ptr_rotate_dispatch(left, mid, right) }
44 }
45}
46
47/// Chooses between the three rotation algorithms. See the algorithm docs below.
48///
49/// # Safety
50///
51/// The specified range must be valid for reading and writing.
52#[inline]
53#[ferrocene::prevalidated]
54const unsafe fn ptr_rotate_dispatch<T>(left: usize, mid: *mut T, right: usize) {
55 // `T` is not a zero-sized type, so it's okay to divide by its size.
56 if !cfg!(feature = "optimize_for_size")
57 // FIXME(const-hack): Use cmp::min when available in const
58 && const_min(left, right) <= size_of::<BufType>() / size_of::<T>()
59 {
60 // SAFETY: guaranteed by the caller
61 unsafe { ptr_rotate_memmove(left, mid, right) };
62 } else if !cfg!(feature = "optimize_for_size")
63 && ((left + right < 24) || (size_of::<T>() > size_of::<[usize; 4]>()))
64 {
65 // SAFETY: guaranteed by the caller
66 unsafe { ptr_rotate_gcd(left, mid, right) }
67 } else {
68 // SAFETY: guaranteed by the caller
69 unsafe { ptr_rotate_swap(left, mid, right) }
70 }
71}
72
73/// Algorithm 1 is used if `min(left, right)` is small enough to fit onto a stack buffer. The
74/// `min(left, right)` elements are copied onto the buffer, `memmove` is applied to the others, and
75/// the ones on the buffer are moved back into the hole on the opposite side of where they
76/// originated.
77///
78/// # Safety
79///
80/// The specified range must be valid for reading and writing.
81#[inline]
82#[ferrocene::prevalidated]
83const unsafe fn ptr_rotate_memmove<T>(left: usize, mid: *mut T, right: usize) {
84 // The `[T; 0]` here is to ensure this is appropriately aligned for T
85 let mut rawarray = MaybeUninit::<(BufType, [T; 0])>::uninit();
86 let buf = rawarray.as_mut_ptr() as *mut T;
87 // SAFETY: `mid-left <= mid-left+right < mid+right`
88 let dim = unsafe { mid.sub(left).add(right) };
89 if left <= right {
90 // SAFETY:
91 //
92 // 1) The `if` condition about the sizes ensures `[mid-left; left]` will fit in
93 // `buf` without overflow and `buf` was created just above and so cannot be
94 // overlapped with any value of `[mid-left; left]`
95 // 2) [mid-left, mid+right) are all valid for reading and writing and we don't care
96 // about overlaps here.
97 // 3) The `if` condition about `left <= right` ensures writing `left` elements to
98 // `dim = mid-left+right` is valid because:
99 // - `buf` is valid and `left` elements were written in it in 1)
100 // - `dim+left = mid-left+right+left = mid+right` and we write `[dim, dim+left)`
101 unsafe {
102 // 1)
103 ptr::copy_nonoverlapping(mid.sub(left), buf, left);
104 // 2)
105 ptr::copy(mid, mid.sub(left), right);
106 // 3)
107 ptr::copy_nonoverlapping(buf, dim, left);
108 }
109 } else {
110 // SAFETY: same reasoning as above but with `left` and `right` reversed
111 unsafe {
112 ptr::copy_nonoverlapping(mid, buf, right);
113 ptr::copy(mid.sub(left), dim, left);
114 ptr::copy_nonoverlapping(buf, mid.sub(left), right);
115 }
116 }
117}
118
119/// Algorithm 2 is used for small values of `left + right` or for large `T`. The elements
120/// are moved into their final positions one at a time starting at `mid - left` and advancing by
121/// `right` steps modulo `left + right`, such that only one temporary is needed. Eventually, we
122/// arrive back at `mid - left`. However, if `gcd(left + right, right)` is not 1, the above steps
123/// skipped over elements. For example:
124/// ```text
125/// left = 10, right = 6
126/// the `^` indicates an element in its final place
127/// 6 7 8 9 10 11 12 13 14 15 . 0 1 2 3 4 5
128/// after using one step of the above algorithm (The X will be overwritten at the end of the round,
129/// and 12 is stored in a temporary):
130/// X 7 8 9 10 11 6 13 14 15 . 0 1 2 3 4 5
131/// ^
132/// after using another step (now 2 is in the temporary):
133/// X 7 8 9 10 11 6 13 14 15 . 0 1 12 3 4 5
134/// ^ ^
135/// after the third step (the steps wrap around, and 8 is in the temporary):
136/// X 7 2 9 10 11 6 13 14 15 . 0 1 12 3 4 5
137/// ^ ^ ^
138/// after 7 more steps, the round ends with the temporary 0 getting put in the X:
139/// 0 7 2 9 4 11 6 13 8 15 . 10 1 12 3 14 5
140/// ^ ^ ^ ^ ^ ^ ^ ^
141/// ```
142/// Fortunately, the number of skipped over elements between finalized elements is always equal, so
143/// we can just offset our starting position and do more rounds (the total number of rounds is the
144/// `gcd(left + right, right)` value). The end result is that all elements are finalized once and
145/// only once.
146///
147/// Algorithm 2 can be vectorized by chunking and performing many rounds at once, but there are too
148/// few rounds on average until `left + right` is enormous, and the worst case of a single
149/// round is always there.
150///
151/// # Safety
152///
153/// The specified range must be valid for reading and writing.
154#[inline]
155#[ferrocene::prevalidated]
156const unsafe fn ptr_rotate_gcd<T>(left: usize, mid: *mut T, right: usize) {
157 // Algorithm 2
158 // Microbenchmarks indicate that the average performance for random shifts is better all
159 // the way until about `left + right == 32`, but the worst case performance breaks even
160 // around 16. 24 was chosen as middle ground. If the size of `T` is larger than 4
161 // `usize`s, this algorithm also outperforms other algorithms.
162 // SAFETY: callers must ensure `mid - left` is valid for reading and writing.
163 let x = unsafe { mid.sub(left) };
164 // beginning of first round
165 // SAFETY: see previous comment.
166 let mut tmp: T = unsafe { x.read() };
167 let mut i = right;
168 // `gcd` can be found before hand by calculating `gcd(left + right, right)`,
169 // but it is faster to do one loop which calculates the gcd as a side effect, then
170 // doing the rest of the chunk
171 let mut gcd = right;
172 // benchmarks reveal that it is faster to swap temporaries all the way through instead
173 // of reading one temporary once, copying backwards, and then writing that temporary at
174 // the very end. This is possibly due to the fact that swapping or replacing temporaries
175 // uses only one memory address in the loop instead of needing to manage two.
176 loop {
177 // [long-safety-expl]
178 // SAFETY: callers must ensure `[left, left+mid+right)` are all valid for reading and
179 // writing.
180 //
181 // - `i` start with `right` so `mid-left <= x+i = x+right = mid-left+right < mid+right`
182 // - `i <= left+right-1` is always true
183 // - if `i < left`, `right` is added so `i < left+right` and on the next
184 // iteration `left` is removed from `i` so it doesn't go further
185 // - if `i >= left`, `left` is removed immediately and so it doesn't go further.
186 // - overflows cannot happen for `i` since the function's safety contract ask for
187 // `mid+right-1 = x+left+right` to be valid for writing
188 // - underflows cannot happen because `i` must be bigger or equal to `left` for
189 // a subtraction of `left` to happen.
190 //
191 // So `x+i` is valid for reading and writing if the caller respected the contract
192 tmp = unsafe { x.add(i).replace(tmp) };
193 // instead of incrementing `i` and then checking if it is outside the bounds, we
194 // check if `i` will go outside the bounds on the next increment. This prevents
195 // any wrapping of pointers or `usize`.
196 if i >= left {
197 i -= left;
198 if i == 0 {
199 // end of first round
200 // SAFETY: tmp has been read from a valid source and x is valid for writing
201 // according to the caller.
202 unsafe { x.write(tmp) };
203 break;
204 }
205 // this conditional must be here if `left + right >= 15`
206 if i < gcd {
207 gcd = i;
208 }
209 } else {
210 i += right;
211 }
212 }
213 // finish the chunk with more rounds
214 // FIXME(const-hack): Use `for start in 1..gcd` when available in const
215 let mut start = 1;
216 while start < gcd {
217 // SAFETY: `gcd` is at most equal to `right` so all values in `1..gcd` are valid for
218 // reading and writing as per the function's safety contract, see [long-safety-expl]
219 // above
220 tmp = unsafe { x.add(start).read() };
221 // [safety-expl-addition]
222 //
223 // Here `start < gcd` so `start < right` so `i < right+right`: `right` being the
224 // greatest common divisor of `(left+right, right)` means that `left = right` so
225 // `i < left+right` so `x+i = mid-left+i` is always valid for reading and writing
226 // according to the function's safety contract.
227 i = start + right;
228 loop {
229 // SAFETY: see [long-safety-expl] and [safety-expl-addition]
230 tmp = unsafe { x.add(i).replace(tmp) };
231 if i >= left {
232 i -= left;
233 if i == start {
234 // SAFETY: see [long-safety-expl] and [safety-expl-addition]
235 unsafe { x.add(start).write(tmp) };
236 break;
237 }
238 } else {
239 i += right;
240 }
241 }
242
243 start += 1;
244 }
245}
246
247/// Algorithm 3 utilizes repeated swapping of `min(left, right)` elements.
248///
249/// ///
250/// ```text
251/// left = 11, right = 4
252/// [4 5 6 7 8 9 10 11 12 13 14 . 0 1 2 3]
253/// ^ ^ ^ ^ ^ ^ ^ ^ swapping the right most elements with elements to the left
254/// [4 5 6 7 8 9 10 . 0 1 2 3] 11 12 13 14
255/// ^ ^ ^ ^ ^ ^ ^ ^ swapping these
256/// [4 5 6 . 0 1 2 3] 7 8 9 10 11 12 13 14
257/// we cannot swap any more, but a smaller rotation problem is left to solve
258/// ```
259/// when `left < right` the swapping happens from the left instead.
260///
261/// # Safety
262///
263/// The specified range must be valid for reading and writing.
264#[inline]
265#[ferrocene::prevalidated]
266const unsafe fn ptr_rotate_swap<T>(mut left: usize, mut mid: *mut T, mut right: usize) {
267 loop {
268 if left >= right {
269 // Algorithm 3
270 // There is an alternate way of swapping that involves finding where the last swap
271 // of this algorithm would be, and swapping using that last chunk instead of swapping
272 // adjacent chunks like this algorithm is doing, but this way is still faster.
273 loop {
274 // SAFETY:
275 // `left >= right` so `[mid-right, mid+right)` is valid for reading and writing
276 // Subtracting `right` from `mid` each turn is counterbalanced by the addition and
277 // check after it.
278 unsafe {
279 ptr::swap_nonoverlapping(mid.sub(right), mid, right);
280 mid = mid.sub(right);
281 }
282 left -= right;
283 if left < right {
284 break;
285 }
286 }
287 } else {
288 // Algorithm 3, `left < right`
289 loop {
290 // SAFETY: `[mid-left, mid+left)` is valid for reading and writing because
291 // `left < right` so `mid+left < mid+right`.
292 // Adding `left` to `mid` each turn is counterbalanced by the subtraction and check
293 // after it.
294 unsafe {
295 ptr::swap_nonoverlapping(mid.sub(left), mid, left);
296 mid = mid.add(left);
297 }
298 right -= left;
299 if right < left {
300 break;
301 }
302 }
303 }
304 if (right == 0) || (left == 0) {
305 return;
306 }
307
308 // Switch to the buffered algorithm once the smaller side fits in the stack
309 // buffer. The swap algorithm is efficient for reducing large blocks, but its
310 // tail can degenerate into many small swaps when one side becomes tiny.
311 if !cfg!(feature = "optimize_for_size")
312 && const_min(left, right) <= size_of::<BufType>() / size_of::<T>()
313 {
314 // SAFETY: the remaining range `[mid-left, mid+right)` is a subrange of the
315 // original input, so it is valid for reading and writing.
316 unsafe { ptr_rotate_memmove(left, mid, right) };
317 return;
318 }
319 }
320}
321
322// FIXME(const-hack): Use cmp::min when available in const
323#[ferrocene::prevalidated]
324const fn const_min(left: usize, right: usize) -> usize {
325 if right < left { right } else { left }
326}