1use super::plumbing::*;
2use super::*;
3
4use std::fmt::{self, Debug};
5
6#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
11#[derive(Clone)]
12pub struct FilterMap<I, P> {
13 base: I,
14 filter_op: P,
15}
16
17impl<I: Debug, P> Debug for FilterMap<I, P> {
18 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19 f.debug_struct("FilterMap")
20 .field("base", &self.base)
21 .finish()
22 }
23}
24
25impl<I, P> FilterMap<I, P> {
26 pub(super) fn new(base: I, filter_op: P) -> Self {
28 FilterMap { base, filter_op }
29 }
30}
31
32impl<I, P, R> ParallelIterator for FilterMap<I, P>
33where
34 I: ParallelIterator,
35 P: Fn(I::Item) -> Option<R> + Sync + Send,
36 R: Send,
37{
38 type Item = R;
39
40 fn drive_unindexed<C>(self, consumer: C) -> C::Result
41 where
42 C: UnindexedConsumer<Self::Item>,
43 {
44 let consumer = FilterMapConsumer::new(consumer, &self.filter_op);
45 self.base.drive_unindexed(consumer)
46 }
47}
48
49struct FilterMapConsumer<'p, C, P> {
53 base: C,
54 filter_op: &'p P,
55}
56
57impl<'p, C, P: 'p> FilterMapConsumer<'p, C, P> {
58 fn new(base: C, filter_op: &'p P) -> Self {
59 FilterMapConsumer { base, filter_op }
60 }
61}
62
63impl<'p, T, U, C, P> Consumer<T> for FilterMapConsumer<'p, C, P>
64where
65 C: Consumer<U>,
66 P: Fn(T) -> Option<U> + Sync + 'p,
67{
68 type Folder = FilterMapFolder<'p, C::Folder, P>;
69 type Reducer = C::Reducer;
70 type Result = C::Result;
71
72 fn split_at(self, index: usize) -> (Self, Self, Self::Reducer) {
73 let (left, right, reducer) = self.base.split_at(index);
74 (
75 FilterMapConsumer::new(left, self.filter_op),
76 FilterMapConsumer::new(right, self.filter_op),
77 reducer,
78 )
79 }
80
81 fn into_folder(self) -> Self::Folder {
82 let base = self.base.into_folder();
83 FilterMapFolder {
84 base,
85 filter_op: self.filter_op,
86 }
87 }
88
89 fn full(&self) -> bool {
90 self.base.full()
91 }
92}
93
94impl<'p, T, U, C, P> UnindexedConsumer<T> for FilterMapConsumer<'p, C, P>
95where
96 C: UnindexedConsumer<U>,
97 P: Fn(T) -> Option<U> + Sync + 'p,
98{
99 fn split_off_left(&self) -> Self {
100 FilterMapConsumer::new(self.base.split_off_left(), self.filter_op)
101 }
102
103 fn to_reducer(&self) -> Self::Reducer {
104 self.base.to_reducer()
105 }
106}
107
108struct FilterMapFolder<'p, C, P> {
109 base: C,
110 filter_op: &'p P,
111}
112
113impl<'p, T, U, C, P> Folder<T> for FilterMapFolder<'p, C, P>
114where
115 C: Folder<U>,
116 P: Fn(T) -> Option<U> + Sync + 'p,
117{
118 type Result = C::Result;
119
120 fn consume(self, item: T) -> Self {
121 let filter_op = self.filter_op;
122 if let Some(mapped_item) = filter_op(item) {
123 let base = self.base.consume(mapped_item);
124 FilterMapFolder { base, filter_op }
125 } else {
126 self
127 }
128 }
129
130 fn complete(self) -> C::Result {
135 self.base.complete()
136 }
137
138 fn full(&self) -> bool {
139 self.base.full()
140 }
141}