Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 34 additions & 8 deletions src/regex_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,38 @@ where
)
}

fn compile_regex_pattern(pattern: &str) -> Result<BytesRegex, regex::Error> {
BytesRegexBuilder::new(pattern).unicode(false).build()
}

fn compile_regex_set(patterns: Vec<String>, discard_invalid_patterns: bool) -> CompiledRegex {
match BytesRegexSetBuilder::new(&patterns).unicode(false).build() {
Ok(compiled) => CompiledRegex::CompiledSet(compiled),
Err(e) if discard_invalid_patterns => {
let valid_patterns: Vec<_> = patterns
.into_iter()
.filter(|pattern| compile_regex_pattern(pattern).is_ok())
.collect();

match valid_patterns.len() {
0 => CompiledRegex::RegexParsingError(e),
1 => match compile_regex_pattern(&valid_patterns[0]) {
Ok(compiled) => CompiledRegex::Compiled(compiled),
Err(e) => CompiledRegex::RegexParsingError(e),
},
_ => match BytesRegexSetBuilder::new(valid_patterns)
.unicode(false)
.build()
{
Ok(compiled) => CompiledRegex::CompiledSet(compiled),
Err(e) => CompiledRegex::RegexParsingError(e),
},
}
}
Err(e) => CompiledRegex::RegexParsingError(e),
}
}

/// Compiles a filter pattern to a regex. This is only performed *lazily* for
/// filters containing at least a * or ^ symbol. Because Regexes are expansive,
/// we try to convert some patterns to plain filters.
Expand Down Expand Up @@ -218,21 +250,15 @@ where
CompiledRegex::MatchAll
} else if escaped_patterns.len() == 1 {
let pattern = &escaped_patterns[0];
match BytesRegexBuilder::new(pattern).unicode(false).build() {
match compile_regex_pattern(pattern) {
Ok(compiled) => CompiledRegex::Compiled(compiled),
Err(e) => {
// println!("Regex parsing failed ({:?})", e);
CompiledRegex::RegexParsingError(e)
}
}
} else {
match BytesRegexSetBuilder::new(escaped_patterns)
.unicode(false)
.build()
{
Ok(compiled) => CompiledRegex::CompiledSet(compiled),
Err(e) => CompiledRegex::RegexParsingError(e),
}
compile_regex_set(escaped_patterns, is_complete_regex)
}
}

Expand Down
17 changes: 17 additions & 0 deletions tests/unit/regex_manager.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,20 @@
#[cfg(test)]
mod compile_tests {
use crate::regex_manager::compile_regex;

#[test]
fn invalid_complete_regex_does_not_disable_valid_pattern_in_set() {
let compiled = compile_regex(
[r#"/^https:\/\/b\.com/"#, r#"/(?=a)/"#].into_iter(),
false,
false,
true,
);

assert!(compiled.is_match("https://b.com"));
}
}

#[cfg(all(test, feature = "debug-info"))]
mod tests {
use super::super::*;
Expand Down