From 79f76be32d8b431f36eb24317c6aad4869d1439a Mon Sep 17 00:00:00 2001 From: Philippe-Cholet <44676486+Philippe-Cholet@users.noreply.github.com> Date: Fri, 9 Feb 2024 10:22:54 +0100 Subject: [PATCH] Specialize `MapForGrouping::fold` `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. --- src/grouping_map.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/grouping_map.rs b/src/grouping_map.rs index a01968d4a..f165723cc 100644 --- a/src/grouping_map.rs +++ b/src/grouping_map.rs @@ -22,6 +22,7 @@ impl MapForGrouping { } } +#[allow(clippy::missing_trait_methods)] impl Iterator for MapForGrouping where I: Iterator, @@ -32,6 +33,14 @@ where fn next(&mut self) -> Option { self.0.next().map(|val| ((self.1)(&val), val)) } + + fn fold(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`