1use ahash::HashMap;
2use rust_decimal::prelude::Zero;
3use rust_decimal::Decimal;
4use serde_json::Value;
5use std::any::Any;
6use std::cell::RefCell;
7use std::collections::hash_map::Entry;
8use std::fmt::{Debug, Display, Formatter};
9use std::ops::Deref;
10use std::rc::Rc;
11
12mod conv;
13mod de;
14mod ser;
15mod types;
16
17pub use de::VariableDeserializer;
18pub use types::VariableType;
19
20pub(crate) type RcCell<T> = Rc<RefCell<T>>;
21
22pub enum Variable {
23 Null,
24 Bool(bool),
25 Number(Decimal),
26 String(Rc<str>),
27 Array(RcCell<Vec<Variable>>),
28 Object(RcCell<HashMap<Rc<str>, Variable>>),
29 Dynamic(Rc<dyn DynamicVariable>),
30}
31
32pub trait DynamicVariable: Display {
33 fn type_name(&self) -> &'static str;
34
35 fn as_any(&self) -> &dyn Any;
36
37 fn to_value(&self) -> Value;
38}
39
40impl Variable {
41 pub fn from_array(arr: Vec<Self>) -> Self {
42 Self::Array(Rc::new(RefCell::new(arr)))
43 }
44
45 pub fn from_object(obj: HashMap<Rc<str>, Self>) -> Self {
46 Self::Object(Rc::new(RefCell::new(obj)))
47 }
48
49 pub fn empty_object() -> Self {
50 Variable::Object(Default::default())
51 }
52
53 pub fn empty_array() -> Self {
54 Variable::Array(Default::default())
55 }
56
57 pub fn as_str(&self) -> Option<&str> {
58 match self {
59 Variable::String(s) => Some(s.as_ref()),
60 _ => None,
61 }
62 }
63
64 pub fn as_rc_str(&self) -> Option<Rc<str>> {
65 match self {
66 Variable::String(s) => Some(s.clone()),
67 _ => None,
68 }
69 }
70
71 pub fn as_array(&self) -> Option<RcCell<Vec<Variable>>> {
72 match self {
73 Variable::Array(arr) => Some(arr.clone()),
74 _ => None,
75 }
76 }
77
78 pub fn is_array(&self) -> bool {
79 match self {
80 Variable::Array(_) => true,
81 _ => false,
82 }
83 }
84
85 pub fn as_object(&self) -> Option<RcCell<HashMap<Rc<str>, Variable>>> {
86 match self {
87 Variable::Object(obj) => Some(obj.clone()),
88 _ => None,
89 }
90 }
91
92 pub fn is_object(&self) -> bool {
93 match self {
94 Variable::Object(_) => true,
95 _ => false,
96 }
97 }
98
99 pub fn as_bool(&self) -> Option<bool> {
100 match self {
101 Variable::Bool(b) => Some(*b),
102 _ => None,
103 }
104 }
105
106 pub fn as_number(&self) -> Option<Decimal> {
107 match self {
108 Variable::Number(n) => Some(*n),
109 _ => None,
110 }
111 }
112
113 pub fn type_name(&self) -> &'static str {
114 match self {
115 Variable::Null => "null",
116 Variable::Bool(_) => "bool",
117 Variable::Number(_) => "number",
118 Variable::String(_) => "string",
119 Variable::Array(_) => "array",
120 Variable::Object(_) => "object",
121 Variable::Dynamic(d) => d.type_name(),
122 }
123 }
124
125 pub fn dynamic<T: DynamicVariable + 'static>(&self) -> Option<&T> {
126 match self {
127 Variable::Dynamic(d) => d.as_any().downcast_ref::<T>(),
128 _ => None,
129 }
130 }
131
132 pub fn to_value(&self) -> Value {
133 Value::from(self.shallow_clone())
134 }
135
136 pub fn dot(&self, key: &str) -> Option<Variable> {
137 key.split('.')
138 .try_fold(self.shallow_clone(), |var, part| match var {
139 Variable::Object(obj) => {
140 let reference = obj.borrow();
141 reference.get(part).map(|v| v.shallow_clone())
142 }
143 _ => None,
144 })
145 }
146
147 fn dot_head(&self, key: &str) -> Option<Variable> {
148 let mut parts = Vec::from_iter(key.split('.'));
149 parts.pop();
150
151 parts
152 .iter()
153 .try_fold(self.shallow_clone(), |var, part| match var {
154 Variable::Object(obj) => {
155 let mut obj_ref = obj.borrow_mut();
156 Some(match obj_ref.entry(Rc::from(*part)) {
157 Entry::Occupied(occ) => occ.get().shallow_clone(),
158 Entry::Vacant(vac) => vac.insert(Self::empty_object()).shallow_clone(),
159 })
160 }
161 _ => None,
162 })
163 }
164 pub fn dot_remove(&self, key: &str) -> Option<Variable> {
165 let last_part = key.split('.').last()?;
166 let head = self.dot_head(key)?;
167 let Variable::Object(object_ref) = head else {
168 return None;
169 };
170
171 let mut object = object_ref.borrow_mut();
172 object.remove(last_part)
173 }
174
175 pub fn dot_insert(&self, key: &str, variable: Variable) -> Option<Variable> {
176 let last_part = key.split('.').last()?;
177 let head = self.dot_head(key)?;
178 let Variable::Object(object_ref) = head else {
179 return None;
180 };
181
182 let mut object = object_ref.borrow_mut();
183 object.insert(Rc::from(last_part), variable)
184 }
185
186 pub fn merge(&mut self, patch: &Variable) -> Variable {
187 let _ = merge_variables(self, patch, true, MergeStrategy::InPlace);
188
189 self.shallow_clone()
190 }
191
192 pub fn merge_clone(&mut self, patch: &Variable) -> Variable {
193 let mut new_self = self.shallow_clone();
194
195 let _ = merge_variables(&mut new_self, patch, true, MergeStrategy::CloneOnWrite);
196 new_self
197 }
198
199 pub fn shallow_clone(&self) -> Self {
200 match self {
201 Variable::Null => Variable::Null,
202 Variable::Bool(b) => Variable::Bool(*b),
203 Variable::Number(n) => Variable::Number(*n),
204 Variable::String(s) => Variable::String(s.clone()),
205 Variable::Array(a) => Variable::Array(a.clone()),
206 Variable::Object(o) => Variable::Object(o.clone()),
207 Variable::Dynamic(d) => Variable::Dynamic(d.clone()),
208 }
209 }
210
211 pub fn deep_clone(&self) -> Self {
212 match self {
213 Variable::Array(a) => {
214 let arr = a.borrow();
215 Variable::from_array(arr.iter().map(|v| v.deep_clone()).collect())
216 }
217 Variable::Object(o) => {
218 let obj = o.borrow();
219 Variable::from_object(
220 obj.iter()
221 .map(|(k, v)| (k.clone(), v.deep_clone()))
222 .collect(),
223 )
224 }
225 _ => self.shallow_clone(),
226 }
227 }
228
229 pub fn depth_clone(&self, depth: usize) -> Self {
230 match depth.is_zero() {
231 true => self.shallow_clone(),
232 false => match self {
233 Variable::Array(a) => {
234 let arr = a.borrow();
235 Variable::from_array(arr.iter().map(|v| v.depth_clone(depth - 1)).collect())
236 }
237 Variable::Object(o) => {
238 let obj = o.borrow();
239 Variable::from_object(
240 obj.iter()
241 .map(|(k, v)| (k.clone(), v.depth_clone(depth - 1)))
242 .collect(),
243 )
244 }
245 _ => self.shallow_clone(),
246 },
247 }
248 }
249}
250
251impl Clone for Variable {
252 fn clone(&self) -> Self {
253 self.shallow_clone()
254 }
255}
256
257#[derive(Copy, Clone)]
258enum MergeStrategy {
259 InPlace,
260 CloneOnWrite,
261}
262
263fn merge_variables(
264 doc: &mut Variable,
265 patch: &Variable,
266 top_level: bool,
267 strategy: MergeStrategy,
268) -> bool {
269 if patch.is_array() && top_level {
270 *doc = patch.shallow_clone();
271 return true;
272 }
273
274 if !patch.is_object() && top_level {
275 return false;
276 }
277
278 if doc.is_object() && patch.is_object() {
279 let doc_ref = doc.as_object().unwrap();
280 let patch_ref = patch.as_object().unwrap();
281 if Rc::ptr_eq(&doc_ref, &patch_ref) {
282 return false;
283 }
284
285 let patch = patch_ref.borrow();
286 match strategy {
287 MergeStrategy::InPlace => {
288 let mut map = doc_ref.borrow_mut();
289 for (key, value) in patch.deref() {
290 if value == &Variable::Null {
291 map.remove(key);
292 } else {
293 let entry = map.entry(key.clone()).or_insert(Variable::Null);
294 merge_variables(entry, value, false, strategy);
295 }
296 }
297
298 return true;
299 }
300 MergeStrategy::CloneOnWrite => {
301 let mut changed = false;
302 let mut new_map = None;
303
304 for (key, value) in patch.deref() {
305 let map = if let Some(ref mut m) = new_map {
307 m
308 } else {
309 let m = doc_ref.borrow().clone();
310 new_map = Some(m);
311 new_map.as_mut().unwrap()
312 };
313
314 if value == &Variable::Null {
315 if map.remove(key).is_some() {
317 changed = true;
318 }
319 } else {
320 let entry = map.entry(key.clone()).or_insert(Variable::Null);
322 if merge_variables(entry, value, false, strategy) {
323 changed = true;
324 }
325 }
326 }
327
328 if changed {
330 if let Some(new_map) = new_map {
331 *doc = Variable::Object(Rc::new(RefCell::new(new_map)));
332 }
333 return true;
334 }
335
336 return false;
337 }
338 }
339 } else {
340 let new_value = patch.shallow_clone();
341 if *doc != new_value {
342 *doc = new_value;
343 return true;
344 }
345
346 return false;
347 }
348}
349
350impl Display for Variable {
351 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
352 match self {
353 Variable::Null => write!(f, "null"),
354 Variable::Bool(b) => match *b {
355 true => write!(f, "true"),
356 false => write!(f, "false"),
357 },
358 Variable::Number(n) => write!(f, "{n}"),
359 Variable::String(s) => write!(f, "\"{s}\""),
360 Variable::Array(arr) => {
361 let arr = arr.borrow();
362 let s = arr
363 .iter()
364 .map(|v| v.to_string())
365 .collect::<Vec<String>>()
366 .join(",");
367 write!(f, "[{s}]")
368 }
369 Variable::Object(obj) => {
370 let obj = obj.borrow();
371 let s = obj
372 .iter()
373 .map(|(k, v)| format!("\"{k}\":{v}"))
374 .collect::<Vec<String>>()
375 .join(",");
376
377 write!(f, "{{{s}}}")
378 }
379 Variable::Dynamic(d) => write!(f, "{d}"),
380 }
381 }
382}
383
384impl Debug for Variable {
385 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
386 write!(f, "{}", self)
387 }
388}
389
390impl PartialEq for Variable {
391 fn eq(&self, other: &Self) -> bool {
392 match (&self, &other) {
393 (Variable::Null, Variable::Null) => true,
394 (Variable::Bool(b1), Variable::Bool(b2)) => b1 == b2,
395 (Variable::Number(n1), Variable::Number(n2)) => n1 == n2,
396 (Variable::String(s1), Variable::String(s2)) => s1 == s2,
397 (Variable::Array(a1), Variable::Array(a2)) => a1 == a2,
398 (Variable::Object(obj1), Variable::Object(obj2)) => obj1 == obj2,
399 (Variable::Dynamic(d1), Variable::Dynamic(d2)) => Rc::ptr_eq(d1, d2),
400 _ => false,
401 }
402 }
403}
404
405impl Eq for Variable {}