use regex;
pub struct UrlMatcher {
urls: Vec<&'static str>,
url_pattern: Vec<regex::Regex>,
match_set: regex::RegexSet,
}
impl UrlMatcher {
pub fn new() -> UrlMatcher {
UrlMatcher {
urls: Vec::new(),
url_pattern: Vec::new(),
match_set: regex::RegexSet::new(&[""]).unwrap(),
}
}
pub fn add_url(&mut self, url: &'static str) {
self.urls.push(url);
self.url_pattern.push(regex::Regex::new(url).unwrap());
self.match_set = regex::RegexSet::new(self.urls.as_slice()).unwrap()
}
pub fn gen_url_regex_set(&self) -> regex::RegexSet {
regex::RegexSet::new(self.urls.as_slice()).unwrap()
}
pub fn match_url<'a>(
&'a self,
url: &str,
) -> Result<(&'a regex::Regex, &'static str), &'static str> {
let matches: Vec<_> = self.match_set.matches(url).into_iter().collect();
match matches.is_empty() {
true => Err(""),
false => {
let index = matches[0];
Ok((&self.url_pattern[index], self.urls[index]))
}
}
}
}