Skip to content

Commit 558cd1e

Browse files
committed
Auto merge of #41670 - scottmcm:slice-rotate, r=alexcrichton
Add an in-place rotate method for slices to libcore A helpful primitive for moving chunks of data around inside a slice. For example, if you have a range selected and are drag-and-dropping it somewhere else (Example from [Sean Parent's talk](https://youtu.be/qH6sSOr-yk8?t=560)). (If this should be an RFC instead of a PR, please let me know.) Edit: changed example
2 parents 668e698 + 094d61f commit 558cd1e

File tree

12 files changed

+285
-0
lines changed

12 files changed

+285
-0
lines changed

src/doc/unstable-book/src/SUMMARY.md

+1
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,7 @@
190190
- [sip_hash_13](library-features/sip-hash-13.md)
191191
- [slice_concat_ext](library-features/slice-concat-ext.md)
192192
- [slice_get_slice](library-features/slice-get-slice.md)
193+
- [slice_rotate](library-features/slice-rotate.md)
193194
- [slice_rsplit](library-features/slice-rsplit.md)
194195
- [sort_internals](library-features/sort-internals.md)
195196
- [sort_unstable](library-features/sort-unstable.md)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# `slice_rotate`
2+
3+
The tracking issue for this feature is: [#41891]
4+
5+
[#41891]: https://github.com/rust-lang/rust/issues/41891
6+
7+
------------------------

src/libcollections/benches/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
#![feature(i128_type)]
1414
#![feature(rand)]
1515
#![feature(repr_simd)]
16+
#![feature(slice_rotate)]
1617
#![feature(sort_unstable)]
1718
#![feature(test)]
1819

src/libcollections/benches/slice.rs

+41
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,11 @@ fn gen_random(len: usize) -> Vec<u64> {
195195
rng.gen_iter::<u64>().take(len).collect()
196196
}
197197

198+
fn gen_random_bytes(len: usize) -> Vec<u8> {
199+
let mut rng = thread_rng();
200+
rng.gen_iter::<u8>().take(len).collect()
201+
}
202+
198203
fn gen_mostly_ascending(len: usize) -> Vec<u64> {
199204
let mut rng = thread_rng();
200205
let mut v = gen_ascending(len);
@@ -315,3 +320,39 @@ reverse!(reverse_u64, u64, |x| x as u64);
315320
reverse!(reverse_u128, u128, |x| x as u128);
316321
#[repr(simd)] struct F64x4(f64, f64, f64, f64);
317322
reverse!(reverse_simd_f64x4, F64x4, |x| { let x = x as f64; F64x4(x,x,x,x) });
323+
324+
macro_rules! rotate {
325+
($name:ident, $gen:expr, $len:expr, $mid:expr) => {
326+
#[bench]
327+
fn $name(b: &mut Bencher) {
328+
let size = mem::size_of_val(&$gen(1)[0]);
329+
let mut v = $gen($len * 8 / size);
330+
b.iter(|| black_box(&mut v).rotate(($mid*8+size-1)/size));
331+
b.bytes = (v.len() * size) as u64;
332+
}
333+
}
334+
}
335+
336+
rotate!(rotate_tiny_by1, gen_random, 16, 1);
337+
rotate!(rotate_tiny_half, gen_random, 16, 16/2);
338+
rotate!(rotate_tiny_half_plus_one, gen_random, 16, 16/2+1);
339+
340+
rotate!(rotate_medium_by1, gen_random, 9158, 1);
341+
rotate!(rotate_medium_by727_u64, gen_random, 9158, 727);
342+
rotate!(rotate_medium_by727_bytes, gen_random_bytes, 9158, 727);
343+
rotate!(rotate_medium_by727_strings, gen_strings, 9158, 727);
344+
rotate!(rotate_medium_half, gen_random, 9158, 9158/2);
345+
rotate!(rotate_medium_half_plus_one, gen_random, 9158, 9158/2+1);
346+
347+
// Intended to use more RAM than the machine has cache
348+
rotate!(rotate_huge_by1, gen_random, 5*1024*1024, 1);
349+
rotate!(rotate_huge_by9199_u64, gen_random, 5*1024*1024, 9199);
350+
rotate!(rotate_huge_by9199_bytes, gen_random_bytes, 5*1024*1024, 9199);
351+
rotate!(rotate_huge_by9199_strings, gen_strings, 5*1024*1024, 9199);
352+
rotate!(rotate_huge_by9199_big, gen_big_random, 5*1024*1024, 9199);
353+
rotate!(rotate_huge_by1234577_u64, gen_random, 5*1024*1024, 1234577);
354+
rotate!(rotate_huge_by1234577_bytes, gen_random_bytes, 5*1024*1024, 1234577);
355+
rotate!(rotate_huge_by1234577_strings, gen_strings, 5*1024*1024, 1234577);
356+
rotate!(rotate_huge_by1234577_big, gen_big_random, 5*1024*1024, 1234577);
357+
rotate!(rotate_huge_half, gen_random, 5*1024*1024, 5*1024*1024/2);
358+
rotate!(rotate_huge_half_plus_one, gen_random, 5*1024*1024, 5*1024*1024/2+1);

src/libcollections/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@
5555
#![feature(shared)]
5656
#![feature(slice_get_slice)]
5757
#![feature(slice_patterns)]
58+
#![cfg_attr(not(test), feature(slice_rotate))]
5859
#![feature(slice_rsplit)]
5960
#![cfg_attr(not(test), feature(sort_unstable))]
6061
#![feature(specialization)]

src/libcollections/slice.rs

+55
Original file line numberDiff line numberDiff line change
@@ -1347,6 +1347,61 @@ impl<T> [T] {
13471347
core_slice::SliceExt::sort_unstable_by_key(self, f);
13481348
}
13491349

1350+
/// Permutes the slice in-place such that `self[mid..]` moves to the
1351+
/// beginning of the slice while `self[..mid]` moves to the end of the
1352+
/// slice. Equivalently, rotates the slice `mid` places to the left
1353+
/// or `k = self.len() - mid` places to the right.
1354+
///
1355+
/// This is a "k-rotation", a permutation in which item `i` moves to
1356+
/// position `i + k`, modulo the length of the slice. See _Elements
1357+
/// of Programming_ [§10.4][eop].
1358+
///
1359+
/// Rotation by `mid` and rotation by `k` are inverse operations.
1360+
///
1361+
/// [eop]: https://books.google.com/books?id=CO9ULZGINlsC&pg=PA178&q=k-rotation
1362+
///
1363+
/// # Panics
1364+
///
1365+
/// This function will panic if `mid` is greater than the length of the
1366+
/// slice. (Note that `mid == self.len()` does _not_ panic; it's a nop
1367+
/// rotation with `k == 0`, the inverse of a rotation with `mid == 0`.)
1368+
///
1369+
/// # Complexity
1370+
///
1371+
/// Takes linear (in `self.len()`) time.
1372+
///
1373+
/// # Examples
1374+
///
1375+
/// ```
1376+
/// #![feature(slice_rotate)]
1377+
///
1378+
/// let mut a = [1, 2, 3, 4, 5, 6, 7];
1379+
/// let mid = 2;
1380+
/// a.rotate(mid);
1381+
/// assert_eq!(&a, &[3, 4, 5, 6, 7, 1, 2]);
1382+
/// let k = a.len() - mid;
1383+
/// a.rotate(k);
1384+
/// assert_eq!(&a, &[1, 2, 3, 4, 5, 6, 7]);
1385+
///
1386+
/// use std::ops::Range;
1387+
/// fn slide<T>(slice: &mut [T], range: Range<usize>, to: usize) {
1388+
/// if to < range.start {
1389+
/// slice[to..range.end].rotate(range.start-to);
1390+
/// } else if to > range.end {
1391+
/// slice[range.start..to].rotate(range.end-range.start);
1392+
/// }
1393+
/// }
1394+
/// let mut v: Vec<_> = (0..10).collect();
1395+
/// slide(&mut v, 1..4, 7);
1396+
/// assert_eq!(&v, &[0, 4, 5, 6, 1, 2, 3, 7, 8, 9]);
1397+
/// slide(&mut v, 6..8, 1);
1398+
/// assert_eq!(&v, &[0, 3, 7, 4, 5, 6, 1, 2, 8, 9]);
1399+
/// ```
1400+
#[unstable(feature = "slice_rotate", issue = "41891")]
1401+
pub fn rotate(&mut self, mid: usize) {
1402+
core_slice::SliceExt::rotate(self, mid);
1403+
}
1404+
13501405
/// Copies the elements from `src` into `self`.
13511406
///
13521407
/// The length of `src` must be the same as `self`.

src/libcollections/tests/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
#![feature(pattern)]
2020
#![feature(placement_in_syntax)]
2121
#![feature(rand)]
22+
#![feature(slice_rotate)]
2223
#![feature(splice)]
2324
#![feature(step_by)]
2425
#![feature(str_escape)]

src/libcollections/tests/slice.rs

+35
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,41 @@ fn test_sort_stability() {
466466
}
467467
}
468468

469+
#[test]
470+
fn test_rotate() {
471+
let expected: Vec<_> = (0..13).collect();
472+
let mut v = Vec::new();
473+
474+
// no-ops
475+
v.clone_from(&expected);
476+
v.rotate(0);
477+
assert_eq!(v, expected);
478+
v.rotate(expected.len());
479+
assert_eq!(v, expected);
480+
let mut zst_array = [(), (), ()];
481+
zst_array.rotate(2);
482+
483+
// happy path
484+
v = (5..13).chain(0..5).collect();
485+
v.rotate(8);
486+
assert_eq!(v, expected);
487+
488+
let expected: Vec<_> = (0..1000).collect();
489+
490+
// small rotations in large slice, uses ptr::copy
491+
v = (2..1000).chain(0..2).collect();
492+
v.rotate(998);
493+
assert_eq!(v, expected);
494+
v = (998..1000).chain(0..998).collect();
495+
v.rotate(2);
496+
assert_eq!(v, expected);
497+
498+
// non-small prime rotation, has a few rounds of swapping
499+
v = (389..1000).chain(0..389).collect();
500+
v.rotate(1000-389);
501+
assert_eq!(v, expected);
502+
}
503+
469504
#[test]
470505
fn test_concat() {
471506
let v: [Vec<i32>; 0] = [];

src/libcore/slice/mod.rs

+14
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ use mem;
5151
use marker::{Copy, Send, Sync, Sized, self};
5252
use iter_private::TrustedRandomAccess;
5353

54+
mod rotate;
5455
mod sort;
5556

5657
#[repr(C)]
@@ -202,6 +203,9 @@ pub trait SliceExt {
202203
#[stable(feature = "core", since = "1.6.0")]
203204
fn ends_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
204205

206+
#[unstable(feature = "slice_rotate", issue = "41891")]
207+
fn rotate(&mut self, mid: usize);
208+
205209
#[stable(feature = "clone_from_slice", since = "1.7.0")]
206210
fn clone_from_slice(&mut self, src: &[Self::Item]) where Self::Item: Clone;
207211

@@ -635,6 +639,16 @@ impl<T> SliceExt for [T] {
635639
self.binary_search_by(|p| p.borrow().cmp(x))
636640
}
637641

642+
fn rotate(&mut self, mid: usize) {
643+
assert!(mid <= self.len());
644+
let k = self.len() - mid;
645+
646+
unsafe {
647+
let p = self.as_mut_ptr();
648+
rotate::ptr_rotate(mid, p.offset(mid as isize), k);
649+
}
650+
}
651+
638652
#[inline]
639653
fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
640654
assert!(self.len() == src.len(),

src/libcore/slice/rotate.rs

+112
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
// Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
use cmp;
12+
use mem;
13+
use ptr;
14+
15+
/// Rotation is much faster if it has access to a little bit of memory. This
16+
/// union provides a RawVec-like interface, but to a fixed-size stack buffer.
17+
#[allow(unions_with_drop_fields)]
18+
union RawArray<T> {
19+
/// Ensure this is appropriately aligned for T, and is big
20+
/// enough for two elements even if T is enormous.
21+
typed: [T; 2],
22+
/// For normally-sized types, especially things like u8, having more
23+
/// than 2 in the buffer is necessary for usefulness, so pad it out
24+
/// enough to be helpful, but not so big as to risk overflow.
25+
_extra: [usize; 32],
26+
}
27+
28+
impl<T> RawArray<T> {
29+
fn new() -> Self {
30+
unsafe { mem::uninitialized() }
31+
}
32+
fn ptr(&self) -> *mut T {
33+
unsafe { &self.typed as *const T as *mut T }
34+
}
35+
fn cap() -> usize {
36+
if mem::size_of::<T>() == 0 {
37+
usize::max_value()
38+
} else {
39+
mem::size_of::<Self>() / mem::size_of::<T>()
40+
}
41+
}
42+
}
43+
44+
/// Rotates the range `[mid-left, mid+right)` such that the element at `mid`
45+
/// becomes the first element. Equivalently, rotates the range `left`
46+
/// elements to the left or `right` elements to the right.
47+
///
48+
/// # Safety
49+
///
50+
/// The specified range must be valid for reading and writing.
51+
/// The type `T` must have non-zero size.
52+
///
53+
/// # Algorithm
54+
///
55+
/// For longer rotations, swap the left-most `delta = min(left, right)`
56+
/// elements with the right-most `delta` elements. LLVM vectorizes this,
57+
/// which is profitable as we only reach this step for a "large enough"
58+
/// rotation. Doing this puts `delta` elements on the larger side into the
59+
/// correct position, leaving a smaller rotate problem. Demonstration:
60+
///
61+
/// ```text
62+
/// [ 6 7 8 9 10 11 12 13 . 1 2 3 4 5 ]
63+
/// 1 2 3 4 5 [ 11 12 13 . 6 7 8 9 10 ]
64+
/// 1 2 3 4 5 [ 8 9 10 . 6 7 ] 11 12 13
65+
/// 1 2 3 4 5 6 7 [ 10 . 8 9 ] 11 12 13
66+
/// 1 2 3 4 5 6 7 [ 9 . 8 ] 10 11 12 13
67+
/// 1 2 3 4 5 6 7 8 [ . ] 9 10 11 12 13
68+
/// ```
69+
///
70+
/// Once the rotation is small enough, copy some elements into a stack
71+
/// buffer, `memmove` the others, and move the ones back from the buffer.
72+
pub unsafe fn ptr_rotate<T>(mut left: usize, mid: *mut T, mut right: usize) {
73+
loop {
74+
let delta = cmp::min(left, right);
75+
if delta <= RawArray::<T>::cap() {
76+
break;
77+
}
78+
79+
ptr_swap_n(
80+
mid.offset(-(left as isize)),
81+
mid.offset((right-delta) as isize),
82+
delta);
83+
84+
if left <= right {
85+
right -= delta;
86+
} else {
87+
left -= delta;
88+
}
89+
}
90+
91+
let rawarray = RawArray::new();
92+
let buf = rawarray.ptr();
93+
94+
let dim = mid.offset(-(left as isize)).offset(right as isize);
95+
if left <= right {
96+
ptr::copy_nonoverlapping(mid.offset(-(left as isize)), buf, left);
97+
ptr::copy(mid, mid.offset(-(left as isize)), right);
98+
ptr::copy_nonoverlapping(buf, dim, left);
99+
}
100+
else {
101+
ptr::copy_nonoverlapping(mid, buf, right);
102+
ptr::copy(mid.offset(-(left as isize)), dim, left);
103+
ptr::copy_nonoverlapping(buf, mid.offset(-(left as isize)), right);
104+
}
105+
}
106+
107+
unsafe fn ptr_swap_n<T>(a: *mut T, b: *mut T, n: usize) {
108+
for i in 0..n {
109+
// These are nonoverlapping, so use mem::swap instead of ptr::swap
110+
mem::swap(&mut *a.offset(i as isize), &mut *b.offset(i as isize));
111+
}
112+
}

src/libcore/tests/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
#![feature(raw)]
3131
#![feature(sip_hash_13)]
3232
#![feature(slice_patterns)]
33+
#![feature(slice_rotate)]
3334
#![feature(sort_internals)]
3435
#![feature(sort_unstable)]
3536
#![feature(specialization)]

src/libcore/tests/slice.rs

+16
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,22 @@ fn test_find_rfind() {
238238
assert_eq!(v.iter().rfind(|&&x| x <= 3), Some(&3));
239239
}
240240

241+
#[test]
242+
fn test_rotate() {
243+
const N: usize = 600;
244+
let a: &mut [_] = &mut [0; N];
245+
for i in 0..N {
246+
a[i] = i;
247+
}
248+
249+
a.rotate(42);
250+
let k = N - 42;
251+
252+
for i in 0..N {
253+
assert_eq!(a[(i+k)%N], i);
254+
}
255+
}
256+
241257
#[test]
242258
fn sort_unstable() {
243259
let mut v = [0; 600];

0 commit comments

Comments
 (0)