pub mod rumtk_search {
use crate::cache::{get_or_set_from_cache, new_cache, AHashMap, LazyRUMCache};
use crate::rumtk_cache_fetch;
use crate::strings::{CompactStringExt, RUMString};
use regex::Regex;
static mut re_cache: RegexCache = new_cache();
const DEFAULT_REGEX_CACHE_PAGE_SIZE: usize = 10;
pub type RegexCache = LazyRUMCache<RUMString, Regex>;
pub type SearchGroups = AHashMap<RUMString, RUMString>;
pub type CapturedList = Vec<RUMString>;
fn compile_regex(expr: &RUMString) -> Regex {
Regex::new(expr).unwrap()
}
pub fn string_search_named_captures(input: &str, expr: &str, default: &str) -> SearchGroups {
let re = rumtk_cache_fetch!(&mut re_cache, &RUMString::from(expr), compile_regex);
let names: Vec<&str> = re
.capture_names()
.skip(1)
.map(|x| x.unwrap_or(""))
.collect();
let mut clean_names: Vec<&str> = Vec::with_capacity(names.len());
let mut groups = SearchGroups::with_capacity(DEFAULT_REGEX_CACHE_PAGE_SIZE);
for name in &names {
if !name.is_empty() {
clean_names.push(name);
}
}
if clean_names.is_empty() {
return groups;
}
for name in &clean_names {
groups.insert(RUMString::from(name.to_string()), RUMString::from(default));
}
for cap in re.captures_iter(input).map(|c| c) {
for name in &clean_names {
let val = cap.name(name).map_or("", |s| s.as_str());
if !val.is_empty() {
groups.insert(RUMString::from(name.to_string()), RUMString::from(val));
}
}
}
groups
}
pub fn string_search_all_captures(input: &str, expr: &str, default: &str) -> CapturedList {
let re = rumtk_cache_fetch!(&mut re_cache, &RUMString::from(expr), compile_regex);
let mut capture_list = CapturedList::with_capacity(DEFAULT_REGEX_CACHE_PAGE_SIZE);
for caps in re.captures_iter(input) {
for c in caps.iter().skip(1) {
let c_str = c.unwrap().as_str();
capture_list.push(RUMString::from(c_str));
}
}
capture_list
}
pub fn string_list(input: &str, re: &Regex) -> CapturedList {
let mut list: Vec<RUMString> = Vec::with_capacity(DEFAULT_REGEX_CACHE_PAGE_SIZE);
for itm in re.find_iter(input) {
list.push(RUMString::from(itm.as_str()));
}
list
}
pub fn string_search(input: &str, expr: &str, join_pattern: &str) -> RUMString {
let re = rumtk_cache_fetch!(&mut re_cache, &RUMString::from(expr), compile_regex);
string_list(input, &re).join_compact(join_pattern)
}
}