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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
//!
//! # Bindings
//!
//! This library provides a mechansim for designing applications with a data-driven
//! control flow. This is essentially the paradigm found in spreadsheets, where
//! a formula will update automatically if its dependencies update. This is a
//! convenient way to express how a user interface updates, as it eliminates the
//! need to describe and manage events.
//! 
//! A simple binding can be created using `let binding = bind(X)`. This creates
//! a simple mutable binding that can be updated using `binding.set(Y)` or
//! retrieved using `binding.get()`.
//! 
//! This value can be monitored using `when_changed`, as in 
//! `let lifetime = binding.when_changed(notify(|| println!("Changed!")))`.
//! The lifetime value returned can be used to stop the notifications from firing.
//! Unless `lifetime.keep_alive()` is called, it will also stop the notifications
//! once it goes out of scope.
//! 
//! So far, this is very similar to traditional observables. What makes bindings
//! different is the idea that they can be computed as well. Here's an example:
//! 
//! ```
//! # use flo_binding::*;
//! let mut number      = bind(1);
//! let number_clone    = number.clone();
//! let plusone         = computed(move || number_clone.get() + 1);
//! 
//! let mut lifetime    = plusone.when_changed(notify(|| println!("Changed!")));
//! 
//! println!("{}", plusone.get());  // 2
//! # assert!(plusone.get() == 2);
//! number.set(2);                  // 'Changed!'
//! println!("{}", plusone.get());  // 3
//! # assert!(plusone.get() == 3);
//! lifetime.done();
//! 
//! number.set(3);                  // Lifetime is done, so no notification
//! println!("{}", plusone.get());  // 4
//! # assert!(plusone.get() == 4);
//! ```
//! 
//! Computed values can be as complicated as necessary, and will notify the 
//! specified function whenever their value changes.
//! 
//! Cloning a binding creates a new binding that references the same location.
//! This makes it easier to pass bindings into closures (though still a
//! little awkward as Rust doesn't really have a shorthand way of doing this
//! for philosophical reasons). They're similar in behaviour to an 
//! `Arc<Mutex<X>>` object in this respect (and never really immutable given
//! that cloning them creates a mutable object)
//! 
//! Computed bindings as demonstrated above are 'lazy'. They don't know their
//! own value until they have been evaluated after a change (and start in this
//! 'uncertain' state), so they will not notify of value changes until they
//! have been read at least once and will not notify again until they have
//! been read again. Reading the value from within the notification is possible
//! but in general the idea is to queue up an update for later: being lazy in
//! this way prevents repeated computations of intermediate values when many
//! values are being updated. Knock-on effects are all accounted for, so if
//! a future update is queued, it won't trigger further notifications.
//!
#![warn(bare_trait_objects)]

extern crate desync;
extern crate futures;

mod traits;
pub mod binding_context;
mod binding;
mod computed;
mod bindref;
mod notify_fn;
mod releasable;
mod follow;
mod bind_stream;

pub use self::traits::*;
pub use self::binding::*;
pub use self::computed::*;
pub use self::bindref::*;
pub use self::notify_fn::*;
pub use self::follow::*;
pub use self::bind_stream::*;

///
/// Creates a simple bound value with the specified initial value
///
pub fn bind<Value: Clone+PartialEq>(val: Value) -> Binding<Value> {
    Binding::new(val)
}

///
/// Creates a computed value that tracks bindings accessed during the function call and marks itself as changed when any of these dependencies also change
///
pub fn computed<Value, TFn>(calculate_value: TFn) -> ComputedBinding<Value, TFn>
where Value: Clone+Send, TFn: 'static+Send+Sync+Fn() -> Value {
    ComputedBinding::new(calculate_value)
}

#[cfg(test)]
mod test {
    use super::*;
    use super::binding_context::*;

    use std::thread;
    use std::sync::*;
    use std::time::Duration;

    #[test]
    fn can_create_binding() {
        let bound = bind(1);
        assert!(bound.get() == 1);
    }

    #[test]
    fn can_update_binding() {
        let mut bound = bind(1);

        bound.set(2);
        assert!(bound.get() == 2);
    }

    #[test]
    fn notified_on_change() {
        let mut bound   = bind(1);
        let changed     = bind(false);

        let mut notify_changed = changed.clone();
        bound.when_changed(notify(move || notify_changed.set(true))).keep_alive();

        assert!(changed.get() == false);
        bound.set(2);
        assert!(changed.get() == true);
    }

    #[test]
    fn not_notified_on_no_change() {
        let mut bound   = bind(1);
        let changed     = bind(false);

        let mut notify_changed = changed.clone();
        bound.when_changed(notify(move || notify_changed.set(true))).keep_alive();

        assert!(changed.get() == false);
        bound.set(1);
        assert!(changed.get() == false);
    }

