Skip to content

Commit ef72b23

Browse files
committed
Override iterator fold and rfold
These benefit from internal iteration over just the head and then the tail, or vice versa. The `iter_sum_ringmap_10_000` benchmark is about twice as fast with this change!
1 parent 2d9e930 commit ef72b23

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/macros.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,13 @@ macro_rules! iterator_methods {
9898
self.next_back()
9999
}
100100

101+
fn fold<Acc, F>(self, acc: Acc, f: F) -> Acc
102+
where
103+
F: FnMut(Acc, Self::Item) -> Acc,
104+
{
105+
self.iter.map($map_elt).fold(acc, f)
106+
}
107+
101108
fn collect<C>(self) -> C
102109
where
103110
C: FromIterator<Self::Item>,
@@ -120,6 +127,13 @@ macro_rules! double_ended_iterator_methods {
120127
fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
121128
self.iter.nth_back(n).map($map_elt)
122129
}
130+
131+
fn rfold<Acc, F>(self, acc: Acc, f: F) -> Acc
132+
where
133+
F: FnMut(Acc, Self::Item) -> Acc,
134+
{
135+
self.iter.map($map_elt).rfold(acc, f)
136+
}
123137
};
124138
}
125139

src/map/iter.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,14 @@ impl<'a, K, V> Iterator for Buckets<'a, K, V> {
9292
self.next_back()
9393
}
9494

95+
fn fold<Acc, F>(self, mut acc: Acc, mut f: F) -> Acc
96+
where
97+
F: FnMut(Acc, Self::Item) -> Acc,
98+
{
99+
acc = self.head.fold(acc, &mut f);
100+
self.tail.fold(acc, &mut f)
101+
}
102+
95103
fn collect<C>(self) -> C
96104
where
97105
C: FromIterator<Self::Item>,
@@ -118,6 +126,14 @@ impl<K, V> DoubleEndedIterator for Buckets<'_, K, V> {
118126
}
119127
self.head.nth_back(n)
120128
}
129+
130+
fn rfold<Acc, F>(self, mut acc: Acc, mut f: F) -> Acc
131+
where
132+
F: FnMut(Acc, Self::Item) -> Acc,
133+
{
134+
acc = self.tail.rfold(acc, &mut f);
135+
self.head.rfold(acc, &mut f)
136+
}
121137
}
122138

123139
impl<K, V> ExactSizeIterator for Buckets<'_, K, V> {
@@ -208,6 +224,14 @@ impl<'a, K, V> Iterator for BucketsMut<'a, K, V> {
208224
self.next_back()
209225
}
210226

227+
fn fold<Acc, F>(self, acc: Acc, mut f: F) -> Acc
228+
where
229+
F: FnMut(Acc, Self::Item) -> Acc,
230+
{
231+
let acc = self.head.fold(acc, &mut f);
232+
self.tail.fold(acc, &mut f)
233+
}
234+
211235
fn collect<C>(self) -> C
212236
where
213237
C: FromIterator<Self::Item>,
@@ -234,6 +258,14 @@ impl<K, V> DoubleEndedIterator for BucketsMut<'_, K, V> {
234258
}
235259
self.head.nth_back(n)
236260
}
261+
262+
fn rfold<Acc, F>(self, acc: Acc, mut f: F) -> Acc
263+
where
264+
F: FnMut(Acc, Self::Item) -> Acc,
265+
{
266+
let acc = self.tail.rfold(acc, &mut f);
267+
self.head.rfold(acc, &mut f)
268+
}
237269
}
238270

239271
impl<K, V> ExactSizeIterator for BucketsMut<'_, K, V> {

0 commit comments

Comments
 (0)