From e6201cfb5cabc636a1dbfb1e543e5485639497a4 Mon Sep 17 00:00:00 2001 From: Georg Brandl Date: Sat, 30 Apr 2016 11:16:30 +0200 Subject: [PATCH] Implement find() on Chain iterators This results in a roughly 2x speedup compared to the default impl "inherited" from Iterator. --- src/libcore/iter/mod.rs | 17 +++++++++++++++++ src/libcoretest/iter.rs | 13 +++++++++++++ 2 files changed, 30 insertions(+) diff --git a/src/libcore/iter/mod.rs b/src/libcore/iter/mod.rs index abc199cd182..17f7c0a773e 100644 --- a/src/libcore/iter/mod.rs +++ b/src/libcore/iter/mod.rs @@ -541,6 +541,23 @@ impl Iterator for Chain where } } + #[inline] + fn find

(&mut self, mut predicate: P) -> Option where + P: FnMut(&Self::Item) -> bool, + { + match self.state { + ChainState::Both => match self.a.find(&mut predicate) { + None => { + self.state = ChainState::Back; + self.b.find(predicate) + } + v => v + }, + ChainState::Front => self.a.find(predicate), + ChainState::Back => self.b.find(predicate), + } + } + #[inline] fn last(self) -> Option { match self.state { diff --git a/src/libcoretest/iter.rs b/src/libcoretest/iter.rs index 6c0cb03b5f7..56b10d0b79b 100644 --- a/src/libcoretest/iter.rs +++ b/src/libcoretest/iter.rs @@ -133,6 +133,19 @@ fn test_iterator_chain_count() { assert_eq!(zs.iter().chain(&ys).count(), 4); } +#[test] +fn test_iterator_chain_find() { + let xs = [0, 1, 2, 3, 4, 5]; + let ys = [30, 40, 50, 60]; + let mut iter = xs.iter().chain(&ys); + assert_eq!(iter.find(|&&i| i == 4), Some(&4)); + assert_eq!(iter.next(), Some(&5)); + assert_eq!(iter.find(|&&i| i == 40), Some(&40)); + assert_eq!(iter.next(), Some(&50)); + assert_eq!(iter.find(|&&i| i == 100), None); + assert_eq!(iter.next(), None); +} + #[test] fn test_filter_map() { let it = (0..).step_by(1).take(10)