zen_types/variable_type/
conv.rs1use crate::variable_type::VariableType;
2use serde_json::Value;
3use std::borrow::Cow;
4use std::cell::RefCell;
5use std::ops::Deref;
6use std::rc::Rc;
7
8impl<'a> From<Cow<'a, Value>> for VariableType {
9 fn from(value: Cow<'a, Value>) -> Self {
10 match value.deref() {
11 Value::Null => VariableType::Null,
12 Value::Bool(_) => VariableType::Bool,
13 Value::Number(_) => VariableType::Number,
14 Value::String(_) => VariableType::String,
15 Value::Array(_) => {
16 let Value::Array(arr) = value.into_owned() else {
17 panic!("unexpected type of value, expected array");
18 };
19
20 VariableType::from(arr)
21 }
22 Value::Object(_) => {
23 let Value::Object(obj) = value.into_owned() else {
24 panic!("unexpected type of value, expected object");
25 };
26
27 VariableType::Object(Rc::new(RefCell::new(
28 obj.into_iter()
29 .map(|(k, v)| (Rc::from(k.as_str()), v.into()))
30 .collect(),
31 )))
32 }
33 }
34 }
35}
36
37impl From<Value> for VariableType {
38 fn from(value: Value) -> Self {
39 VariableType::from(Cow::Owned(value)).into()
40 }
41}
42
43impl From<&Value> for VariableType {
44 fn from(value: &Value) -> Self {
45 VariableType::from(Cow::Borrowed(value)).into()
46 }
47}
48
49impl From<Vec<Value>> for VariableType {
50 fn from(arr: Vec<Value>) -> Self {
51 if arr.len() == 0 {
52 return VariableType::Array(Rc::new(VariableType::Any));
53 }
54
55 let result_type = arr
56 .into_iter()
57 .fold(None, |acc: Option<VariableType>, b| match acc {
58 Some(a) => Some(a.merge(&VariableType::from(b))),
59 None => Some(VariableType::from(b)),
60 });
61
62 VariableType::Array(Rc::new(result_type.unwrap_or(VariableType::Any)))
63 }
64}
65
66impl From<&Vec<Value>> for VariableType {
67 fn from(arr: &Vec<Value>) -> Self {
68 if arr.len() == 0 {
69 return VariableType::Array(Rc::new(VariableType::Any));
70 }
71
72 let result_type = arr
73 .iter()
74 .fold(None, |acc: Option<VariableType>, b| match acc {
75 Some(a) => Some(a.merge(&VariableType::from(b))),
76 None => Some(VariableType::from(b)),
77 });
78
79 VariableType::Array(Rc::new(result_type.unwrap_or(VariableType::Any)))
80 }
81}