Skip to content

Override Cycle::try_fold #62737

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 17, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions src/libcore/iter/adapters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,36 @@ impl<I> Iterator for Cycle<I> where I: Clone + Iterator {
_ => (usize::MAX, None)
}
}

#[inline]
fn try_fold<Acc, F, R>(&mut self, mut acc: Acc, mut f: F) -> R
where
F: FnMut(Acc, Self::Item) -> R,
R: Try<Ok = Acc>,
{
// fully iterate the current iterator. this is necessary because
// `self.iter` may be empty even when `self.orig` isn't
acc = self.iter.try_fold(acc, &mut f)?;
self.iter = self.orig.clone();

// complete a full cycle, keeping track of whether the cycled
// iterator is empty or not. we need to return early in case
// of an empty iterator to prevent an infinite loop
let mut is_empty = true;
acc = self.iter.try_fold(acc, |acc, x| {
is_empty = false;
f(acc, x)
})?;

if is_empty {
return Try::from_ok(acc);
}

loop {
self.iter = self.orig.clone();
acc = self.iter.try_fold(acc, &mut f)?;
}
}
}

#[stable(feature = "fused", since = "1.26.0")]
Expand Down
12 changes: 12 additions & 0 deletions src/libcore/tests/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1015,6 +1015,18 @@ fn test_cycle() {
assert_eq!(empty::<i32>().cycle().fold(0, |acc, x| acc + x), 0);

assert_eq!(once(1).cycle().skip(1).take(4).fold(0, |acc, x| acc + x), 4);

assert_eq!((0..10).cycle().take(5).sum::<i32>(), 10);
assert_eq!((0..10).cycle().take(15).sum::<i32>(), 55);
assert_eq!((0..10).cycle().take(25).sum::<i32>(), 100);

let mut iter = (0..10).cycle();
iter.nth(14);
assert_eq!(iter.take(8).sum::<i32>(), 38);

let mut iter = (0..10).cycle();
iter.nth(9);
assert_eq!(iter.take(3).sum::<i32>(), 3);
}

#[test]
Expand Down