Skip to content

Commit

Permalink
Specialize MapForGrouping::fold
Browse files Browse the repository at this point in the history
`MapForGrouping` is only internally used by `GroupingMapBy` and it only calls `for_each` on it (which in turn rely on `fold`). So I allow the clippy lint `missing_trait_methods` because specialize other methods is simply useless.
I could replace `next` body by `unreachable!()` and it would still work fine. Anyway, it will disappear from test coverage now that we have one.
I previously wandered how to test and benchmark this. The current tests will test this. And I guess I could benchmark this `fold` specialization through some `into_grouping_map_by` benchmark but I simply don't think it's worth the time: no doubt `adapted_iterator.map.fold` is faster than the default `fold` calling `next` repeatedly.
Note that all `GroupingMapBy` methods ultimately rely on this `fold` so this specialization will improve performance for all its methods.
  • Loading branch information
Philippe-Cholet committed Feb 9, 2024
1 parent 3e47a02 commit 79f76be
Showing 1 changed file with 9 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/grouping_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ impl<I, F> MapForGrouping<I, F> {
}
}

#[allow(clippy::missing_trait_methods)]
impl<K, V, I, F> Iterator for MapForGrouping<I, F>
where
I: Iterator<Item = V>,
Expand All @@ -32,6 +33,14 @@ where
fn next(&mut self) -> Option<Self::Item> {
self.0.next().map(|val| ((self.1)(&val), val))
}

fn fold<B, G>(self, init: B, f: G) -> B
where
G: FnMut(B, Self::Item) -> B,
{
let mut key_mapper = self.1;
self.0.map(|val| (key_mapper(&val), val)).fold(init, f)
}
}

/// Creates a new `GroupingMap` from `iter`
Expand Down

0 comments on commit 79f76be

Please sign in to comment.