Skip to content

Commit

Permalink
replace by_ref with internal iteration
Browse files Browse the repository at this point in the history
  • Loading branch information
hellow554 committed Jun 9, 2022
1 parent 695ddda commit 0cf44b6
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 24 deletions.
18 changes: 11 additions & 7 deletions src/adaptors/mod.rs
Expand Up @@ -1027,14 +1027,18 @@ impl<I, F> Iterator for Positions<I, F>
type Item = usize;

fn next(&mut self) -> Option<Self::Item> {
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<usize>) {
Expand Down
7 changes: 1 addition & 6 deletions src/lib.rs
Expand Up @@ -1748,12 +1748,7 @@ pub trait Itertools : Iterator {
fn find_position<P>(&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.
///
Expand Down
28 changes: 17 additions & 11 deletions src/unique_impl.rs
Expand Up @@ -57,13 +57,17 @@ impl<I, V, F> Iterator for UniqueBy<I, V, F>
type Item = I::Item;

fn next(&mut self) -> Option<Self::Item> {
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]
Expand Down Expand Up @@ -107,14 +111,16 @@ impl<I> Iterator for Unique<I>
type Item = I::Item;

fn next(&mut self) -> Option<Self::Item> {
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]
Expand Down

0 comments on commit 0cf44b6

Please sign in to comment.