Skip to content

Commit 43c353f

Browse files
committed
simplification: do not process the ArrayChunks remainder in fold()
1 parent cfcce8e commit 43c353f

File tree

2 files changed

+4
-19
lines changed

2 files changed

+4
-19
lines changed

library/core/src/iter/adapters/array_chunks.rs

Lines changed: 2 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -209,10 +209,6 @@ where
209209
Self: Sized,
210210
F: FnMut(B, Self::Item) -> B,
211211
{
212-
if self.remainder.is_some() {
213-
return init;
214-
}
215-
216212
let mut accum = init;
217213
let inner_len = self.iter.size();
218214
let mut i = 0;
@@ -233,20 +229,8 @@ where
233229
i += N;
234230
}
235231

236-
let remainder = inner_len % N;
237-
238-
let mut tail = MaybeUninit::uninit_array();
239-
let mut guard = array::Guard { array_mut: &mut tail, initialized: 0 };
240-
for i in 0..remainder {
241-
// SAFETY: the remainder was not visited by the previous loop, so we're still only
242-
// accessing each element once
243-
let val = unsafe { self.iter.__iterator_get_unchecked(inner_len - remainder + i) };
244-
guard.array_mut[i].write(val);
245-
guard.initialized = i + 1;
246-
}
247-
mem::forget(guard);
248-
// SAFETY: the loop above initialized elements up to the `remainder` index
249-
self.remainder = Some(unsafe { array::IntoIter::new_unchecked(tail, 0..remainder) });
232+
// unlike try_fold this method does not need to take care of the remainder
233+
// since `self` will be dropped
250234

251235
accum
252236
}

library/core/tests/iter/adapters/array_chunks.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,8 @@ fn test_iterator_array_chunks_fold() {
139139
let result =
140140
(0..10).map(|_| CountDrop::new(&count)).array_chunks::<3>().fold(0, |acc, _item| acc + 1);
141141
assert_eq!(result, 3);
142-
assert_eq!(count.get(), 10);
142+
// fold impls may or may not process the remainder
143+
assert!(count.get() <= 10 && count.get() >= 9);
143144
}
144145

145146
#[test]

0 commit comments

Comments
 (0)