summaryrefslogtreecommitdiff
path: root/src/regex_set.rs
blob: 20bc56bf96915798dfaac1e182b2e7d6a6ac9bf1 (plain)
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
use std::borrow::Borrow;
use regex::Regex;

// Yeah, I'm aware this is sorta crappy, should be cheaper to compile a regex
// ORing all the patterns, I guess...
#[derive(Debug)]
pub struct RegexSet {
    items: Vec<Regex>
}

impl RegexSet {
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    pub fn extend<I>(&mut self, iter: I)
        where I: IntoIterator<Item=String>
    {
        for s in iter.into_iter() {
            self.insert(&s)
        }
    }

    pub fn insert<S>(&mut self, string: &S)
        where S: Borrow<str>
    {
        let s = string.borrow();
        match Regex::new(&format!("^{}$", s)) {
            Ok(r) => {
                self.items.push(r);
            }
            Err(err) => {
                error!("Invalid pattern provided: {}, {:?}", s, err);
            }
        }
    }

    pub fn matches<S>(&self, string: &S) -> bool
        where S: Borrow<str>
    {
        let s = string.borrow();
        for r in &self.items {
            if r.is_match(s) {
                return true;
            }
        }

        false
    }
}

impl Default for RegexSet {
    fn default() -> Self {
        RegexSet {
            items: vec![],
        }
    }
}