dd_sds/scanner/regex_rule/
regex_cache_store.rs

1use crate::SharedPool;
2use crate::scanner::regex_rule::regex_store::{RegexCacheKey, SharedRegex};
3use lazy_static::lazy_static;
4use regex_automata::meta::Regex as MetaRegex;
5use slotmap::SecondaryMap;
6use std::sync::Arc;
7extern crate num_cpus;
8
9lazy_static! {
10    static ref REGEX_CACHE_STORE: Arc<SharedPool<Box<RegexCaches>>> = Arc::new(SharedPool::new(
11        Box::new(|| Box::new(RegexCaches::new())),
12        num_cpus::get()
13    ));
14}
15
16pub fn access_regex_caches<T>(func: impl FnOnce(&mut RegexCaches) -> T) -> T {
17    // This function isn't strictly necessary, but it makes it easier to change the implementation
18    // later
19    let mut caches = REGEX_CACHE_STORE.get();
20    func(caches.get_ref())
21}
22
23pub struct RegexCaches {
24    map: SecondaryMap<RegexCacheKey, RegexCacheValue>,
25}
26
27pub struct RegexCacheValue {
28    pub cache: regex_automata::meta::Cache,
29    pub captures: regex_automata::util::captures::Captures,
30}
31
32impl RegexCaches {
33    pub fn new() -> Self {
34        Self {
35            map: SecondaryMap::new(),
36        }
37    }
38
39    pub fn get(&mut self, shared_regex: &SharedRegex) -> &mut RegexCacheValue {
40        self.raw_get(shared_regex.cache_key, &shared_regex.regex)
41    }
42
43    pub(super) fn raw_get(
44        &mut self,
45        key: RegexCacheKey,
46        regex: &MetaRegex,
47    ) -> &mut RegexCacheValue {
48        self.map
49            .entry(key)
50            .unwrap()
51            .or_insert_with(|| RegexCacheValue {
52                cache: regex.create_cache(),
53                captures: regex.create_captures(),
54            })
55    }
56}