use crate::value::Value;
use regex::Regex;
use std::collections::HashMap;
thread_local! {
static REGEX_MEMO: std::cell::RefCell<HashMap<String, Option<Regex>>> =
std::cell::RefCell::new(HashMap::new());
}
pub(crate) fn compiled_regex(pattern: &str) -> Option<Regex> {
REGEX_MEMO.with(|m| {
let mut m = m.borrow_mut();
if let Some(re) = m.get(pattern) {
return re.clone();
}
if m.len() >= 4_096 {
m.clear();
}
let re = Regex::new(pattern).ok();
m.insert(pattern.to_string(), re.clone());
re
})
}
pub(crate) fn regex_test(a: &Value, b: &Value, want: bool) -> bool {
if matches!(a, Value::Null) || matches!(b, Value::Null) {
return !want;
}
match compiled_regex(&b.to_string()) {
Some(re) => re.is_match(&a.to_string()) == want,
None => false,
}
}