]> git.lizzy.rs Git - rust.git/commitdiff
simplification: do not process the ArrayChunks remainder in fold()
authorThe 8472 <git@infinite-source.de>
Sun, 23 Oct 2022 19:29:15 +0000 (21:29 +0200)
committerThe 8472 <git@infinite-source.de>
Mon, 7 Nov 2022 20:44:25 +0000 (21:44 +0100)
library/core/src/iter/adapters/array_chunks.rs
library/core/tests/iter/adapters/array_chunks.rs

index 3f0fad4ed336f0b599245923df64a7d4877aec3e..9bd135007b4a6b520a76b19782e03f619f32dde1 100644 (file)
@@ -209,10 +209,6 @@ fn fold<B, F>(mut self, init: B, mut f: F) -> B
         Self: Sized,
         F: FnMut(B, Self::Item) -> B,
     {
-        if self.remainder.is_some() {
-            return init;
-        }
-
         let mut accum = init;
         let inner_len = self.iter.size();
         let mut i = 0;
@@ -233,20 +229,8 @@ fn fold<B, F>(mut self, init: B, mut f: F) -> B
             i += N;
         }
 
-        let remainder = inner_len % N;
-
-        let mut tail = MaybeUninit::uninit_array();
-        let mut guard = array::Guard { array_mut: &mut tail, initialized: 0 };
-        for i in 0..remainder {
-            // SAFETY: the remainder was not visited by the previous loop, so we're still only
-            // accessing each element once
-            let val = unsafe { self.iter.__iterator_get_unchecked(inner_len - remainder + i) };
-            guard.array_mut[i].write(val);
-            guard.initialized = i + 1;
-        }
-        mem::forget(guard);
-        // SAFETY: the loop above initialized elements up to the `remainder` index
-        self.remainder = Some(unsafe { array::IntoIter::new_unchecked(tail, 0..remainder) });
+        // unlike try_fold this method does not need to take care of the remainder
+        // since `self` will be dropped
 
         accum
     }
index 4e9d89e1e580f688c0d1d95afe636c8cf48a1bff..ef4a7e53bdd339caa6f7b22fbfb37fb16927b201 100644 (file)
@@ -139,7 +139,8 @@ fn test_iterator_array_chunks_fold() {
     let result =
         (0..10).map(|_| CountDrop::new(&count)).array_chunks::<3>().fold(0, |acc, _item| acc + 1);
     assert_eq!(result, 3);
-    assert_eq!(count.get(), 10);
+    // fold impls may or may not process the remainder
+    assert!(count.get() <= 10 && count.get() >= 9);
 }
 
 #[test]