diff --git a/src/adaptors/mod.rs b/src/adaptors/mod.rs index 7ee81d1fe..b6711d565 100644 --- a/src/adaptors/mod.rs +++ b/src/adaptors/mod.rs @@ -1027,14 +1027,18 @@ impl Iterator for Positions type Item = usize; fn next(&mut self) -> Option { - for v in self.iter.by_ref() { - let i = self.count; - self.count = i + 1; - if (self.f)(v) { - return Some(i); + // let's help the borrow checker a little bit :) + let count = &mut self.count; + let f = &mut self.f; + self.iter.find_map(|v| { + let i = *count; + *count = i + 1; + if f(v) { + Some(i) + } else { + None } - } - None + }) } fn size_hint(&self) -> (usize, Option) { diff --git a/src/lib.rs b/src/lib.rs index 8a5cd5947..69491ce12 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1748,12 +1748,7 @@ pub trait Itertools : Iterator { fn find_position

(&mut self, mut pred: P) -> Option<(usize, Self::Item)> where P: FnMut(&Self::Item) -> bool { - for (index, elt) in self.enumerate() { - if pred(&elt) { - return Some((index, elt)); - } - } - None + self.enumerate().find(|x| pred(&x.1)) } /// Find the value of the first element satisfying a predicate or return the last element, if any. /// diff --git a/src/unique_impl.rs b/src/unique_impl.rs index d71b24a70..3f9082662 100644 --- a/src/unique_impl.rs +++ b/src/unique_impl.rs @@ -57,13 +57,17 @@ impl Iterator for UniqueBy type Item = I::Item; fn next(&mut self) -> Option { - for v in self.iter.by_ref() { - let key = (self.f)(&v); - if self.used.insert(key, ()).is_none() { - return Some(v); + // let's help the borrow checker a little bit :) + let used = &mut self.used; + let f = &mut self.f; + self.iter.find_map(|v| { + let key = f(&v); + if used.insert(key, ()).is_none() { + Some(v) + } else { + None } - } - None + }) } #[inline] @@ -107,14 +111,16 @@ impl Iterator for Unique type Item = I::Item; fn next(&mut self) -> Option { - for v in self.iter.iter.by_ref() { - if let Entry::Vacant(entry) = self.iter.used.entry(v) { + let used = &mut self.iter.used; + self.iter.iter.find_map(|v| { + if let Entry::Vacant(entry) = used.entry(v) { let elt = entry.key().clone(); entry.insert(()); - return Some(elt); + Some(elt) + } else { + None } - } - None + }) } #[inline]