grit_pattern_matcher/
constant.rs

1use std::fmt::Display;
2
3#[derive(Debug, Clone)]
4pub enum Constant {
5    Boolean(bool),
6    String(String),
7    Integer(i64),
8    Float(f64),
9    Undefined,
10}
11
12impl Constant {
13    pub fn is_truthy(&self) -> bool {
14        match self {
15            Constant::Integer(i) => *i != 0,
16            Constant::Float(d) => *d != 0.0,
17            Constant::Boolean(b) => *b,
18            Constant::String(s) => !s.is_empty(),
19            Constant::Undefined => false,
20        }
21    }
22
23    pub fn is_undefined(&self) -> bool {
24        matches!(self, Self::Undefined)
25    }
26}
27
28impl Display for Constant {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        match self {
31            Constant::Boolean(b) => write!(f, "{}", b),
32            Constant::String(s) => write!(f, "{}", s),
33            Constant::Integer(n) => write!(f, "{}", n),
34            Constant::Float(n) => write!(f, "{}", n),
35            Constant::Undefined => write!(f, ""),
36        }
37    }
38}
39
40impl PartialEq for Constant {
41    fn eq(&self, other: &Self) -> bool {
42        match (self, other) {
43            (Constant::Boolean(b1), Constant::Boolean(b2)) => b1 == b2,
44            (Constant::String(s1), Constant::String(s2)) => s1 == s2,
45            (Constant::Integer(n1), Constant::Integer(n2)) => n1 == n2,
46            (Constant::Float(n1), Constant::Float(n2)) => n1 == n2,
47            _ => false,
48        }
49    }
50}