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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
use super::{Stream, Sink, Subscription};
use std::default::Default;
use std::sync::{Arc, RwLock};

/// Trait that applies to both readonly and writeable reactive values.
pub trait ReactiveValue<T> {
    /// Returns the current value of the ReactiveValue.
    fn get(&self) -> Arc<T>;

    /// Returns a Stream that represents the changing value over time.
    /// Use this function to subscribe to changes in the ReactiveValue.ReadonlyReactiveValue
    ///
    /// # Examples
    /// ```
    /// use std::sync::{Arc, Mutex};
    /// use epoxy_streams::ReactiveValue;
    ///
    /// let value = ReactiveValue::new(4);
    ///
    /// let last_value = Arc::new(Mutex::new(0_i32));
    /// let last_value_write = last_value.clone();
    ///
    /// let subscription = value.as_stream().subscribe(move |val| {
    ///     *last_value_write.lock().unwrap() = *val;
    /// });
    ///
    /// value.set(1);
    /// assert_eq!(*last_value.lock().unwrap(), 1);
    ///
    /// value.set(100);
    /// assert_eq!(*last_value.lock().unwrap(), 100);
    /// ```
    fn as_stream(&self) -> Stream<T>;
}

// IMPLEMENTATIONS

struct ReadonlyReactiveValueImpl<T> {
    value: Box<RwLock<Arc<T>>>,

    #[allow(dead_code)]
    subscription: Subscription<T>,
}

impl<T> ReactiveValue<T> for ReadonlyReactiveValueImpl<T> {
    fn as_stream(&self) -> Stream<T> {
        self.subscription.stream.clone()
    }

    fn get(&self) -> Arc<T> {
        match self.value.read() {
            Ok(val) => Arc::clone(&val),
            Err(err) => panic!("ReactiveValue mutex poisoned: {}", err),
        }
    }
}

struct WriteableReactiveValueImpl<T> {
    value: Box<RwLock<Arc<T>>>,
    host: Sink<T>,
}

impl<T> ReactiveValue<T> for WriteableReactiveValueImpl<T> {
    fn as_stream(&self) -> Stream<T> {
        self.host.get_stream()
    }

    fn get(&self) -> Arc<T> {
        match self.value.read() {
            Ok(val) => Arc::clone(&val),
            Err(err) => panic!("ReactiveValue mutex poisoned: {}", err),
        }
    }
}

/// Holds the latest value emitted by a stream.
///
/// ReactiveValues automatically unsubscribe from the stream when they are destroyed, preventing
/// the kinds of memory leaks common in reactive programming.
///
/// # Examples
///
/// ```
/// use epoxy_streams::ReactiveValue;
///
/// let stream_host: epoxy_streams::Sink<i32> = epoxy_streams::Sink::new();
/// let stream = stream_host.get_stream();
/// let reactive_value = stream.map(|val| val * 100).to_reactive_value();
/// assert_eq!(*reactive_value.get(), 0);
/// stream_host.emit(1);
/// assert_eq!(*reactive_value.get(), 100);
/// stream_host.emit(3);
/// assert_eq!(*reactive_value.get(), 300);
/// ```
///
/// ```
/// use epoxy_streams::ReactiveValue;
///
/// let stream_host: epoxy_streams::Sink<i32> = epoxy_streams::Sink::new();
/// let stream = stream_host.get_stream();
/// let reactive_value = stream.map(|val| val * 100).to_reactive_value_with_default(1000);
/// assert_eq!(*reactive_value.get(), 1000);
/// stream_host.emit(100);
/// assert_eq!(*reactive_value.get(), 10000);
/// ```
pub struct ReadonlyReactiveValue<T> {
    pointer: Arc<ReadonlyReactiveValueImpl<T>>,
}

impl<T> ReactiveValue<T> for ReadonlyReactiveValue<T> {
    fn as_stream(&self) -> Stream<T> {
        self.pointer.as_stream()
    }

    fn get(&self) -> Arc<T> {
        self.pointer.get()
    }
}

impl<T> Clone for ReadonlyReactiveValue<T> {
    fn clone(&self) -> Self {
        ReadonlyReactiveValue {
            pointer: Arc::clone(&self.pointer),
        }
    }
}

/// Reactive value that is explicitly set, rather than being derived from a stream.
///
/// # Examples
/// ```
/// use epoxy_streams::ReactiveValue;
///
/// let writeable_value = ReactiveValue::new(5);
/// assert_eq!(*writeable_value.get(), 5);
///
/// writeable_value.set(50);
/// assert_eq!(*writeable_value.get(), 50);
/// ```
pub struct WriteableReactiveValue<T> {
    pointer: Arc<WriteableReactiveValueImpl<T>>,
}

impl<T> ReactiveValue<T> for WriteableReactiveValue<T> {
    fn as_stream(&self) -> Stream<T> {
        self.pointer.as_stream()
    }

