From d0be24ac62f1ebe3907685ea54ed00c0c173e32a Mon Sep 17 00:00:00 2001 From: Martin von Zweigbergk Date: Wed, 23 Aug 2023 22:33:35 -0700 Subject: [PATCH] merge: rewrite `iter()` using `itertools::interleave()` `itertools::interleave()` does exactly what we want for `Merge::iter()`. I had just not thought to look for it before. Hopefully it's not noticeably slow. --- lib/src/merge.rs | 34 ++-------------------------------- 1 file changed, 2 insertions(+), 32 deletions(-) diff --git a/lib/src/merge.rs b/lib/src/merge.rs index 245fc5641..7151ab142 100644 --- a/lib/src/merge.rs +++ b/lib/src/merge.rs @@ -218,8 +218,8 @@ impl Merge { /// Returns an iterator over the terms. The items will alternate between /// positive and negative terms, starting with positive (since there's one /// more of those). - pub fn iter(&self) -> Iter<'_, T> { - Iter::new(self) + pub fn iter(&self) -> impl Iterator { + itertools::interleave(&self.adds, &self.removes) } /// Creates a new merge by applying `f` to each remove and add. @@ -246,36 +246,6 @@ impl Merge { } } -/// Iterator over the terms in a merge. See `Merge::iter()`. -pub struct Iter<'a, T> { - merge: &'a Merge, - i: usize, -} - -impl<'a, T> Iter<'a, T> { - fn new(merge: &'a Merge) -> Self { - Self { merge, i: 0 } - } -} - -impl<'a, T> Iterator for Iter<'a, T> { - type Item = &'a T; - - fn next(&mut self) -> Option { - if self.i > 2 * self.merge.removes.len() { - None - } else { - let item = if self.i % 2 == 0 { - &self.merge.adds[self.i / 2] - } else { - &self.merge.removes[self.i / 2] - }; - self.i += 1; - Some(item) - } - } -} - /// Helper for consuming items from an iterator and then creating a `Merge`. /// /// By not collecting directly into `Merge`, we can avoid creating invalid