Skip to content

Commit 20d8478

Browse files
committed
Fix intersperse_fold
1 parent c4df63f commit 20d8478

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

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

+2-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,8 +173,7 @@ 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);
180179
}

library/core/tests/iter.rs

+29
Original file line numberDiff line numberDiff line change
@@ -3562,6 +3562,35 @@ 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+
3582+
#[test]
3583+
fn test_intersperse_collect_string() {
3584+
let contents = vec![1, 2, 3];
3585+
3586+
let contents_string = contents
3587+
.into_iter()
3588+
.map(|id| id.to_string())
3589+
.intersperse(", ".to_owned())
3590+
.collect::<String>();
3591+
assert_eq!(contents_string, "1, 2, 3");
3592+
}
3593+
35653594
#[test]
35663595
fn test_fold_specialization_intersperse() {
35673596
let mut iter = (1..2).intersperse(0);

0 commit comments

Comments
 (0)