Skip to main content

hamelin_lib/
operator.rs

1use anyhow::bail;
2use std::fmt::Display;
3
4/// Hamelin language operators.
5/// Display returns the Hamelin syntax representation.
6/// For SQL syntax, convert to Operator using TryFrom.
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub enum Operator {
9    Minus,
10    Plus,
11    Concat,
12    Asterisk,
13    Slash,
14    Percent,
15    Eq,
16    Neq,
17    Lt,
18    Lte,
19    Gt,
20    Gte,
21    Not,
22    And,
23    Or,
24    In,
25    NotIn,
26    Is,
27    IsNot,
28    Like,
29    Range,
30}
31
32impl Operator {
33    /// Parse from Hamelin syntax
34    pub fn of(expression: &str) -> anyhow::Result<Self> {
35        match expression {
36            "-" => Ok(Self::Minus),
37            "+" => Ok(Self::Plus),
38            "||" => Ok(Self::Concat),
39            "*" => Ok(Self::Asterisk),
40            "/" => Ok(Self::Slash),
41            "%" => Ok(Self::Percent),
42            "==" => Ok(Self::Eq),
43            "!=" => Ok(Self::Neq),
44            "<>" => Ok(Self::Neq),
45            "<" => Ok(Self::Lt),
46            "<=" => Ok(Self::Lte),
47            ">" => Ok(Self::Gt),
48            ">=" => Ok(Self::Gte),
49            "NOT" => Ok(Self::Not),
50            "AND" => Ok(Self::And),
51            "OR" => Ok(Self::Or),
52            "IN" => Ok(Self::In),
53            "NOT IN" => Ok(Self::NotIn),
54            "IS" => Ok(Self::Is),
55            "IS NOT" => Ok(Self::IsNot),
56            "LIKE" => Ok(Self::Like),
57            ".." => Ok(Self::Range),
58            _ => bail!("Unknown operator: {}", expression),
59        }
60    }
61
62    pub fn str(&self) -> &'static str {
63        match self {
64            Self::Minus => "-",
65            Self::Plus => "+",
66            Self::Concat => "||",
67            Self::Asterisk => "*",
68            Self::Slash => "/",
69            Self::Percent => "%",
70            Self::Eq => "==",
71            Self::Neq => "!=",
72            Self::Lt => "<",
73            Self::Lte => "<=",
74            Self::Gt => ">",
75            Self::Gte => ">=",
76            Self::Not => "NOT",
77            Self::And => "AND",
78            Self::Or => "OR",
79            Self::In => "IN",
80            Self::NotIn => "NOT IN",
81            Self::Is => "IS",
82            Self::IsNot => "IS NOT",
83            Self::Like => "LIKE",
84            Self::Range => "..",
85        }
86    }
87}
88
89/// Display returns Hamelin syntax
90impl Display for Operator {
91    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92        write!(f, "{}", self.str())
93    }
94}