mod regex;
mod simple;
use std::fmt;
#[derive(Debug)]
pub enum PatternError {
#[cfg(feature = "regex")]
InvalidSyntax(String),
#[doc(hidden)]
_Unreachable,
}
impl fmt::Display for PatternError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
#[cfg(feature = "regex")]
PatternError::InvalidSyntax(msg) => write!(f, "invalid filter pattern: {msg}"),
PatternError::_Unreachable => {
write!(
f,
"(unreachable — PatternError constructed on no-regex path)"
)
}
}
}
}
pub(crate) trait PatternMatcher {
fn matches(&self, target: &str) -> bool;
}
pub(crate) struct Pattern(Box<dyn PatternMatcher>);
impl Pattern {
#[allow(clippy::unnecessary_wraps)]
pub(crate) fn new(pattern: &str) -> Result<Self, PatternError> {
#[cfg(feature = "regex")]
{
let compiled = if pattern.is_empty() { "^$" } else { pattern };
regex::RegexMatcher::new(compiled)
.map(|m| Pattern(Box::new(m)))
.map_err(PatternError::InvalidSyntax)
}
#[cfg(not(feature = "regex"))]
{
Ok(Pattern(Box::new(simple::SimpleMatcher::new(pattern))))
}
}
pub(crate) fn matches(&self, target: &str) -> bool {
self.0.matches(target)
}
}