Skip to content

Commit 5d7f32e

Browse files
committed
Implement DedupByWithCount in terms of CoalesceBy
1 parent 9d9bf4d commit 5d7f32e

File tree

1 file changed

+15
-37
lines changed

1 file changed

+15
-37
lines changed

src/adaptors/mod.rs

Lines changed: 15 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -799,11 +799,21 @@ pub fn dedup<I>(iter: I) -> Dedup<I>
799799
/// See [`.dedup_by_with_count()`](../trait.Itertools.html#method.dedup_by_with_count) or
800800
/// [`.dedup_with_count()`](../trait.Itertools.html#method.dedup_with_count) for more information.
801801
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
802-
pub struct DedupByWithCount<I, Pred>
803-
where I: Iterator
802+
pub type DedupByWithCount<I, Pred> = CoalesceBy<I, DedupPredWithCount2CoalescePred<Pred>, (usize, <I as Iterator>::Item)>;
803+
804+
#[derive(Clone)]
805+
pub struct DedupPredWithCount2CoalescePred<DP>(DP);
806+
807+
impl<DP, T> CoalescePredicate<T, (usize, T)> for DedupPredWithCount2CoalescePred<DP>
808+
where DP: DedupPredicate<T>
804809
{
805-
iter: CoalesceCore<I, (usize, I::Item)>,
806-
dedup_pred: Pred,
810+
fn coalesce_pair(&mut self, (c, t): (usize, T), item: T) -> Result<(usize, T), ((usize, T), (usize, T))> {
811+
if self.0.dedup_pair(&t, &item) {
812+
Ok((c + 1, t))
813+
} else {
814+
Err(((c, t), (1, item)))
815+
}
816+
}
807817
}
808818

809819
/// An iterator adaptor that removes repeated duplicates, while keeping a count of how many
@@ -821,7 +831,7 @@ pub fn dedup_by_with_count<I, Pred>(mut iter: I, dedup_pred: Pred) -> DedupByWit
821831
last: iter.next().map(|v| (1, v)),
822832
iter,
823833
},
824-
dedup_pred,
834+
f: DedupPredWithCount2CoalescePred(dedup_pred),
825835
}
826836
}
827837

@@ -832,38 +842,6 @@ pub fn dedup_with_count<I>(iter: I) -> DedupWithCount<I>
832842
dedup_by_with_count(iter, DedupEq)
833843
}
834844

835-
impl<I, Pred> fmt::Debug for DedupByWithCount<I, Pred>
836-
where I: Iterator + fmt::Debug,
837-
I::Item: fmt::Debug,
838-
{
839-
debug_fmt_fields!(Dedup, iter);
840-
}
841-
842-
impl<I: Clone, Pred: Clone> Clone for DedupByWithCount<I, Pred>
843-
where I: Iterator,
844-
I::Item: Clone,
845-
{
846-
clone_fields!(iter, dedup_pred);
847-
}
848-
849-
impl<I, Pred> Iterator for DedupByWithCount<I, Pred>
850-
where I: Iterator,
851-
Pred: DedupPredicate<I::Item>,
852-
{
853-
type Item = (usize, I::Item);
854-
855-
fn next(&mut self) -> Option<(usize, I::Item)> {
856-
let ref mut dedup_pred = self.dedup_pred;
857-
self.iter.next_with(|(c, x), y| {
858-
if dedup_pred.dedup_pair(&x, &y) { Ok((c + 1, x)) } else { Err(((c, x), (1, y))) }
859-
})
860-
}
861-
862-
fn size_hint(&self) -> (usize, Option<usize>) {
863-
self.iter.size_hint()
864-
}
865-
}
866-
867845
impl<I: Iterator, Pred: DedupPredicate<I::Item>> FusedIterator for DedupByWithCount<I, Pred> {}
868846

869847
/// An iterator adaptor that borrows from a `Clone`-able iterator

0 commit comments

Comments
 (0)