#[easy_ext::ext(IteratorExt)]
pub impl<I> I
where
Self: Sized + Iterator,
{
#[allow(dead_code)]
fn filter_while<F>(self, filter_fn: F) -> FilterWhile<Self, F>
where
F: Fn(&Self::Item) -> FilterWhileAction,
{
FilterWhile {
iter: self,
filter_fn,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum FilterWhileAction {
#[default]
Pick,
Skip,
Break,
}
impl FilterWhileAction {
pub fn or(self, other: FilterWhileAction) -> FilterWhileAction {
match (self, other) {
(Self::Pick, other) => other,
(Self::Skip, Self::Break) | (Self::Break, _) => Self::Break,
(Self::Skip, _) => Self::Skip,
}
}
}
pub struct FilterWhile<I, F> {
iter: I,
filter_fn: F,
}
impl<I, F> Iterator for FilterWhile<I, F>
where
I: Iterator,
F: Fn(&I::Item) -> FilterWhileAction,
{
type Item = I::Item;
fn next(&mut self) -> Option<Self::Item> {
for item in self.iter.by_ref() {
match (self.filter_fn)(&item) {
FilterWhileAction::Pick => return Some(item),
FilterWhileAction::Skip => {}
FilterWhileAction::Break => break,
}
}
None
}
}