use crate::LendingIterator;
use core::fmt;
#[derive(Clone)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Filter<I, P> {
iter: I,
predicate: P,
}
impl<I, P> Filter<I, P> {
pub(crate) fn new(iter: I, predicate: P) -> Self {
Self { iter, predicate }
}
}
impl<I: fmt::Debug, P> fmt::Debug for Filter<I, P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Filter")
.field("iter", &self.iter)
.finish_non_exhaustive()
}
}
impl<I, P> LendingIterator for Filter<I, P>
where
I: LendingIterator,
P: for<'a> FnMut(&I::Item<'a>) -> bool,
{
type Item<'a>
= I::Item<'a>
where
Self: 'a;
#[inline]
fn next(&mut self) -> Option<Self::Item<'_>> {
loop {
let self_ = unsafe { &mut *(self as *mut Self) };
if let Some(item) = self_.iter.next() {
if (self_.predicate)(&item) {
return Some(item);
}
} else {
return None;
}
}
}
}
#[cfg(test)]
mod tests {
use crate::{LendingIterator, ToLendingIterator};
fn identity(x: i32) -> i32 {
x
}
#[test]
fn filter_basic() {
let result: Vec<_> = (0..10)
.into_lending()
.filter(|&x| x % 2 == 0)
.map(identity)
.into_iter()
.collect();
assert_eq!(result, vec![0, 2, 4, 6, 8]);
}
}