Skip to content

Commit

Permalink
Rollup merge of rust-lang#100663 - clarfonthey:const-reverse, r=scottmcm
Browse files Browse the repository at this point in the history
Make slice::reverse const

I remember this not being doable for some reason before, but decided to try it again and everything worked out in the tests.
  • Loading branch information
matthiaskrgr authored Aug 21, 2022
2 parents 0562eec + ae2b1db commit 84dec7b
Showing 1 changed file with 8 additions and 5 deletions.
13 changes: 8 additions & 5 deletions library/core/src/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -674,8 +674,9 @@ impl<T> [T] {
/// assert!(v == [3, 2, 1]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_reverse", issue = "100784")]
#[inline]
pub fn reverse(&mut self) {
pub const fn reverse(&mut self) {
let half_len = self.len() / 2;
let Range { start, end } = self.as_mut_ptr_range();

Expand All @@ -698,18 +699,20 @@ impl<T> [T] {
revswap(front_half, back_half, half_len);

#[inline]
fn revswap<T>(a: &mut [T], b: &mut [T], n: usize) {
debug_assert_eq!(a.len(), n);
debug_assert_eq!(b.len(), n);
const fn revswap<T>(a: &mut [T], b: &mut [T], n: usize) {
debug_assert!(a.len() == n);
debug_assert!(b.len() == n);

// Because this function is first compiled in isolation,
// this check tells LLVM that the indexing below is
// in-bounds. Then after inlining -- once the actual
// lengths of the slices are known -- it's removed.
let (a, b) = (&mut a[..n], &mut b[..n]);

for i in 0..n {
let mut i = 0;
while i < n {
mem::swap(&mut a[i], &mut b[n - 1 - i]);
i += 1;
}
}
}
Expand Down

0 comments on commit 84dec7b

Please sign in to comment.