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