reactive_graph_graph/instances/properties/
property_instance.rs

1use std::collections::BTreeMap;
2use std::hash::Hash;
3use std::hash::Hasher;
4use std::ops::Deref;
5use std::ops::DerefMut;
6
7use dashmap::DashMap;
8use dashmap::DashSet;
9use schemars::JsonSchema;
10use schemars::Schema;
11use schemars::SchemaGenerator;
12use schemars::json_schema;
13use serde::Deserialize;
14use serde::Serialize;
15use serde_json::Map;
16use serde_json::Value;
17use std::borrow::Cow;
18
19use crate::HashableValue;
20use crate::MutablePropertyInstanceSetter;
21use crate::PropertyInstanceGetter;
22use crate::PropertyTypes;
23
24#[cfg(any(test, feature = "test"))]
25use crate::test_utils::default_from::DefaultFrom;
26#[cfg(any(test, feature = "test"))]
27use default_test::DefaultTest;
28#[cfg(any(test, feature = "test"))]
29use rand::Rng;
30#[cfg(any(test, feature = "test"))]
31use reactive_graph_utils_test::r_string;
32#[cfg(any(test, feature = "test"))]
33use serde_json::json;
34
35pub struct ContainerPropertyInstance<IdType: Clone> {
36    /// Id of the container
37    pub id: IdType,
38
39    /// Property name
40    pub name: String,
41
42    /// Store the current value
43    pub value: Value,
44}
45
46impl<IdType: Clone> ContainerPropertyInstance<IdType> {
47    pub fn new<N: Into<String>>(id: IdType, name: N, value: Value) -> Self {
48        ContainerPropertyInstance { id, name: name.into(), value }
49    }
50}
51
52pub type PropertyNames = DashSet<String>;
53
54/// Container for property instances.
55/// PropertyInstances exposes all functionality from the underlying DashMap<String, Value>.
56#[derive(Clone, Debug, Default, Serialize, Deserialize)]
57pub struct PropertyInstances(DashMap<String, Value>);
58
59impl PropertyInstances {
60    /// Creates an empty map of property instances.
61    pub fn new() -> Self {
62        PropertyInstances(DashMap::new())
63    }
64
65    /// Creates property instances from a property type and initializes the values with the
66    /// default values of the data type of the property.
67    pub fn new_from_property_types_with_defaults(property_types: &PropertyTypes) -> Self {
68        let properties = Self::new();
69        for property_type in property_types.iter() {
70            properties.insert(property_type.key().clone(), property_type.data_type.default_value());
71        }
72        properties
73    }
74
75    /// Add or replace property instance with the given name.
76    /// Consumes and returns self (builder style).
77    pub fn property<N: Into<String>, V: Into<Value>>(self, name: N, value: V) -> Self {
78        self.insert(name.into(), value.into());
79        self
80    }
81
82    /// Returns all property names.
83    pub fn names(&self) -> PropertyNames {
84        self.iter().map(|property| property.key().clone()).collect()
85    }
86
87    // TODO: pub fn validate(&self) -> Result<(), PropertyInstancesValidationError> {}
88
89    /// Returns a sorted list of property instances.
90    pub fn to_map(&self) -> BTreeMap<String, Value> {
91        self.0.iter().map(|property| (property.key().clone(), property.value().clone())).collect()
92        // let mut tys: HashMap<String, Value> = self.0.iter().map(|ty| ty.clone()).collect();
93        // tys.sort();
94        // tys
95    }
96}
97
98impl PropertyInstanceGetter for PropertyInstances {
99    fn get(&self, property_name: &str) -> Option<Value> {
100        self.0.get(property_name).map(|property| property.value().clone())
101    }
102
103    fn as_bool(&self, property_name: &str) -> Option<bool> {
104        self.0.get(property_name).and_then(|p| p.as_bool())
105    }
106
107    fn as_u64(&self, property_name: &str) -> Option<u64> {
108        self.0.get(property_name).and_then(|p| p.as_u64())
109    }
110
111    fn as_i64(&self, property_name: &str) -> Option<i64> {
112        self.0.get(property_name).and_then(|p| p.as_i64())
113    }
114
115    fn as_f64(&self, property_name: &str) -> Option<f64> {
116        self.0.get(property_name).and_then(|p| p.as_f64())
117    }
118
119    fn as_string(&self, property_name: &str) -> Option<String> {
120        self.0.get(property_name).and_then(|p| p.as_str().map(|s| s.to_string()))
121    }
122
123    fn as_array(&self, property_name: &str) -> Option<Vec<Value>> {
124        self.0.get(property_name).and_then(|p| p.as_array().cloned())
125    }
126
127    fn as_object(&self, property_name: &str) -> Option<Map<String, Value>> {
128        self.0.get(property_name).and_then(|p| p.as_object().cloned())
129    }
130}
131
132impl MutablePropertyInstanceSetter for PropertyInstances {
133    fn set<S: Into<String>>(&mut self, property_name: S, value: Value) {
134        if let Some(mut property_value) = self.0.get_mut(&property_name.into()) {
135            let v = property_value.value_mut();
136            *v = value;
137        }
138    }
139}
140
141impl Deref for PropertyInstances {
142    type Target = DashMap<String, Value>;
143
144    fn deref(&self) -> &Self::Target {
145        &self.0
146    }
147}
148
149impl DerefMut for PropertyInstances {
150    fn deref_mut(&mut self) -> &mut Self::Target {
151        &mut self.0
152    }
153}
154
155impl IntoIterator for PropertyInstances {
156    type Item = (String, Value);
157    type IntoIter = dashmap::iter::OwningIter<String, Value>;
158    fn into_iter(self) -> Self::IntoIter {
159        self.0.into_iter()
160    }
161}
162
163impl PartialEq for PropertyInstances {
164    fn eq(&self, other: &Self) -> bool {
165        let this = self.to_map();
166        let other = other.to_map();
167        this.eq(&other)
168    }
169}
170
171impl Eq for PropertyInstances {}
172
173impl Hash for PropertyInstances {
174    fn hash<H: Hasher>(&self, hasher: &mut H) {
175        self.iter().for_each(|property| {
176            property.key().hash(hasher);
177            HashableValue(property.value()).hash(hasher);
178        });
179    }
180}
181
182impl JsonSchema for PropertyInstances {
183    fn schema_name() -> Cow<'static, str> {
184        "PropertyInstances".into()
185    }
186
187    fn json_schema(_: &mut SchemaGenerator) -> Schema {
188        json_schema!({
189            "type": "object",
190            "description": "Properties",
191        })
192    }
193}
194
195// impl From<HashMap<String, Value>> for PropertyInstances {
196//     fn from(tys: HashMap<String, Value>) -> Self {
197//         PropertyInstances(tys.into_iter().collect())
198//     }
199// }
200//
201// impl From<PropertyInstances> for HashMap<String, Value> {
202//     fn from(tys: PropertyInstances) -> Self {
203//         tys.to_map()
204//     }
205// }
206
207impl From<BTreeMap<String, Value>> for PropertyInstances {
208    fn from(tys: BTreeMap<String, Value>) -> Self {
209        PropertyInstances(tys.into_iter().collect())
210    }
211}
212
213impl From<PropertyInstances> for BTreeMap<String, Value> {
214    fn from(tys: PropertyInstances) -> Self {
215        tys.to_map()
216    }
217}
218
219impl From<&PropertyInstances> for BTreeMap<String, Value> {
220    fn from(tys: &PropertyInstances) -> Self {
221        tys.0.iter().map(|ty| (ty.key().clone(), ty.value().clone())).collect()
222    }
223}
224
225impl From<DashMap<String, Value>> for PropertyInstances {
226    fn from(tys: DashMap<String, Value>) -> Self {
227        PropertyInstances(tys)
228    }
229}
230
231impl From<&DashMap<String, Value>> for PropertyInstances {
232    fn from(tys: &DashMap<String, Value>) -> Self {
233        PropertyInstances(tys.clone())
234    }
235}
236
237impl From<PropertyInstances> for DashMap<String, Value> {
238    fn from(tys: PropertyInstances) -> Self {
239        tys.0
240    }
241}
242
243// impl From<PropertyInstances> for HashMap<String, Value> {
244//     fn from(property_instances: PropertyInstances) -> Self {
245//         property_instances.0.into_iter().collect::<HashMap<String, Value>>()
246//     }
247// }
248
249impl FromIterator<(String, Value)> for PropertyInstances {
250    fn from_iter<I: IntoIterator<Item = (String, Value)>>(iter: I) -> Self {
251        let properties = PropertyInstances::new();
252        for (property_name, property_value) in iter {
253            properties.insert(property_name, property_value);
254        }
255        properties
256    }
257}
258
259#[cfg(any(test, feature = "test"))]
260impl DefaultTest for PropertyInstances {
261    fn default_test() -> Self {
262        let property_instances = PropertyInstances::new();
263        let mut rng = rand::rng();
264        for _ in 0..rng.random_range(0..10) {
265            property_instances.insert(r_string(), json!(r_string()));
266        }
267        property_instances
268    }
269}
270
271#[cfg(any(test, feature = "test"))]
272impl DefaultFrom<&PropertyTypes> for PropertyInstances {
273    fn default_from(property_types: &PropertyTypes) -> Self {
274        let properties = Self::new();
275        for property_type in property_types.iter() {
276            properties.insert(property_type.key().clone(), property_type.data_type.default_value_test());
277        }
278        properties
279    }
280}
281
282#[cfg(test)]
283mod tests {
284    // TODO: implement tests
285}