merge: implement iter_mut() and into_iter()

These two are trivial to implement using `itertools::interleave()`. I
don't think we even need tests.
This commit is contained in:
Martin von Zweigbergk 2023-08-23 22:37:03 -07:00 committed by Martin von Zweigbergk
parent d0be24ac62
commit 2063f2f44e

View file

@ -215,13 +215,18 @@ impl<T> Merge<T> {
trivial_merge(&self.removes, &self.adds) trivial_merge(&self.removes, &self.adds)
} }
/// Returns an iterator over the terms. The items will alternate between /// Returns an iterator over references to the terms. The items will
/// positive and negative terms, starting with positive (since there's one /// alternate between positive and negative terms, starting with
/// more of those). /// positive (since there's one more of those).
pub fn iter(&self) -> impl Iterator<Item = &T> { pub fn iter(&self) -> impl Iterator<Item = &T> {
itertools::interleave(&self.adds, &self.removes) itertools::interleave(&self.adds, &self.removes)
} }
/// A version of `Merge::iter()` that iterates over mutable references.
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T> {
itertools::interleave(self.adds.iter_mut(), self.removes.iter_mut())
}
/// Creates a new merge by applying `f` to each remove and add. /// Creates a new merge by applying `f` to each remove and add.
pub fn map<'a, U>(&'a self, f: impl FnMut(&'a T) -> U) -> Merge<U> { pub fn map<'a, U>(&'a self, f: impl FnMut(&'a T) -> U) -> Merge<U> {
let builder: MergeBuilder<U> = self.iter().map(f).collect(); let builder: MergeBuilder<U> = self.iter().map(f).collect();
@ -268,6 +273,15 @@ impl<T> MergeBuilder<T> {
} }
} }
impl<T> IntoIterator for Merge<T> {
type Item = T;
type IntoIter = itertools::Interleave<std::vec::IntoIter<T>, std::vec::IntoIter<T>>;
fn into_iter(self) -> Self::IntoIter {
itertools::interleave(self.adds, self.removes)
}
}
impl<T> FromIterator<T> for MergeBuilder<T> { impl<T> FromIterator<T> for MergeBuilder<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self { fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let mut removes = vec![]; let mut removes = vec![];