๐Ÿ“ฆ da-x / vmess

๐Ÿ“„ filter.rs ยท 61 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61use crate::Error;

#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub enum VMState {
    Running,
    Stopped,
}

#[derive(Debug)]
pub enum Expr {
    Substring(String),
    State(VMState),
    All,
    Not(Box<Expr>),
    And(Box<Expr>, Box<Expr>),
    Or(Box<Expr>, Box<Expr>),
}

pub struct MatchInfo<'a> {
    pub vm_state: Option<VMState>,
    pub name: &'a str,
}

impl Expr {
    pub fn parse_cmd(expr: &[String]) -> Result<Self, Error> {
        if expr.len() == 0 {
            return Ok(Expr::All)
        }

        let owner = expr.join(" ");
        match super::expr::topParser::new().parse(owner.as_str()) {
            Ok(s) => Ok(s),
            Err(e) => Err(Error::FilterParseError(format!("{}", e))),
        }
    }

    pub fn multiple(mut multiple: Vec<Expr>) -> Self {
        let mut v = multiple.pop().unwrap();
        while let Some(s) = multiple.pop() {
            v = Expr::And(Box::new(s), Box::new(v))
        }

        v
    }

    pub fn match_info(&self, info: &MatchInfo) -> bool {
        match self {
            Expr::Substring(substr) => {
                return info.name.contains(substr);
            },
            Expr::State(state) => {
                return info.vm_state == Some(*state);
            }
            Expr::All => true,
            Expr::Not(a) => !a.match_info(info),
            Expr::And(a, b) => a.match_info(info) && b.match_info(info),
            Expr::Or(a, b) => a.match_info(info) || b.match_info(info),
        }
    }
}