Skip to content

Commit 45b853d

Browse files
committed
Revise benchmark & use try_fold for fold
1 parent 13635c1 commit 45b853d

File tree

2 files changed

+13
-10
lines changed

2 files changed

+13
-10
lines changed

benches/bench1.rs

+6-5
Original file line numberDiff line numberDiff line change
@@ -457,11 +457,12 @@ fn while_some(c: &mut Criterion) {
457457
.map(|i| std::char::from_digit(i, 16))
458458
.while_some(),
459459
);
460-
let result: String = data.fold(String::new(), |acc, ch| acc + &ch.to_string());
461-
assert_eq!(
462-
result.chars().collect::<Vec<_>>(),
463-
"0123456789abcdef".chars().collect::<Vec<_>>()
464-
);
460+
// let result: String = data.fold(String::new(), |acc, ch| acc + &ch.to_string());
461+
let result = data.fold(String::new(), |mut acc, ch| {
462+
acc.push(ch);
463+
acc
464+
});
465+
assert_eq!(result.as_str(), "0123456789abcdef");
465466
});
466467
});
467468
}

src/adaptors/mod.rs

+7-5
Original file line numberDiff line numberDiff line change
@@ -582,15 +582,17 @@ where
582582
(0, self.iter.size_hint().1)
583583
}
584584

585-
fn fold<B, F>(self, acc: B, f: F) -> B
585+
fn fold<B, F>(mut self, acc: B, mut f: F) -> B
586586
where
587587
Self: Sized,
588588
F: FnMut(B, Self::Item) -> B,
589589
{
590-
self.iter
591-
.take_while(|opt| opt.is_some())
592-
.map(|item| item.unwrap())
593-
.fold(acc, f)
590+
let res = self.iter.try_fold(acc, |acc, item| match item {
591+
Some(item) => Ok(f(acc, item)),
592+
None => Err(acc),
593+
});
594+
let (Err(res) | Ok(res)) = res;
595+
res
594596
}
595597
}
596598

0 commit comments

Comments
 (0)