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
/// Make a ConnectableObservable behave like a ordinary observable and
/// automates the way you can connect to it.
///
/// Internally it counts the subscriptions to the observable and subscribes
/// (only once) to the source if the number of subscriptions is larger than
/// 0. If the number of subscriptions is smaller than 1, it unsubscribes
/// from the source. This way you can make sure that everything before the
/// published refCount has only a single subscription independently of the
/// number of subscribers to the target observable.
///
/// Note that using the share operator is exactly the same as using the
/// publish operator (making the observable hot) and the refCount operator
/// in a sequence.
use crate::{
  prelude::*,
  rc::{MutArc, MutRc, RcDerefMut},
};

pub struct ShareOp<'a, Item, Err, Source>(
  MutRc<InnerShareOp<Source, Subject<'a, Item, Err>>>,
);

pub struct ShareOpThreads<Item, Err, Source>(
  MutArc<InnerShareOp<Source, SubjectThreads<Item, Err>>>,
);

enum InnerShareOp<Source, Subject> {
  Connectable(ConnectableObservable<Source, Subject>),
  Connected(Subject),
}

macro_rules! impl_trivial {
  ($name: ident, $rc: ident $(,$lf: lifetime)?) => {
    impl<$($lf,)? Item, Err, S> Clone for $name<$($lf,)? Item, Err, S> {
      fn clone(&self) -> Self {
        Self(self.0.clone())
      }
    }

    impl<$($lf,)? Item, Err, S> $name<$($lf,)? Item, Err, S> {
      #[inline]
      pub fn new(source: S) -> Self {
        let inner = InnerShareOp::Connectable(ConnectableObservable::new(source));
        $name($rc::own(inner))
      }
    }
  };
}

impl_trivial!(ShareOp, MutRc, 'a);
impl_trivial!(ShareOpThreads, MutArc);

macro_rules! impl_observable_methods {
  ($subject: ty) => {
    type Unsub = RefCountSubscription<
      $subject,
      <$subject as Observable<Item, Err, O>>::Unsub,
    >;

    fn actual_subscribe(self, observer: O) -> Self::Unsub {
      let mut inner = self.0.rc_deref_mut();
      match &mut *inner {
        InnerShareOp::Connectable(c) => {
          let subject = c.fork();

          let subscription = subject.clone().actual_subscribe(observer);
          let connected = InnerShareOp::Connected(subject.clone());
          let connectable = std::mem::replace(&mut *inner, connected);

          match connectable {
            InnerShareOp::Connectable(connectable) => connectable.connect(),
            InnerShareOp::Connected { .. } => unreachable!(),
          };

          RefCountSubscription { subject, subscription }
        }
        InnerShareOp::Connected(subject) => {
          let subscription = subject.clone().actual_subscribe(observer);
          RefCountSubscription { subject: subject.clone(), subscription }
        }
      }
    }
  };
}

impl<'a, S, Item, Err, O> Observable<Item, Err, O> for ShareOp<'a, Item, Err, S>
where
  Item: Clone,
  Err: Clone,
  O: Observer<Item, Err> + 'a,
  S: Observable<Item, Err, Subject<'a, Item, Err>>,
{
  impl_observable_methods!(Subject<'a, Item, Err>);
}

impl<'a, S, Item, Err> ObservableExt<Item, Err> for ShareOp<'a, Item, Err, S> where
  S: ObservableExt<Item, Err>
{
}

impl<S, Item, Err, O> Observable<Item, Err, O> for ShareOpThreads<Item, Err, S>
where
  Item: Clone,
  Err: Clone,
  O: Observer<Item, Err> + Send + 'static,
  S: Observable<Item, Err, SubjectThreads<Item, Err>>,
{
  impl_observable_methods!(SubjectThreads< Item, Err>);
}

impl<S, Item, Err> ObservableExt<Item, Err> for ShareOpThreads<Item, Err, S> where
  S: ObservableExt<Item, Err>
{
}
pub struct RefCountSubscription<Subject, U> {
  subject: Subject,
  subscription: U,
}

impl<U, Subject> Subscription for RefCountSubscription<Subject, U>
where
  Subject: Subscription + SubjectSize,
  U: Subscription,
{
  fn unsubscribe(self) {
    self.subscription.unsubscribe();
    if self.subject.is_empty() {
      self.subject.unsubscribe()
    }
  }

  #[inline(always)]
  fn is_closed(&self) -> bool {
    self.subscription.is_closed()
  }
}

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

  #[test]
  fn smoke() {
    let mut accept1 = 0;
    let mut accept2 = 0;
    {
      let ref_count = observable::of(1).share();
      ref_count.clone().subscribe(|v| accept1 = v);
      ref_count.clone().subscribe(|v| accept2 = v);
    }

    assert_eq!(accept1, 1);
    assert_eq!(accept2, 0);
  }

  #[test]
  fn auto_unsubscribe() {
    let mut accept1 = 0;
    let mut accept2 = 0;
    {
      let mut subject = Subject::default();
      let ref_count = subject.clone().share();
      let s1 = ref_count.clone().subscribe(|v| accept1 = v);
      let s2 = ref_count.clone().subscribe(|v| accept2 = v);
      subject.next(1);
      s1.unsubscribe();
      s2.unsubscribe();
      subject.next(2);
    }

    assert_eq!(accept1, 1);
    assert_eq!(accept2, 1);
  }

  #[test]
  fn bench() {
    do_bench();
  }

  benchmark_group!(do_bench, bench_ref_count);

  fn bench_ref_count(b: &mut bencher::Bencher) {
    b.iter(smoke)
  }
}