1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
use crate::ops::SharedOp;
use crate::prelude::*;
use std::marker::PhantomData;

/// `FilterMap` operator applies both `Filter` and `Map`.
pub trait FilterMap
where
  Self: Sized,
{
  /// The closure must return an Option<T>. filter_map creates an iterator which
  /// calls this closure on each element. If the closure returns Some(element),
  /// then that element is returned. If the closure returns None, it will try
  /// again, and call the closure on the next element, seeing if it will return
  /// Some.
  ///
  /// Why filter_map and not just filter and map? The key is in this part:
  ///
  /// If the closure returns Some(element), then that element is returned.
  ///
  /// In other words, it removes the Option<T> layer automatically. If your
  /// mapping is already returning an Option<T> and you want to skip over Nones,
  /// then filter_map is much, much nicer to use.
  ///
  /// # Examples
  ///
  /// ```
  ///  # use rxrust::prelude::*;
  ///  # use rxrust::ops::FilterMap;
  ///  let mut res: Vec<i32> = vec![];
  ///   observable::from_iter(["1", "lol", "3", "NaN", "5"].iter())
  ///   .filter_map(|s: &&str| s.parse().ok())
  ///   .subscribe(|v| res.push(v));
  ///
  /// assert_eq!(res, [1, 3, 5]);
  /// ```
  ///
  fn filter_map<F, SourceItem, Item>(
    self,
    f: F,
  ) -> FilterMapOp<Self, F, SourceItem>
  where
    F: FnMut(SourceItem) -> Option<Item>,
  {
    FilterMapOp {
      source: self,
      f,
      _p: PhantomData,
    }
  }
}

impl<T> FilterMap for T {}

pub struct FilterMapOp<S, F, I> {
  source: S,
  f: F,
  _p: PhantomData<I>,
}

impl<Item, Err, SourceItem, S, F, O, U>
  RawSubscribable<Item, Err, Subscriber<O, U>> for FilterMapOp<S, F, SourceItem>
where
  S: RawSubscribable<SourceItem, Err, Subscriber<FilterMapObserver<O, F>, U>>,
  F: FnMut(SourceItem) -> Option<Item>,
{
  type Unsub = S::Unsub;
  fn raw_subscribe(self, subscriber: Subscriber<O, U>) -> Self::Unsub {
    self.source.raw_subscribe(Subscriber {
      observer: FilterMapObserver {
        down_observer: subscriber.observer,
        f: self.f,
      },
      subscription: subscriber.subscription,
    })
  }
}

unsafe impl<S, F, I> Send for FilterMapOp<S, F, I>
where
  S: Send,
  F: Send,
{
}

unsafe impl<S, F, I> Sync for FilterMapOp<S, F, I>
where
  S: Sync,
  F: Sync,
{
}

impl<S, F, I> Fork for FilterMapOp<S, F, I>
where
  S: Fork,
  F: Clone,
{
  type Output = FilterMapOp<S::Output, F, I>;
  fn fork(&self) -> Self::Output {
    FilterMapOp {
      source: self.source.fork(),
      f: self.f.clone(),
      _p: PhantomData,
    }
  }
}
impl<S, F, I> IntoShared for FilterMapOp<S, F, I>
where
  S: IntoShared,
  F: Send + Sync + 'static,
  I: 'static,
{
  type Shared = SharedOp<FilterMapOp<S::Shared, F, I>>;
  fn to_shared(self) -> Self::Shared {
    SharedOp(FilterMapOp {
      source: self.source.to_shared(),
      f: self.f,
      _p: PhantomData,
    })
  }
}

pub struct FilterMapObserver<O, F> {
  down_observer: O,
  f: F,
}

impl<O, F, Item, Err, OutputItem> Observer<Item, Err>
  for FilterMapObserver<O, F>
where
  O: Observer<OutputItem, Err>,
  F: FnMut(Item) -> Option<OutputItem>,
{
  fn next(&mut self, value: Item) {
    if let Some(v) = (self.f)(value) {
      self.down_observer.next(v)
    }
  }
  #[inline(always)]
  fn error(&mut self, err: Err) { self.down_observer.error(err) }
  #[inline(always)]
  fn complete(&mut self) { self.down_observer.complete() }
}

impl<O, F> IntoShared for FilterMapObserver<O, F>
where
  O: IntoShared,
  F: Send + Sync + 'static,
{
  type Shared = FilterMapObserver<O::Shared, F>;
  fn to_shared(self) -> Self::Shared {
    FilterMapObserver {
      down_observer: self.down_observer.to_shared(),
      f: self.f,
    }
  }
}

#[cfg(test)]
mod test {
  use crate::{ops::FilterMap, prelude::*};

  #[test]
  fn map_types_mixed() {
    let mut i = 0;
    observable::from_iter(vec!['a', 'b', 'c'])
      .filter_map(|_v| Some(1))
      .subscribe(|v| i += v);
    assert_eq!(i, 3);
  }

  #[test]
  fn filter_map_shared_and_fork() {
    observable::of(1)
      .filter_map(|_| Some("str"))
      .fork()
      .to_shared()
      .fork()
      .to_shared()
      .subscribe(|_| {});
  }

  #[test]
  fn filter_map_return_ref() {
    observable::of(&1)
      .filter_map(Some)
      .fork()
      .to_shared()
      .fork()
      .to_shared()
      .subscribe(|_| {});
  }
}