use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedFused}; use crate::mem::{ManuallyDrop, MaybeUninit}; use crate::num::NonZeroUsize; use crate::ops::{ControlFlow, Try}; use crate::{array, fmt}; /// An iterator that uses `f` to both filter and map elements from `iter`. /// /// This `struct` is created by the [`filter_map`] method on [`Iterator`]. See its /// documentation for more. /// /// [`filter_map`]: Iterator::filter_map /// [`Iterator`]: trait.Iterator.html #[must_use = "iterators are lazy and do nothing unless consumed"] #[stable(feature = "rust1", since = "1.0.0")] #[derive(Clone)] pub struct FilterMap { iter: I, f: F, } impl FilterMap { pub(in crate::iter) fn new(iter: I, f: F) -> FilterMap { FilterMap { iter, f } } } #[stable(feature = "core_impl_debug", since = "1.9.0")] impl fmt::Debug for FilterMap { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("FilterMap").field("iter", &self.iter).finish() } } fn filter_map_fold( mut f: impl FnMut(T) -> Option, mut fold: impl FnMut(Acc, B) -> Acc, ) -> impl FnMut(Acc, T) -> Acc { move |acc, item| match f(item) { Some(x) => fold(acc, x), None => acc, } } fn filter_map_try_fold<'a, T, B, Acc, R: Try>( f: &'a mut impl FnMut(T) -> Option, mut fold: impl FnMut(Acc, B) -> R + 'a, ) -> impl FnMut(Acc, T) -> R + 'a { move |acc, item| match f(item) { Some(x) => fold(acc, x), None => try { acc }, } } #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for FilterMap where F: FnMut(I::Item) -> Option, { type Item = B; #[inline] fn next(&mut self) -> Option { self.iter.find_map(&mut self.f) } #[inline] fn next_chunk( &mut self, ) -> Result<[Self::Item; N], array::IntoIter> { let mut array: [MaybeUninit; N] = MaybeUninit::uninit_array(); struct Guard<'a, T> { array: &'a mut [MaybeUninit], initialized: usize, } impl Drop for Guard<'_, T> { #[inline] fn drop(&mut self) { if const { crate::mem::needs_drop::() } { // SAFETY: self.initialized is always <= N, which also is the length of the array. unsafe { core::ptr::drop_in_place(MaybeUninit::slice_assume_init_mut( self.array.get_unchecked_mut(..self.initialized), )); } } } } let mut guard = Guard { array: &mut array, initialized: 0 }; let result = self.iter.try_for_each(|element| { let idx = guard.initialized; let val = (self.f)(element); guard.initialized = idx + val.is_some() as usize; // SAFETY: Loop conditions ensure the index is in bounds. unsafe { let opt_payload_at: *const MaybeUninit = (&val as *const Option) .byte_add(core::mem::offset_of!(Option, Some.0)) .cast(); let dst = guard.array.as_mut_ptr().add(idx); crate::ptr::copy_nonoverlapping(opt_payload_at, dst, 1); crate::mem::forget(val); }; if guard.initialized < N { ControlFlow::Continue(()) } else { ControlFlow::Break(()) } }); let guard = ManuallyDrop::new(guard); match result { ControlFlow::Break(()) => { // SAFETY: The loop above is only explicitly broken when the array has been fully initialized Ok(unsafe { MaybeUninit::array_assume_init(array) }) } ControlFlow::Continue(()) => { let initialized = guard.initialized; // SAFETY: The range is in bounds since the loop breaks when reaching N elements. Err(unsafe { array::IntoIter::new_unchecked(array, 0..initialized) }) } } } #[inline] fn size_hint(&self) -> (usize, Option) { let (_, upper) = self.iter.size_hint(); (0, upper) // can't know a lower bound, due to the predicate } #[inline] fn try_fold(&mut self, init: Acc, fold: Fold) -> R where Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try, { self.iter.try_fold(init, filter_map_try_fold(&mut self.f, fold)) } #[inline] fn fold(self, init: Acc, fold: Fold) -> Acc where Fold: FnMut(Acc, Self::Item) -> Acc, { self.iter.fold(init, filter_map_fold(self.f, fold)) } } #[stable(feature = "rust1", since = "1.0.0")] impl DoubleEndedIterator for FilterMap where F: FnMut(I::Item) -> Option, { #[inline] fn next_back(&mut self) -> Option { #[inline] fn find( f: &mut impl FnMut(T) -> Option, ) -> impl FnMut((), T) -> ControlFlow + '_ { move |(), x| match f(x) { Some(x) => ControlFlow::Break(x), None => ControlFlow::Continue(()), } } self.iter.try_rfold((), find(&mut self.f)).break_value() } #[inline] fn try_rfold(&mut self, init: Acc, fold: Fold) -> R where Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try, { self.iter.try_rfold(init, filter_map_try_fold(&mut self.f, fold)) } #[inline] fn rfold(self, init: Acc, fold: Fold) -> Acc where Fold: FnMut(Acc, Self::Item) -> Acc, { self.iter.rfold(init, filter_map_fold(self.f, fold)) } } #[stable(feature = "fused", since = "1.26.0")] impl FusedIterator for FilterMap where F: FnMut(I::Item) -> Option {} #[unstable(issue = "none", feature = "trusted_fused")] unsafe impl TrustedFused for FilterMap {} #[unstable(issue = "none", feature = "inplace_iteration")] unsafe impl SourceIter for FilterMap where I: SourceIter, { type Source = I::Source; #[inline] unsafe fn as_inner(&mut self) -> &mut I::Source { // SAFETY: unsafe function forwarding to unsafe function with the same requirements unsafe { SourceIter::as_inner(&mut self.iter) } } } #[unstable(issue = "none", feature = "inplace_iteration")] unsafe impl InPlaceIterable for FilterMap { const EXPAND_BY: Option = I::EXPAND_BY; const MERGE_BY: Option = I::MERGE_BY; }