tytanic_filter/ast/
regex.rs

1use std::fmt::Debug;
2use std::hash::Hash;
3use std::ops::Deref;
4
5/// A regex pattern literal node.
6///
7/// This implements traits such a [`Eq`] without regard for the internal
8/// structure, it purely compares by looking at the source pattern.
9#[derive(Clone)]
10pub struct Regex(pub regex::Regex);
11
12impl Regex {
13    /// Creates a new [`Regex`] from the given pattern.
14    pub fn new<S: AsRef<str>>(pat: S) -> Result<Self, regex::Error> {
15        Ok(Self(regex::Regex::new(pat.as_ref())?))
16    }
17}
18
19impl Regex {
20    /// The inner regex pattern.
21    pub fn as_regex(&self) -> &regex::Regex {
22        &self.0
23    }
24
25    /// The inner string.
26    pub fn as_str(&self) -> &str {
27        self.0.as_str()
28    }
29
30    /// Unwraps the inner regex pattern.
31    pub fn into_inner(self) -> regex::Regex {
32        self.0
33    }
34}
35
36impl Regex {
37    /// Returns true if the id matches this pattern.
38    pub fn is_match<S: AsRef<str>>(&self, id: S) -> bool {
39        self.0.is_match(id.as_ref())
40    }
41}
42
43impl Debug for Regex {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        write!(f, "\"{}\"", self.0.as_str())
46    }
47}
48
49impl PartialEq for Regex {
50    fn eq(&self, other: &Self) -> bool {
51        self.0.as_str() == other.0.as_str()
52    }
53}
54
55impl Eq for Regex {}
56
57impl Hash for Regex {
58    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
59        self.0.as_str().hash(state);
60    }
61}
62
63impl Deref for Regex {
64    type Target = regex::Regex;
65
66    fn deref(&self) -> &Self::Target {
67        self.as_regex()
68    }
69}
70
71impl AsRef<regex::Regex> for Regex {
72    fn as_ref(&self) -> &regex::Regex {
73        self.as_regex()
74    }
75}
76
77impl AsRef<str> for Regex {
78    fn as_ref(&self) -> &str {
79        self.as_str()
80    }
81}
82
83impl From<regex::Regex> for Regex {
84    fn from(value: regex::Regex) -> Self {
85        Self(value)
86    }
87}
88
89impl From<Regex> for regex::Regex {
90    fn from(value: Regex) -> Self {
91        value.into_inner()
92    }
93}