zen_expression/variable/types/
mod.rs

1mod conv;
2mod util;
3
4use serde::{Deserialize, Serialize};
5use std::collections::HashMap;
6use std::fmt::Display;
7use std::hash::{Hash, Hasher};
8use std::rc::Rc;
9
10#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
11pub enum VariableType {
12    Any,
13    Null,
14    Bool,
15    String,
16    Number,
17    Constant(Rc<serde_json::Value>),
18    Array(Rc<VariableType>),
19    Object(HashMap<String, Rc<VariableType>>),
20}
21
22impl VariableType {
23    pub fn array(self) -> Self {
24        Self::Array(Rc::new(self))
25    }
26}
27
28impl Default for VariableType {
29    fn default() -> Self {
30        VariableType::Null
31    }
32}
33
34impl Display for VariableType {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        match self {
37            VariableType::Any => write!(f, "any"),
38            VariableType::Null => write!(f, "null"),
39            VariableType::Bool => write!(f, "bool"),
40            VariableType::String => write!(f, "string"),
41            VariableType::Number => write!(f, "number"),
42            VariableType::Constant(c) => write!(f, "{c}"),
43            VariableType::Array(v) => write!(f, "{v}[]"),
44            VariableType::Object(_) => write!(f, "object"),
45        }
46    }
47}
48
49impl Hash for VariableType {
50    fn hash<H: Hasher>(&self, state: &mut H) {
51        match &self {
52            VariableType::Any => 0.hash(state),
53            VariableType::Null => 1.hash(state),
54            VariableType::Bool => 2.hash(state),
55            VariableType::String => 3.hash(state),
56            VariableType::Number => 4.hash(state),
57            VariableType::Constant(c) => c.hash(state),
58            VariableType::Array(arr) => arr.hash(state),
59            VariableType::Object(obj) => {
60                let mut pairs: Vec<_> = obj.iter().collect();
61                pairs.sort_by_key(|i| i.0);
62
63                Hash::hash(&pairs, state);
64            }
65        }
66    }
67}