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
use crate::state_functions::*;
use std::marker::PhantomData;
pub struct StateAccess<T> {
pub id: topo::Id,
_phantom_data: PhantomData<T>,
}
impl<T> std::fmt::Debug for StateAccess<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "({:#?})", self.id)
}
}
impl<T> Copy for StateAccess<T> {}
impl<T> Clone for StateAccess<T> {
fn clone(&self) -> StateAccess<T> {
StateAccess::<T> {
id: self.id,
_phantom_data: PhantomData::<T>,
}
}
}
impl<T> StateAccess<T>
where
T: 'static,
{
pub fn new(id: topo::Id) -> StateAccess<T> {
StateAccess {
id,
_phantom_data: PhantomData,
}
}
pub fn set(self, value: T) {
set_state_with_topo_id(value, self.id);
}
pub fn remove(self) -> Option<T> {
remove_state_with_topo_id(self.id)
}
pub fn delete(self) {
self.remove();
}
pub fn reset_on_drop(self) -> Self {
use_drop_type(move || self.delete());
self
}
pub fn update<F: FnOnce(&mut T) -> ()>(self, func: F) {
update_state_with_topo_id(self.id, func);
}
pub fn state_exists(self) -> bool {
state_exists_for_topo_id::<T>(self.id)
}
pub fn get_with<F: FnOnce(&T) -> R, R>(self, func: F) -> R {
read_state_with_topo_id(self.id, func)
}
}
pub trait CloneState<T>
where
T: Clone + 'static,
{
fn get(&self) -> T;
fn soft_get(&self) -> Option<T>;
}
impl<T> CloneState<T> for StateAccess<T>
where
T: Clone + 'static,
{
fn get(&self) -> T {
clone_state_with_topo_id::<T>(self.id).expect("state should be present")
}
fn soft_get(&self) -> Option<T> {
clone_state_with_topo_id::<T>(self.id)
}
}
#[derive(Clone)]
struct ChangedWrapper<T>(T);
pub trait ChangedState {
fn changed(&self) -> bool;
}
impl<T> ChangedState for StateAccess<T>
where
T: Clone + 'static + PartialEq,
{
fn changed(&self) -> bool {
if let Some(old_state) = clone_state_with_topo_id::<ChangedWrapper<T>>(self.id) {
old_state.0 != self.get()
} else {
set_state_with_topo_id(ChangedWrapper(self.get()), self.id);
true
}
}
}
impl<T> std::fmt::Display for StateAccess<T>
where
T: std::fmt::Display + 'static,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.get_with(|t| format!("{}", t)))
}
}
use std::ops::Add;
impl<T> Add for StateAccess<T>
where
T: Copy + Add<Output = T> + 'static,
{
type Output = T;
fn add(self, other: Self) -> Self::Output {
self.get_with(|s| other.get_with(|o| *o + *s))
}
}