Skip to content

Commit

Permalink
Stop fold at first None when iterator yield
Browse files Browse the repository at this point in the history
  • Loading branch information
m-ou-se authored and tesuji committed Jan 19, 2021
1 parent 20d8478 commit 9272d53
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
2 changes: 2 additions & 0 deletions library/core/src/iter/adapters/intersperse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,8 @@ where
if !needs_sep {
if let Some(x) = iter.next() {
accum = f(accum, x);
} else {
return accum;
}
}

Expand Down
12 changes: 12 additions & 0 deletions library/core/tests/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3577,6 +3577,18 @@ fn test_intersperse_fold() {
acc
});
assert_eq!(v.as_slice(), [9, 2, 9, 3]);

struct NoneAtStart(i32); // Produces: None, Some(2), Some(3), None, ...
impl Iterator for NoneAtStart {
type Item = i32;
fn next(&mut self) -> Option<i32> {
self.0 += 1;
Some(self.0).filter(|i| i % 3 != 1)
}
}

let v = NoneAtStart(0).intersperse(1000).fold(0, |a, b| a + b);
assert_eq!(v, 0);
}

#[test]
Expand Down

0 comments on commit 9272d53

Please sign in to comment.