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
use crate::txrx::*;
use std::{cell::RefCell, rc::Rc};
#[derive(Clone)]
pub struct Model<T> {
value: Rc<RefCell<T>>,
trns: Transmitter<T>,
recv: Receiver<T>,
}
impl<T: Clone + 'static> Model<T> {
pub fn new(t: T) -> Model<T> {
let (trns, recv) = txrx::<T>();
Model {
value: Rc::new(RefCell::new(t)),
trns,
recv,
}
}
pub fn transmit(&self) {
self.trns.send(&self.value.as_ref().borrow());
}
pub fn visit<F, A>(&self, f: F) -> A
where
A: 'static,
F: FnOnce(&T) -> A,
{
f(&self.value.borrow())
}
pub fn visit_mut<F, A>(&self, f: F) -> A
where
A: 'static,
F: FnOnce(&mut T) -> A,
{
let a = f(&mut self.value.borrow_mut());
self.transmit();
a
}
pub fn replace(&self, t: T) -> T {
let t = self.value.replace(t);
self.transmit();
t
}
pub fn replace_with<F>(&self, f: F) -> T
where
F: FnOnce(&mut T) -> T,
{
let t = self.value.replace_with(f);
self.transmit();
t
}
pub fn recv(&self) -> &Receiver<T> {
&self.recv
}
}
impl<T: Clone + Default + 'static> Model<T> {
pub fn take(&self) -> T {
let new_t = Default::default();
self.replace(new_t)
}
}