1pub mod json;
2
3use json::Json;
4use std::{
5 fmt::Debug,
6 ops::{Deref, DerefMut},
7 sync::{Arc, Mutex},
8};
9
10#[derive(Debug, Clone)]
11pub struct RJson(Arc<Mutex<Json>>);
12
13impl From<RJson> for Json {
14 fn from(value: RJson) -> Self {
15 let json = value.0.lock().unwrap();
16 (*json).clone()
17 }
18}
19impl From<Json> for RJson {
20 fn from(value: Json) -> Self {
21 Self(Arc::new(Mutex::new(value)))
22 }
23}
24impl From<serde_json::Value> for RJson {
25 fn from(value: serde_json::Value) -> Self {
26 let json: Json = value.into();
27 json.into()
28 }
29}
30impl From<RJson> for serde_json::Value {
31 fn from(value: RJson) -> Self {
32 let json: Json = value.into();
33 json.into()
34 }
35}
36
37impl Deref for RJson {
38 type Target = Arc<Mutex<Json>>;
39 fn deref(&self) -> &Self::Target {
40 &self.0
41 }
42}
43impl DerefMut for RJson {
44 fn deref_mut(&mut self) -> &mut Self::Target {
45 &mut self.0
46 }
47}
48
49impl core::hash::Hash for RJson {
50 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
51 self.get_json_ptr_address().hash(state);
52 }
53}
54impl PartialEq for RJson {
55 fn eq(&self, other: &Self) -> bool {
56 self.get_json_ptr_address() == other.get_json_ptr_address()
57 }
58}
59impl Eq for RJson {}
60
61impl RJson {
62 pub fn new<T: Into<Json>>(value: T) -> Self {
63 let json: Json = value.into();
64 Self(Arc::new(Mutex::new(json)))
65 }
66 pub fn get_json_ptr_address(&self) -> usize {
67 let json = self.0.lock().unwrap();
68 json.get_ptr_address()
69 }
70 pub fn index<I: json::Index>(&self, index: I) -> RJson {
71 let json = self.0.lock().unwrap();
72 json[index].clone()
73 }
74 pub fn get<I: json::Index + ToString + Clone>(&self, index: I) -> RJson {
75 crate::effect::Effect::track(self.get_json_ptr_address(), &index);
77 self.index(&index)
78 }
79 pub fn set<I: json::Index + ToString + Clone + Debug, V: Into<serde_json::Value>>(&self, index: I, value: V) {
80 let value: serde_json::Value = value.into();
81 let value: RJson = value.into();
82 self.0.lock().unwrap().set(&index, value);
83 crate::effect::Effect::trigger(self.get_json_ptr_address(), &index);
84 }
85}