-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathregex.rs
81 lines (72 loc) · 2.13 KB
/
regex.rs
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
use regex::{Regex, RegexBuilder};
use std::sync::Arc;
#[derive(Debug, Clone)]
pub struct LazyRegex {
pub(crate) original: String,
pub(crate) regex: String,
pub(crate) compiled: Option<Arc<Regex>>,
pub(crate) ignore_case: bool,
}
impl LazyRegex {
#[cfg(feature = "router")]
pub fn new_node(regex: String, ignore_case: bool) -> LazyRegex {
LazyRegex {
regex: if regex.is_empty() {
".*".to_string()
} else {
["^", regex.as_str()].join("")
},
original: regex,
compiled: None,
ignore_case,
}
}
pub fn new_leaf(regex: &str, ignore_case: bool) -> LazyRegex {
LazyRegex {
regex: ["^", regex, "$"].join(""),
original: regex.to_string(),
compiled: None,
ignore_case,
}
}
#[cfg(feature = "router")]
pub fn is_match(&self, value: &str) -> bool {
match &self.compiled {
Some(regex) => regex.is_match(value),
None => {
if self.original.is_empty() {
true
} else {
match self.create_regex() {
None => false,
Some(regex) => regex.is_match(value),
}
}
}
}
}
pub fn regex(&self) -> Option<Arc<Regex>> {
match &self.compiled {
Some(regex) => Some(regex.clone()),
None => self.create_regex(),
}
}
pub fn create_regex(&self) -> Option<Arc<Regex>> {
match RegexBuilder::new(self.regex.as_str()).case_insensitive(self.ignore_case).build() {
Ok(regex) => Some(Arc::new(regex)),
Err(e) => {
tracing::error!("cannot create regex: {:?}", e);
None
}
}
}
pub fn compile(&self) -> Self {
let compiled = self.create_regex();
LazyRegex {
regex: self.regex.clone(),
original: self.original.clone(),
compiled,
ignore_case: self.ignore_case,
}
}
}