    #[test]
    fn notifies_after_each_change() {
        let mut bound       = bind(1);
        let change_count    = bind(0);

        let mut notify_count = change_count.clone();
        bound.when_changed(notify(move || { let count = notify_count.get(); notify_count.set(count+1) })).keep_alive();

        assert!(change_count.get() == 0);
        bound.set(2);
        assert!(change_count.get() == 1);

        bound.set(3);
        assert!(change_count.get() == 2);

        bound.set(4);
        assert!(change_count.get() == 3);
    }

    #[test]
    fn dispatches_multiple_notifications() {
        let mut bound       = bind(1);
        let change_count    = bind(0);

        let mut notify_count = change_count.clone();
        let mut notify_count2 = change_count.clone();
        bound.when_changed(notify(move || { let count = notify_count.get(); notify_count.set(count+1) })).keep_alive();
        bound.when_changed(notify(move || { let count = notify_count2.get(); notify_count2.set(count+1) })).keep_alive();

        assert!(change_count.get() == 0);
        bound.set(2);
        assert!(change_count.get() == 2);

        bound.set(3);
        assert!(change_count.get() == 4);

        bound.set(4);
        assert!(change_count.get() == 6);
    }

    #[test]
    fn stops_notifying_after_release() {
        let mut bound       = bind(1);
        let change_count    = bind(0);

        let mut notify_count = change_count.clone();
        let mut lifetime = bound.when_changed(notify(move || { let count = notify_count.get(); notify_count.set(count+1) }));

        assert!(change_count.get() == 0);
        bound.set(2);
        assert!(change_count.get() == 1);

        lifetime.done();
        assert!(change_count.get() == 1);
        bound.set(3);
        assert!(change_count.get() == 1);
    }

    #[test]
    fn release_only_affects_one_notification() {
        let mut bound       = bind(1);
        let change_count    = bind(0);

        let mut notify_count = change_count.clone();
        let mut notify_count2 = change_count.clone();
        let mut lifetime = bound.when_changed(notify(move || { let count = notify_count.get(); notify_count.set(count+1) }));
        bound.when_changed(notify(move || { let count = notify_count2.get(); notify_count2.set(count+1) })).keep_alive();

        assert!(change_count.get() == 0);
        bound.set(2);
        assert!(change_count.get() == 2);

        bound.set(3);
        assert!(change_count.get() == 4);

        bound.set(4);
        assert!(change_count.get() == 6);

        lifetime.done();

        bound.set(5);
        assert!(change_count.get() == 7);

        bound.set(6);
        assert!(change_count.get() == 8);

        bound.set(7);
        assert!(change_count.get() == 9);
    }

    #[test]
    fn binding_context_is_notified() {
        let mut bound = bind(1);

        bound.set(2);

        let (value, context) = BindingContext::bind(|| bound.get());
        assert!(value == 2);

        let changed = bind(false);
        let mut notify_changed = changed.clone();
        context.when_changed(notify(move || notify_changed.set(true))).keep_alive();

        assert!(changed.get() == false);
        bound.set(3);
        assert!(changed.get() == true);
    }

    #[test]
    fn can_compute_value() {
        let bound           = bind(1);

        let computed_from   = bound.clone();
        let computed        = computed(move || computed_from.get() + 1);

        assert!(computed.get() == 2);
    }

    #[test]
    fn can_recompute_value() {
        let mut bound       = bind(1);

        let computed_from   = bound.clone();
        let computed        = computed(move || computed_from.get() + 1);

        assert!(computed.get() == 2);

        bound.set(2);
        assert!(computed.get() == 3);

        bound.set(3);
        assert!(computed.get() == 4);
    }

    #[test]
    fn can_recursively_compute_values() {
        let mut bound           = bind(1);

        let computed_from       = bound.clone();
        let computed_val        = computed(move || computed_from.get() + 1);

        let more_computed_from  = computed_val.clone();
        let more_computed       = computed(move || more_computed_from.get() + 1);

        assert!(computed_val.get() == 2);
        assert!(more_computed.get() == 3);

        bound.set(2);
        assert!(computed_val.get() == 3);
        assert!(more_computed.get() == 4);

        bound.set(3);
        assert!(computed_val.get() == 4);
        assert!(more_computed.get() == 5);
    }

    #[test]
    fn can_recursively_compute_values_2() {
        let mut bound           = bind(1);

        let computed_from       = bound.clone();
        let computed_val        = computed(move || computed_from.get() + 1);
        let more_computed       = computed(move || computed_val.get() + 1);

        assert!(more_computed.get() == 3);

        bound.set(2);
        assert!(more_computed.get() == 4);

        bound.set(3);
        assert!(more_computed.get() == 5);
    }

