zen_types/variable/
conv.rs1use crate::variable::Variable;
2use rust_decimal::Decimal;
3use serde_json::{Number, Value};
4use std::rc::Rc;
5
6impl From<Value> for Variable {
7 fn from(value: Value) -> Self {
8 match value {
9 Value::Null => Variable::Null,
10 Value::Bool(b) => Variable::Bool(b),
11 Value::Number(n) => Variable::Number(
12 Decimal::from_str_exact(n.as_str())
13 .or_else(|_| Decimal::from_scientific(n.as_str()))
14 .expect("Allowed number"),
15 ),
16 Value::String(s) => Variable::String(Rc::from(s.as_str())),
17 Value::Array(arr) => {
18 Variable::from_array(arr.into_iter().map(Variable::from).collect())
19 }
20 Value::Object(obj) => Variable::from_object(
21 obj.into_iter()
22 .map(|(k, v)| (Rc::from(k.as_str()), Variable::from(v)))
23 .collect(),
24 ),
25 }
26 }
27}
28
29impl From<&Value> for Variable {
30 fn from(value: &Value) -> Self {
31 match value {
32 Value::Null => Variable::Null,
33 Value::Bool(b) => Variable::Bool(*b),
34 Value::Number(n) => Variable::Number(
35 Decimal::from_str_exact(n.as_str())
36 .or_else(|_| Decimal::from_scientific(n.as_str()))
37 .expect("Allowed number"),
38 ),
39 Value::String(s) => Variable::String(Rc::from(s.as_str())),
40 Value::Array(arr) => Variable::from_array(arr.iter().map(Variable::from).collect()),
41 Value::Object(obj) => Variable::from_object(
42 obj.iter()
43 .map(|(k, v)| (Rc::from(k.as_str()), Variable::from(v)))
44 .collect(),
45 ),
46 }
47 }
48}
49
50impl From<Variable> for Value {
51 fn from(value: Variable) -> Self {
52 match value {
53 Variable::Null => Value::Null,
54 Variable::Bool(b) => Value::Bool(b),
55 Variable::Number(n) => {
56 Value::Number(Number::from_string_unchecked(n.normalize().to_string()))
57 }
58 Variable::String(s) => Value::String(s.to_string()),
59 Variable::Array(arr) => {
60 let vec = Rc::try_unwrap(arr)
61 .map(|a| a.into_inner())
62 .unwrap_or_else(|s| {
63 let borrowed = s.borrow();
64 borrowed.clone()
65 });
66
67 Value::Array(vec.into_iter().map(Value::from).collect())
68 }
69 Variable::Object(obj) => {
70 let hmap = Rc::try_unwrap(obj)
71 .map(|a| a.into_inner())
72 .unwrap_or_else(|s| {
73 let borrowed = s.borrow();
74 borrowed.clone()
75 });
76
77 Value::Object(
78 hmap.into_iter()
79 .map(|(k, v)| (k.to_string(), Value::from(v)))
80 .collect(),
81 )
82 }
83 Variable::Dynamic(d) => d.to_value(),
84 }
85 }
86}