Skip to content

Commit 202720b

Browse files
committed
Auto merge of #81152 - lzutao:intersperse_fold, r=m-ou-se
Fix intersperse_fold Here is a standalone playground link in case anybody wants to modify code: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=626b4d044fb74f044a36098ad907e40f Fixes #81145 cc #79479 `@jonas-schievink`
2 parents 65767e5 + 9272d53 commit 202720b

File tree

2 files changed

+45
-3
lines changed

2 files changed

+45
-3
lines changed

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

+4-3
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ where
160160
}
161161

162162
fn intersperse_fold<I, B, F, G>(
163-
mut iter: Peekable<I>,
163+
mut iter: I,
164164
init: B,
165165
mut f: F,
166166
mut separator: G,
@@ -173,10 +173,11 @@ where
173173
{
174174
let mut accum = init;
175175

176-
// Use `peek()` first to avoid calling `next()` on an empty iterator.
177-
if !needs_sep || iter.peek().is_some() {
176+
if !needs_sep {
178177
if let Some(x) = iter.next() {
179178
accum = f(accum, x);
179+
} else {
180+
return accum;
180181
}
181182
}
182183

library/core/tests/iter.rs

+41
Original file line numberDiff line numberDiff line change
@@ -3562,6 +3562,47 @@ fn test_intersperse_size_hint() {
35623562
assert_eq!([].iter().intersperse(&()).size_hint(), (0, Some(0)));
35633563
}
35643564

3565+
#[test]
3566+
fn test_intersperse_fold() {
3567+
let v = (1..4).intersperse(9).fold(Vec::new(), |mut acc, x| {
3568+
acc.push(x);
3569+
acc
3570+
});
3571+
assert_eq!(v.as_slice(), [1, 9, 2, 9, 3]);
3572+
3573+
let mut iter = (1..4).intersperse(9);
3574+
assert_eq!(iter.next(), Some(1));
3575+
let v = iter.fold(Vec::new(), |mut acc, x| {
3576+
acc.push(x);
3577+
acc
3578+
});
3579+
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);
3592+
}
3593+
3594+
#[test]
3595+
fn test_intersperse_collect_string() {
3596+
let contents = vec![1, 2, 3];
3597+
3598+
let contents_string = contents
3599+
.into_iter()
3600+
.map(|id| id.to_string())
3601+
.intersperse(", ".to_owned())
3602+
.collect::<String>();
3603+
assert_eq!(contents_string, "1, 2, 3");
3604+
}
3605+
35653606
#[test]
35663607
fn test_fold_specialization_intersperse() {
35673608
let mut iter = (1..2).intersperse(0);

0 commit comments

Comments
 (0)