    #[test]
    fn can_recursively_compute_values_3() {
        let mut bound           = bind(1);

        let computed_from       = bound.clone();
        let computed_val        = computed(move || computed_from.get() + 1);
        let more_computed       = computed(move || computed_val.get() + 1);
        let even_more_computed  = computed(move || more_computed.get() + 1);

        assert!(even_more_computed.get() == 4);

        bound.set(2);
        assert!(even_more_computed.get() == 5);

        bound.set(3);
        assert!(even_more_computed.get() == 6);
    }

    #[test]
    #[should_panic]
    fn panics_if_computed_generated_during_binding() {
        let mut bound           = bind(1);

        let computed_from       = bound.clone();
        let computed_val        = computed(move || computed_from.get() + 1);
        let even_more_computed  = computed(move || {
            let computed_val = computed_val.clone();

            // This computed binding would be dropped after the first evaluation, which would result in the binding never updating.
            // We should panic here.
            let more_computed = computed(move || computed_val.get() + 1);
            more_computed.get() + 1
        });

        assert!(even_more_computed.get() == 4);

        bound.set(2);
        assert!(even_more_computed.get() == 5);

        bound.set(3);
        assert!(even_more_computed.get() == 6);
    }

    #[test]
    fn computed_only_recomputes_as_needed() {
        let mut bound           = bind(1);

        let counter             = Arc::new(Mutex::new(0));
        let compute_counter     = counter.clone();
        let computed_from       = bound.clone();
        let computed            = computed(move || {
            let mut counter = compute_counter.lock().unwrap();
            *counter = *counter + 1;

            computed_from.get() + 1
        });

        assert!(computed.get() == 2);
        {
            let counter = counter.lock().unwrap();
            assert!(counter.clone() == 1);
        }

        assert!(computed.get() == 2);
        {
            let counter = counter.lock().unwrap();
            assert!(counter.clone() == 1);
        }

        bound.set(2);
        assert!(computed.get() == 3);
        {
            let counter = counter.lock().unwrap();
            assert!(counter.clone() == 2);
        }
    }

    #[test]
    fn computed_caches_values() {
        let update_count            = Arc::new(Mutex::new(0));
        let mut bound               = bind(1);

        let computed_update_count   = Arc::clone(&update_count);
        let computed_from           = bound.clone();
        let computed                = computed(move || {
            let mut computed_update_count = computed_update_count.lock().unwrap();
            *computed_update_count += 1;

            computed_from.get() + 1
        });

        assert!(computed.get() == 2);
        assert!(*update_count.lock().unwrap() == 1);

        assert!(computed.get() == 2);
        assert!(*update_count.lock().unwrap() == 1);

        bound.set(2);
        assert!(computed.get() == 3);
        assert!(*update_count.lock().unwrap() == 2);

        bound.set(3);
        assert!(*update_count.lock().unwrap() == 2);
        assert!(computed.get() == 4);
        assert!(*update_count.lock().unwrap() == 3);
    }

    #[test]
    fn computed_notifies_of_changes() {
        let mut bound       = bind(1);

        let computed_from   = bound.clone();
        let computed        = computed(move || computed_from.get() + 1);

        let mut changed = bind(false);
        let mut notify_changed = changed.clone();
        computed.when_changed(notify(move || notify_changed.set(true))).keep_alive();

        assert!(computed.get() == 2);
        assert!(changed.get() == false);

        bound.set(2);
        assert!(changed.get() == true);
        assert!(computed.get() == 3);

        changed.set(false);
        bound.set(3);
        assert!(changed.get() == true);
        assert!(computed.get() == 4);
    }

    #[test]
    fn computed_switches_dependencies() {
        let mut switch      = bind(false);
        let mut val1        = bind(1);
        let mut val2        = bind(2);

        let computed_switch = switch.clone();
        let computed_val1   = val1.clone();
        let computed_val2   = val2.clone();
        let computed        = computed(move || {
            // Use val1 when switch is false, and val2 when switch is true
            if computed_switch.get() {
                computed_val2.get() + 1
            } else {
                computed_val1.get() + 1
            }
        });

        let mut changed = bind(false);
        let mut notify_changed = changed.clone();
        computed.when_changed(notify(move || notify_changed.set(true))).keep_alive();

        // Initial value of computed (first get 'arms' when_changed too)
        assert!(computed.get() == 2);
        assert!(changed.get() == false);

        // Setting val2 shouldn't cause computed to become 'changed' initially
        val2.set(3);
        assert!(changed.get() == false);
        assert!(computed.get() == 2);

        // ... but setting val1 should
        val1.set(2);
        assert!(changed.get() == true);
        assert!(computed.get() == 3);

        // Flicking the switch will use the val2 value we set earlier
        changed.set(false);
        switch.set(true);
        assert!(changed.get() == true);
        assert!(computed.get() == 4);

        // Updating val2 should now mark us as changed
        changed.set(false);
        val2.set(4);
        assert!(changed.get() == true);
        assert!(computed.get() == 5);
        
        // Updating val1 should not mark us as changed
        changed.set(false);
        val1.set(5);
        assert!(changed.get() == false);
        assert!(computed.get() == 5);
    }

