mirror of
https://github.com/rust-lang/rust.git
synced 2026-05-16 21:15:18 +03:00
iter: Implement .fold() for .chain()
Chain can do something interesting here where it passes on the fold into its inner iterators. The lets the underlying iterator's custom fold() be used, and skips the regular chain logic in next.
This commit is contained in:
@@ -550,6 +550,25 @@ fn count(self) -> usize {
|
||||
}
|
||||
}
|
||||
|
||||
fn fold<Acc, F>(self, init: Acc, mut f: F) -> Acc
|
||||
where F: FnMut(Acc, Self::Item) -> Acc,
|
||||
{
|
||||
let mut accum = init;
|
||||
match self.state {
|
||||
ChainState::Both | ChainState::Front => {
|
||||
accum = self.a.fold(accum, &mut f);
|
||||
}
|
||||
_ => { }
|
||||
}
|
||||
match self.state {
|
||||
ChainState::Both | ChainState::Back => {
|
||||
accum = self.b.fold(accum, &mut f);
|
||||
}
|
||||
_ => { }
|
||||
}
|
||||
accum
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn nth(&mut self, mut n: usize) -> Option<A::Item> {
|
||||
match self.state {
|
||||
|
||||
@@ -985,6 +985,18 @@ fn test_empty() {
|
||||
assert_eq!(it.next(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_chain_fold() {
|
||||
let xs = [1, 2, 3];
|
||||
let ys = [1, 2, 0];
|
||||
|
||||
let mut iter = xs.iter().chain(&ys);
|
||||
iter.next();
|
||||
let mut result = Vec::new();
|
||||
iter.fold((), |(), &elt| result.push(elt));
|
||||
assert_eq!(&[2, 3, 1, 2, 0], &result[..]);
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_rposition(b: &mut Bencher) {
|
||||
let it: Vec<usize> = (0..300).collect();
|
||||
|
||||
Reference in New Issue
Block a user