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
use crate::internals::stream_controller::*;
use crate::prelude::*;

#[derive(Clone)]
pub struct Contains<Item>
where
  Item: Clone + Send + Sync + PartialEq,
{
  target: Item,
}

impl<'a, Item> Contains<Item>
where
  Item: Clone + Send + Sync + PartialEq,
{
  pub fn new(target: Item) -> Contains<Item> {
    Contains { target }
  }
  pub fn execute(&self, source: Observable<'a, Item>) -> Observable<'a, bool> {
    let target = self.target.clone();

    Observable::<bool>::create(move |s| {
      let target = target.clone();
      let sctl = StreamController::new(s);
      let sctl_next = sctl.clone();
      let sctl_error = sctl.clone();
      let sctl_complete = sctl.clone();
      source.inner_subscribe(sctl.new_observer(
        move |serial, x| {
          if x == target {
            sctl_next.sink_next(true);
            sctl_next.sink_complete(&serial);
          }
        },
        move |serial, _| {
          sctl_error.sink_next(false);
          sctl_error.sink_complete(&serial);
        },
        move |serial| {
          sctl_complete.sink_next(false);
          sctl_complete.sink_complete(&serial);
        },
      ));
    })
  }
}

impl<'a, Item> Observable<'a, Item>
where
  Item: Clone + Send + Sync + PartialEq,
{
  pub fn contains(&self, target: Item) -> Observable<'a, bool> {
    Contains::new(target).execute(self.clone())
  }
}

#[cfg(test)]
mod test {
  use crate::prelude::*;

  #[test]
  fn basic() {
    observables::from_iter(0..10).contains(5).subscribe(
      |x| {
        println!("{}", x);
        assert_eq!(x, true);
      },
      print_error!(),
      print_complete!(),
    );
  }

  #[test]
  fn not_found() {
    observables::from_iter(0..10).contains(100).subscribe(
      |x| {
        println!("{}", x);
        assert_eq!(x, false);
      },
      print_error!(),
      print_complete!(),
    );
  }

  #[test]
  fn error() {
    observables::error(RxError::from_error("ERR!"))
      .contains(5)
      .subscribe(
        |x| {
          println!("{}", x);
          assert_eq!(x, false);
        },
        print_error_as!(&str),
        print_complete!(),
      );
  }

  #[test]
  fn empty() {
    observables::empty().contains(5).subscribe(
      |x| {
        println!("{}", x);
        assert_eq!(x, false);
      },
      print_error!(),
      print_complete!(),
    );
  }
}