Skip to content

Commit 3ced790

Browse files
bors[bot]SkiFire13
andauthored
Merge #517
517: Use internal iteration in more places r=jswrenn a=SkiFire13 I haven't benched it but internal iteration should always be equivalent or faster than external iteration. Co-authored-by: Giacomo Stevanato <[email protected]>
2 parents ddeb9f1 + 80cd4e9 commit 3ced790

File tree

3 files changed

+21
-20
lines changed

3 files changed

+21
-20
lines changed

src/adaptors/coalesce.rs

+15-14
Original file line numberDiff line numberDiff line change
@@ -40,20 +40,21 @@ where
4040

4141
fn next(&mut self) -> Option<Self::Item> {
4242
// this fuses the iterator
43-
let mut last = match self.last.take() {
44-
None => return None,
45-
Some(x) => x,
46-
};
47-
for next in &mut self.iter {
48-
match self.f.coalesce_pair(last, next) {
49-
Ok(joined) => last = joined,
50-
Err((last_, next_)) => {
51-
self.last = Some(next_);
52-
return Some(last_);
53-
}
54-
}
55-
}
56-
Some(last)
43+
let last = self.last.take()?;
44+
45+
let self_last = &mut self.last;
46+
let self_f = &mut self.f;
47+
Some(
48+
self.iter
49+
.try_fold(last, |last, next| match self_f.coalesce_pair(last, next) {
50+
Ok(joined) => Ok(joined),
51+
Err((last_, next_)) => {
52+
*self_last = Some(next_);
53+
Err(last_)
54+
}
55+
})
56+
.unwrap_or_else(|x| x),
57+
)
5758
}
5859

5960
fn size_hint(&self) -> (usize, Option<usize>) {

src/grouping_map.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -102,12 +102,12 @@ impl<I, K, V> GroupingMap<I>
102102
{
103103
let mut destination_map = HashMap::new();
104104

105-
for (key, val) in self.iter {
105+
self.iter.for_each(|(key, val)| {
106106
let acc = destination_map.remove(&key);
107107
if let Some(op_res) = operation(acc, &key, val) {
108108
destination_map.insert(key, op_res);
109109
}
110-
}
110+
});
111111

112112
destination_map
113113
}
@@ -208,9 +208,9 @@ impl<I, K, V> GroupingMap<I>
208208
{
209209
let mut destination_map = HashMap::new();
210210

211-
for (key, val) in self.iter {
211+
self.iter.for_each(|(key, val)| {
212212
destination_map.entry(key).or_insert_with(C::default).extend(Some(val));
213-
}
213+
});
214214

215215
destination_map
216216
}

src/k_smallest.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,15 @@ pub(crate) fn k_smallest<T: Ord, I: Iterator<Item = T>>(mut iter: I, k: usize) -
66

77
let mut heap = iter.by_ref().take(k).collect::<BinaryHeap<_>>();
88

9-
for i in iter {
9+
iter.for_each(|i| {
1010
debug_assert_eq!(heap.len(), k);
1111
// Equivalent to heap.push(min(i, heap.pop())) but more efficient.
1212
// This should be done with a single `.peek_mut().unwrap()` but
1313
// `PeekMut` sifts-down unconditionally on Rust 1.46.0 and prior.
1414
if *heap.peek().unwrap() > i {
1515
*heap.peek_mut().unwrap() = i;
1616
}
17-
}
17+
});
1818

1919
heap
2020
}

0 commit comments

Comments
 (0)