Skip to content

Commit 9272d53

Browse files
m-ou-setesuji
authored andcommitted
Stop fold at first None when iterator yield
1 parent 20d8478 commit 9272d53

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

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

+2
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,8 @@ where
176176
if !needs_sep {
177177
if let Some(x) = iter.next() {
178178
accum = f(accum, x);
179+
} else {
180+
return accum;
179181
}
180182
}
181183

library/core/tests/iter.rs

+12
Original file line numberDiff line numberDiff line change
@@ -3577,6 +3577,18 @@ fn test_intersperse_fold() {
35773577
acc
35783578
});
35793579
assert_eq!(v.as_slice(), [9, 2, 9, 3]);
3580+
3581+
struct NoneAtStart(i32); // Produces: None, Some(2), Some(3), None, ...
3582+
impl Iterator for NoneAtStart {
3583+
type Item = i32;
3584+
fn next(&mut self) -> Option<i32> {
3585+
self.0 += 1;
3586+
Some(self.0).filter(|i| i % 3 != 1)
3587+
}
3588+
}
3589+
3590+
let v = NoneAtStart(0).intersperse(1000).fold(0, |a, b| a + b);
3591+
assert_eq!(v, 0);
35803592
}
35813593

35823594
#[test]

0 commit comments

Comments
 (0)