From: The 8472 Date: Sun, 23 Oct 2022 19:29:15 +0000 (+0200) Subject: simplification: do not process the ArrayChunks remainder in fold() X-Git-Url: https://git.lizzy.rs/?a=commitdiff_plain;h=43c353fff73a1ee38d0ec29042e42bdeea05c191;p=rust.git simplification: do not process the ArrayChunks remainder in fold() --- diff --git a/library/core/src/iter/adapters/array_chunks.rs b/library/core/src/iter/adapters/array_chunks.rs index 3f0fad4ed33..9bd135007b4 100644 --- a/library/core/src/iter/adapters/array_chunks.rs +++ b/library/core/src/iter/adapters/array_chunks.rs @@ -209,10 +209,6 @@ fn fold(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(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 } diff --git a/library/core/tests/iter/adapters/array_chunks.rs b/library/core/tests/iter/adapters/array_chunks.rs index 4e9d89e1e58..ef4a7e53bdd 100644 --- a/library/core/tests/iter/adapters/array_chunks.rs +++ b/library/core/tests/iter/adapters/array_chunks.rs @@ -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]