    #[test]
    fn change_during_computation_recomputes() {
        // Create a computed binding that delays for a bit while reading
        let mut some_binding = bind(1);
        let some_computed = {
            let some_binding = some_binding.clone();
            computed(move || {
                let result = some_binding.get() + 1;
                thread::sleep(Duration::from_millis(250));
                result
            })
        };

        // Start a thread that reads a value
        {
            let some_computed = some_computed.clone();
            thread::spawn(move || {
                assert!(some_computed.get() == 2);
            });
        }

        // Let the thread start running (give it enough time to start computing and reach the sleep statement)
        // TODO: thread::sleep might fail on systems that are slow enough or due to glitches (will fail spuriously if we update the binding before the calculation starts)
        thread::sleep(Duration::from_millis(10));

        // Update the value in the binding while the computed is running
        some_binding.set(2);

        // Computed value should update
        assert!(some_computed.get() == 3);
    }

    #[test]
    fn computed_propagates_changes() {
        let mut bound           = bind(1);

        let computed_from       = bound.clone();
        let propagates_from     = computed(move || computed_from.get() + 1);
        let computed_propagated = propagates_from.clone();
        let computed            = computed(move || computed_propagated.get() + 1);

        let mut changed = bind(false);
        let mut notify_changed = changed.clone();
        computed.when_changed(notify(move || notify_changed.set(true))).keep_alive();

        assert!(propagates_from.get() == 2);
        assert!(computed.get() == 3);
        assert!(changed.get() == false);

        bound.set(2);
        assert!(propagates_from.get() == 3);
        assert!(computed.get() == 4);
        assert!(changed.get() == true);

        changed.set(false);
        bound.set(3);
        assert!(changed.get() == true);
        assert!(propagates_from.get() == 4);
        assert!(computed.get() == 5);
    }

    #[test]
    fn computed_stops_notifying_when_released() {
        let mut bound       = bind(1);

        let computed_from   = bound.clone();
        let computed        = computed(move || computed_from.get() + 1);

        let mut changed = bind(false);
        let mut notify_changed = changed.clone();
        let mut lifetime = computed.when_changed(notify(move || notify_changed.set(true)));

        assert!(computed.get() == 2);
        assert!(changed.get() == false);

        bound.set(2);
        assert!(changed.get() == true);
        assert!(computed.get() == 3);

        changed.set(false);
        lifetime.done();

        bound.set(3);
        assert!(changed.get() == false);
        assert!(computed.get() == 4);

        bound.set(4);
        assert!(changed.get() == false);
        assert!(computed.get() == 5);
    }

    #[test]
    fn computed_doesnt_notify_more_than_once() {
        let mut bound       = bind(1);

        let computed_from   = bound.clone();
        let computed        = computed(move || computed_from.get() + 1);

        let mut changed = bind(false);
        let mut notify_changed = changed.clone();
        computed.when_changed(notify(move || notify_changed.set(true))).keep_alive();

        assert!(computed.get() == 2);
        assert!(changed.get() == false);

        // Setting the value marks the computed as changed
        bound.set(2);
        assert!(changed.get() == true);
        changed.set(false);

        // ... but when it's already changed we don't notify again
        bound.set(3);
        assert!(changed.get() == false);

        assert!(computed.get() == 4);

        // Once we've retrieved the value, we'll get notified of changes again
        bound.set(4);
        assert!(changed.get() == true);
    }

    #[test]
    fn computed_stops_notifying_once_out_of_scope() {
        let mut bound       = bind(1);
        let mut changed     = bind(false);

        {
            let computed_from   = bound.clone();
            let computed        = computed(move || computed_from.get() + 1);

            let mut notify_changed = changed.clone();
            computed.when_changed(notify(move || notify_changed.set(true))).keep_alive();

            assert!(computed.get() == 2);
            assert!(changed.get() == false);

            bound.set(2);
            assert!(changed.get() == true);
            assert!(computed.get() == 3);
        };

        // The computed value should have been disposed of so we should get no more notifications once we reach here
        changed.set(false);
        bound.set(3);
        assert!(changed.get() == false);
    }
}