summaryrefslogtreecommitdiff
path: root/libbindgen/src/regex_set.rs
blob: 8747d285ddc1bdae78548b71c5e6e45763746484 (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
59
60
61
62
63
64
65
66
//! A type that represents the union of a set of regular expressions.

use regex::Regex;
use std::borrow::Borrow;

// Yeah, I'm aware this is sorta crappy, should be cheaper to compile a regex
// ORing all the patterns, I guess...

/// A dynamic set of regular expressions.
#[derive(Debug)]
pub struct RegexSet {
    items: Vec<Regex>,
}

impl RegexSet {
    /// Is this set empty?
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// Extend this set with every regex in the iterator.
    pub fn extend<I>(&mut self, iter: I)
        where I: IntoIterator<Item = String>,
    {
        for s in iter.into_iter() {
            self.insert(&s)
        }
    }

    /// Insert a new regex into this set.
    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) => {
                warn!("Invalid pattern provided: {}, {:?}", s, err);
            }
        }
    }

    /// Does the given `string` match any of the regexes in this set?
    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![],
        }
    }
}