Skip to content

Commit 38bb0b1

Browse files
committed
Move rfold logic into iter_rfold
1 parent 3f70049 commit 38bb0b1

File tree

1 file changed

+35
-19
lines changed

1 file changed

+35
-19
lines changed

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

+35-19
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,35 @@ impl<I, U> FlattenCompat<I, U>
393393
where
394394
I: DoubleEndedIterator<Item: IntoIterator<IntoIter = U>>,
395395
{
396+
/// Folds the inner iterators into an accumulator by applying an operation, starting form the
397+
/// back.
398+
///
399+
/// Folds over the inner iterators, not over their elements. Is used by the `rfold` method.
400+
#[inline]
401+
fn iter_rfold<Acc, Fold>(self, mut acc: Acc, mut fold: Fold) -> Acc
402+
where
403+
Fold: FnMut(Acc, U) -> Acc,
404+
{
405+
#[inline]
406+
fn flatten<T: IntoIterator, Acc>(
407+
fold: &mut impl FnMut(Acc, T::IntoIter) -> Acc,
408+
) -> impl FnMut(Acc, T) -> Acc + '_ {
409+
move |acc, iter| fold(acc, iter.into_iter())
410+
}
411+
412+
if let Some(iter) = self.backiter {
413+
acc = fold(acc, iter);
414+
}
415+
416+
acc = self.iter.rfold(acc, flatten(&mut fold));
417+
418+
if let Some(iter) = self.frontiter {
419+
acc = fold(acc, iter);
420+
}
421+
422+
acc
423+
}
424+
396425
/// Folds over the inner iterators in reverse order as long as the given function returns
397426
/// successfully, always storing the most recent inner iterator in `self.backiter`.
398427
///
@@ -579,31 +608,18 @@ where
579608
}
580609

581610
#[inline]
582-
fn rfold<Acc, Fold>(self, mut init: Acc, mut fold: Fold) -> Acc
611+
fn rfold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
583612
where
584613
Fold: FnMut(Acc, Self::Item) -> Acc,
585614
{
586615
#[inline]
587-
fn flatten<T: IntoIterator, Acc>(
588-
fold: &mut impl FnMut(Acc, T::Item) -> Acc,
589-
) -> impl FnMut(Acc, T) -> Acc + '_
590-
where
591-
T::IntoIter: DoubleEndedIterator,
592-
{
593-
move |acc, x| x.into_iter().rfold(acc, &mut *fold)
594-
}
595-
596-
if let Some(back) = self.backiter {
597-
init = back.rfold(init, &mut fold);
598-
}
599-
600-
init = self.iter.rfold(init, flatten(&mut fold));
601-
602-
if let Some(front) = self.frontiter {
603-
init = front.rfold(init, &mut fold);
616+
fn flatten<U: DoubleEndedIterator, Acc>(
617+
mut fold: impl FnMut(Acc, U::Item) -> Acc,
618+
) -> impl FnMut(Acc, U) -> Acc {
619+
move |acc, iter| iter.rfold(acc, &mut fold)
604620
}
605621

606-
init
622+
self.iter_rfold(init, flatten(fold))
607623
}
608624

609625
#[inline]

0 commit comments

Comments
 (0)