Skip to content

Commit 475e4ba

Browse files
committed
Simplify ArrayChunks::{,r}fold impls
1 parent 4c0292c commit 475e4ba

File tree

1 file changed

+4
-46
lines changed

1 file changed

+4
-46
lines changed

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

+4-46
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use crate::array;
22
use crate::iter::{FusedIterator, Iterator};
33
use crate::mem;
44
use crate::mem::MaybeUninit;
5-
use crate::ops::{ControlFlow, Try};
5+
use crate::ops::{ControlFlow, NeverShortCircuit, Try};
66
use crate::ptr;
77

88
/// An iterator over `N` elements of the iterator at a time.
@@ -104,30 +104,12 @@ where
104104
}
105105
}
106106

107-
fn fold<B, F>(self, init: B, mut f: F) -> B
107+
fn fold<B, F>(mut self, init: B, mut f: F) -> B
108108
where
109109
Self: Sized,
110110
F: FnMut(B, Self::Item) -> B,
111111
{
112-
let mut array = MaybeUninit::uninit_array();
113-
// SAFETY: `array` will still be valid if `guard` is dropped.
114-
let mut guard = unsafe { FrontGuard::new(&mut array) };
115-
116-
self.iter.fold(init, |mut acc, item| {
117-
// SAFETY: `init` starts at 0, increases by one each iteration and
118-
// is reset to 0 once it reaches N.
119-
unsafe { array.get_unchecked_mut(guard.init) }.write(item);
120-
guard.init += 1;
121-
if guard.init == N {
122-
guard.init = 0;
123-
let array = mem::replace(&mut array, MaybeUninit::uninit_array());
124-
// SAFETY: the condition above asserts that all elements are
125-
// initialized.
126-
let item = unsafe { MaybeUninit::array_assume_init(array) };
127-
acc = f(acc, item);
128-
}
129-
acc
130-
})
112+
self.try_fold(init, |acc, x| NeverShortCircuit(f(acc, x))).0
131113
}
132114
}
133115

@@ -205,31 +187,7 @@ where
205187
Self: Sized,
206188
F: FnMut(B, Self::Item) -> B,
207189
{
208-
// We are iterating from the back we need to first handle the remainder.
209-
if self.next_back_remainder().is_none() {
210-
return init;
211-
}
212-
213-
let mut array = MaybeUninit::uninit_array();
214-
215-
// SAFETY: `array` will still be valid if `guard` is dropped.
216-
let mut guard = unsafe { BackGuard::new(&mut array) };
217-
218-
self.iter.rfold(init, |mut acc, item| {
219-
guard.uninit -= 1;
220-
// SAFETY: `uninit` starts at N, decreases by one each iteration and
221-
// is reset to N once it reaches 0.
222-
unsafe { array.get_unchecked_mut(guard.uninit) }.write(item);
223-
if guard.uninit == 0 {
224-
guard.uninit = N;
225-
let array = mem::replace(&mut array, MaybeUninit::uninit_array());
226-
// SAFETY: the condition above asserts that all elements are
227-
// initialized.
228-
let item = unsafe { MaybeUninit::array_assume_init(array) };
229-
acc = f(acc, item);
230-
}
231-
acc
232-
})
190+
self.try_rfold(init, |acc, x| NeverShortCircuit(f(acc, x))).0
233191
}
234192
}
235193

0 commit comments

Comments
 (0)