Skip to content

Commit

Permalink
Fix intersperse_fold
Browse files Browse the repository at this point in the history
  • Loading branch information
tesuji committed Jan 19, 2021
1 parent c4df63f commit 20d8478
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
5 changes: 2 additions & 3 deletions library/core/src/iter/adapters/intersperse.rs
Expand Up @@ -160,7 +160,7 @@ where
}

fn intersperse_fold<I, B, F, G>(
mut iter: Peekable<I>,
mut iter: I,
init: B,
mut f: F,
mut separator: G,
Expand All @@ -173,8 +173,7 @@ where
{
let mut accum = init;

// Use `peek()` first to avoid calling `next()` on an empty iterator.
if !needs_sep || iter.peek().is_some() {
if !needs_sep {
if let Some(x) = iter.next() {
accum = f(accum, x);
}
Expand Down
29 changes: 29 additions & 0 deletions library/core/tests/iter.rs
Expand Up @@ -3562,6 +3562,35 @@ fn test_intersperse_size_hint() {
assert_eq!([].iter().intersperse(&()).size_hint(), (0, Some(0)));
}

#[test]
fn test_intersperse_fold() {
let v = (1..4).intersperse(9).fold(Vec::new(), |mut acc, x| {
acc.push(x);
acc
});
assert_eq!(v.as_slice(), [1, 9, 2, 9, 3]);

let mut iter = (1..4).intersperse(9);
assert_eq!(iter.next(), Some(1));
let v = iter.fold(Vec::new(), |mut acc, x| {
acc.push(x);
acc
});
assert_eq!(v.as_slice(), [9, 2, 9, 3]);
}

#[test]
fn test_intersperse_collect_string() {
let contents = vec![1, 2, 3];

let contents_string = contents
.into_iter()
.map(|id| id.to_string())
.intersperse(", ".to_owned())
.collect::<String>();
assert_eq!(contents_string, "1, 2, 3");
}

#[test]
fn test_fold_specialization_intersperse() {
let mut iter = (1..2).intersperse(0);
Expand Down

0 comments on commit 20d8478

Please sign in to comment.