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.
}
}
+ 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 {
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();