    fn get(&self) -> Arc<T> {
        self.pointer.get()
    }
}

impl<T> Clone for WriteableReactiveValue<T> {
    fn clone(&self) -> Self {
        WriteableReactiveValue {
            pointer: Arc::clone(&self.pointer),
        }
    }
}

impl<T: 'static> WriteableReactiveValue<T> {
    /// Sets the value of the ReactiveValue, using a mutex to ensure thread safety.
    ///
    /// Note: use `set_rc` if your new value is already an Arc, as this will prevent the
    /// value from being unnecessarily copied.
    pub fn set(&self, value: T) {
        self.set_rc(Arc::new(value))
    }

    /// Sets the value of the ReactiveValue, using a mutex to ensure thread safety.
    pub fn set_rc(&self, value: Arc<T>) {
        {
            let mut val_mut = self.pointer.value.write().unwrap();
            *val_mut = value.clone();
        }
        self.pointer.host.emit_rc(value)
    }

    /// Returns a ReadonlyReactiveValue whose value matches this one.
    /// This is helpful when exposing ReactiveValues to public APIs, so that
    /// the consumer cannot alter the state of your component.
    pub fn as_readonly(&self) -> ReadonlyReactiveValue<T> {
        self.as_stream()
            .to_reactive_value_with_default_rc(self.get())
    }
}

// CONSTRUCTORS

impl<T: 'static> ReactiveValue<T> {
    /// Creates a new writeable reactive value.
    ///
    /// Note: Use `new_rc` if your default value is already an Arc, as this will
    /// prevent another pointer from being created unnecessarily.
    ///
    /// # Examples
    /// ```
    /// use epoxy_streams::ReactiveValue;
    ///
    /// let writeable_value = ReactiveValue::new(5);
    /// assert_eq!(*writeable_value.get(), 5);
    ///
    /// writeable_value.set(50);
    /// assert_eq!(*writeable_value.get(), 50);
    /// ```
    pub fn new(initial_value: T) -> WriteableReactiveValue<T> {
        ReactiveValue::new_rc(Arc::new(initial_value))
    }

    /// See docs for `new`
    pub fn new_rc(initial_value: Arc<T>) -> WriteableReactiveValue<T> {
        WriteableReactiveValue {
            pointer: Arc::new(WriteableReactiveValueImpl {
                value: Box::new(RwLock::new(initial_value)),
                host: Sink::new(),
            }),
        }
    }

    pub fn from_stream(stream: Stream<T>) -> ReadonlyReactiveValue<T>
    where
        T: Default,
    {
        ReactiveValue::from_stream_with_default(stream, Default::default())
    }

    pub fn from_stream_with_default(stream: Stream<T>, default: T) -> ReadonlyReactiveValue<T> {
        ReactiveValue::from_stream_with_default_rc(stream, Arc::new(default))
    }

    pub fn from_stream_with_default_rc(
        stream: Stream<T>,
        default: Arc<T>,
    ) -> ReadonlyReactiveValue<T> {
        let original_value = Box::new(RwLock::new(default));
        let val_ptr = Box::into_raw(original_value);
        unsafe {
            let value = Box::from_raw(val_ptr);
            let subscription = stream.subscribe(move |val| {
                let mut val_mut = (*val_ptr).write().unwrap();
                *val_mut = val.clone();
            });
            ReadonlyReactiveValue {
                pointer: Arc::new(ReadonlyReactiveValueImpl {
                    value: value,
                    subscription: subscription,
                }),
            }
        }
    }
}

impl<T: 'static> Stream<T> {
    /// Creates a ReactiveValue from the stream, using the empty state value for type T as the
    /// default.
    ///
    /// Use `to_reactive_value_with_default` or `to_reactive_value_with_default_rc` if you want
    /// a more reasonable default value, or if your type T does not implement `Default`.
    ///
    /// # Examples
    /// ```
    /// use epoxy_streams::ReactiveValue;
    ///
    /// let stream_host: epoxy_streams::Sink<i32> = epoxy_streams::Sink::new();
    /// let stream = stream_host.get_stream();
    ///
    /// let reactive_value = stream.map(|val| val * 100).to_reactive_value();
    /// assert_eq!(*reactive_value.get(), 0);
    ///
    /// stream_host.emit(100);
    /// assert_eq!(*reactive_value.get(), 10000);
    /// ```
    pub fn to_reactive_value(self) -> ReadonlyReactiveValue<T>
    where
        T: Default,
    {
        ReactiveValue::from_stream(self)
    }

    /// See `to_reactive_value`.
    pub fn to_reactive_value_with_default(self, default: T) -> ReadonlyReactiveValue<T> {
        ReactiveValue::from_stream_with_default(self, default)
    }

    /// See `to_reactive_value`.
    pub fn to_reactive_value_with_default_rc(self, default: Arc<T>) -> ReadonlyReactiveValue<T> {
        ReactiveValue::from_stream_with_default_rc(self, default)
    }
}