]> git.lizzy.rs Git - rust.git/commitdiff
Make slice::reverse const
authorltdk <usr@ltdk.xyz>
Wed, 17 Aug 2022 06:01:32 +0000 (02:01 -0400)
committerltdk <usr@ltdk.xyz>
Wed, 17 Aug 2022 06:01:32 +0000 (02:01 -0400)
library/core/src/slice/mod.rs

index e79d47c9f98cdf0c234c3dafed3359104043ede5..361862cdd5257d7de07cdca4d9ca74a4a26c03bb 100644 (file)
@@ -674,8 +674,9 @@ pub const fn swap(&mut self, a: usize, b: usize) {
     /// assert!(v == [3, 2, 1]);
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
+    #[rustc_const_unstable(feature = "const_reverse", issue = "none")]
     #[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();
 
@@ -698,9 +699,9 @@ pub fn reverse(&mut self) {
         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
@@ -708,8 +709,10 @@ fn revswap<T>(a: &mut [T], b: &mut [T], n: usize) {
             // 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;
             }
         }
     }