use std::borrow::Cow;
use std::cell::RefCell;
use std::num::NonZeroUsize;
use crate::recency::RecencySlots;
use regex::{Regex, RegexBuilder};
use relate_core::{Error, Result};
const MAX_CACHED_PATTERN_BYTES: usize = 1024;
const MAX_CACHED_PROGRAM_BYTES: usize = 256 * 1024;
const CACHED_PATTERNS: usize = 8;
struct PatternCache(RecencySlots<Slot>);
struct Slot {
pattern: Box<str>,
mode: Mode,
entry: Entry,
}
impl Slot {
fn matches(&self, pattern: &str, mode: Mode) -> bool {
self.mode == mode && &*self.pattern == pattern
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(in crate::eval) enum Mode {
Anchored,
Search,
}
enum Entry {
Compiled(Regex),
OverBudget,
}
impl PatternCache {
fn hit(&mut self, pattern: &str, mode: Mode) -> Option<&Entry> {
self.0
.hit(|slot| slot.matches(pattern, mode))
.map(|slot| &slot.entry)
}
fn insert(&mut self, pattern: &str, mode: Mode, entry: Entry) {
let _ = self.0.insert(Slot {
pattern: pattern.into(),
mode,
entry,
});
}
}
thread_local! {
static COMPILED: RefCell<PatternCache> =
const {
RefCell::new(PatternCache(RecencySlots::new(
NonZeroUsize::new(CACHED_PATTERNS).expect("a non-zero cache cap"),
)))
};
}
fn invalid_regex() -> Error {
Error::argument_error("invalid regular expression")
}
fn anchored(pattern: &str) -> String {
format!("^(?:{pattern})$")
}
fn source(pattern: &str, mode: Mode) -> Cow<'_, str> {
match mode {
Mode::Anchored => Cow::Owned(anchored(pattern)),
Mode::Search => Cow::Borrowed(pattern),
}
}
fn uncached<R>(
pattern: &str,
mode: Mode,
use_regex: impl FnOnce(&Regex) -> R,
) -> std::result::Result<R, regex::Error> {
Regex::new(&source(pattern, mode)).map(|re| use_regex(&re))
}
pub(in crate::eval) fn with_regex<R>(
pattern: &str,
mode: Mode,
use_regex: impl FnOnce(&Regex) -> R,
) -> std::result::Result<R, regex::Error> {
if pattern.len() > MAX_CACHED_PATTERN_BYTES {
return uncached(pattern, mode, use_regex);
}
COMPILED.with(|cache| {
match cache.borrow_mut().hit(pattern, mode) {
Some(Entry::Compiled(re)) => return Ok(use_regex(re)),
Some(Entry::OverBudget) => return uncached(pattern, mode, use_regex),
None => {}
}
let re = match RegexBuilder::new(&source(pattern, mode))
.size_limit(MAX_CACHED_PROGRAM_BYTES)
.dfa_size_limit(MAX_CACHED_PROGRAM_BYTES)
.build()
{
Ok(re) => re,
Err(regex::Error::CompiledTooBig(_)) => {
cache.borrow_mut().insert(pattern, mode, Entry::OverBudget);
return uncached(pattern, mode, use_regex);
}
Err(error) => return Err(error),
};
let used = use_regex(&re);
cache
.borrow_mut()
.insert(pattern, mode, Entry::Compiled(re));
Ok(used)
})
}
pub(super) fn regex_is_match(text: &str, pattern: &str) -> Result<bool> {
with_regex(pattern, Mode::Anchored, |re| re.is_match(text)).map_err(|_| invalid_regex())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn matches_the_whole_string_and_keeps_alternation_anchored() {
assert!(regex_is_match("abc", "a.c").unwrap());
assert!(!regex_is_match("21_val", "1_.*").unwrap());
assert!(regex_is_match("b", "a|b").unwrap());
assert!(!regex_is_match("bx", "a|b").unwrap());
}
#[test]
fn the_search_mode_is_keyed_apart_from_the_anchored_one() {
assert!(!regex_is_match("xabcx", "abc").unwrap());
for _ in 0..2 {
assert!(with_regex("abc", Mode::Search, |re| re.is_match("xabcx")).unwrap());
}
assert!(!regex_is_match("xabcx", "abc").unwrap());
COMPILED.with(|c| {
let table = &c.borrow().0;
assert_eq!(
table.iter().filter(|slot| &*slot.pattern == "abc").count(),
2
);
});
}
#[test]
fn a_cached_pattern_answers_like_a_fresh_one() {
for _ in 0..3 {
assert!(regex_is_match("hello", "h.*o").unwrap());
assert!(!regex_is_match("help", "h.*o").unwrap());
}
}
#[test]
fn an_invalid_pattern_is_never_cached() {
for _ in 0..3 {
assert!(regex_is_match("x", "(").is_err());
}
COMPILED.with(|c| assert!(c.borrow().0.iter().all(|slot| &*slot.pattern != "(")));
}
#[test]
fn an_over_budget_program_answers_uncached_from_the_default_limits() {
let pattern = "a{100000}";
let text = "a".repeat(100_000);
for _ in 0..2 {
assert!(regex_is_match(&text, pattern).unwrap());
}
COMPILED.with(|c| {
let table = &c.borrow().0;
assert!(table
.iter()
.filter(|slot| &*slot.pattern == pattern)
.all(|slot| matches!(slot.entry, Entry::OverBudget)));
assert_eq!(
table
.iter()
.filter(|slot| &*slot.pattern == pattern)
.count(),
1
);
});
}
#[test]
fn a_long_pattern_matches_but_is_never_cached() {
let long = format!("{}x", "a".repeat(MAX_CACHED_PATTERN_BYTES));
let text = format!("{}x", "a".repeat(MAX_CACHED_PATTERN_BYTES));
for _ in 0..3 {
assert!(regex_is_match(&text, &long).unwrap());
}
COMPILED.with(|c| {
assert!(c
.borrow()
.0
.iter()
.all(|slot| slot.pattern.len() <= MAX_CACHED_PATTERN_BYTES))
});
}
#[test]
fn a_hit_pattern_is_not_the_next_eviction_victim() {
assert!(regex_is_match("b", "a|b").unwrap());
for i in 0..(CACHED_PATTERNS - 1) {
assert!(regex_is_match("a", &format!("a|p{i}")).unwrap());
}
assert!(regex_is_match("b", "a|b").unwrap());
assert!(regex_is_match("a", "a|q").unwrap());
COMPILED.with(|c| {
let table = &c.borrow().0;
assert!(table.iter().any(|slot| &*slot.pattern == "a|b"));
assert!(table.iter().all(|slot| &*slot.pattern != "a|p0"));
assert_eq!(table.len(), CACHED_PATTERNS);
});
}
#[test]
fn the_table_stays_bounded_under_distinct_patterns() {
for i in 0..(CACHED_PATTERNS * 4) {
assert!(regex_is_match("a", &format!("a|b{i}")).unwrap());
}
COMPILED.with(|c| assert_eq!(c.borrow().0.len(), CACHED_PATTERNS));
assert!(regex_is_match("a", "a|b0").unwrap());
}
}