use regex::Regex;
fn wildcard_to_regex(pattern: &str) -> Regex {
if let Some(domain) = pattern.strip_prefix("*.") {
let regex_string = format!("^(.*\\.)?{}$", regex::escape(domain));
Regex::new(®ex_string).expect("Invalid regex")
} else {
let regex_string = "^".to_string() + ®ex::escape(pattern).replace("\\*", ".*") + "$";
Regex::new(®ex_string).expect("Invalid regex")
}
}
pub fn matches_pattern(host: &str, pattern: &str) -> bool {
let re = wildcard_to_regex(pattern);
re.is_match(host)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_wildcard_matching() {
assert!(matches_pattern("abc.discord.gg", "*.discord.gg"));
assert!(matches_pattern("xyz.discord.com", "*.discord.com"));
assert!(!matches_pattern("test.instagram.com", "*.discord.com"));
assert!(matches_pattern("discord.gg", "*.discord.gg"));
assert!(matches_pattern("example.com", "*.example.com"));
assert!(matches_pattern("exact.match", "exact.match"));
assert!(matches_pattern("test.wildcard.match", "test.*.match"));
assert!(!matches_pattern("wrong.wildcard.com", "test.*.com"));
}
}