Skip to main content

teaql_tool_std/
filter.rs

1use aho_corasick::AhoCorasick;
2
3pub struct FilterTool;
4
5impl FilterTool {
6    pub fn new() -> Self {
7        Self
8    }
9
10    pub fn build_trie<I, P>(&self, patterns: I) -> AhoCorasick
11    where
12        I: IntoIterator<Item = P>,
13        P: AsRef<[u8]>,
14    {
15        AhoCorasick::new(patterns).unwrap()
16    }
17
18    pub fn contains_sensitive(&self, text: &str, trie: &AhoCorasick) -> bool {
19        trie.is_match(text)
20    }
21
22    pub fn replace_sensitive(&self, text: &str, trie: &AhoCorasick, replacement: &str) -> String {
23        let mut result = String::with_capacity(text.len());
24        let mut last_match = 0;
25        for mat in trie.find_iter(text) {
26            result.push_str(&text[last_match..mat.start()]);
27            result.push_str(replacement);
28            last_match = mat.end();
29        }
30        result.push_str(&text[last_match..]);
31        result
32    }
33}
34
35impl Default for FilterTool {
36    fn default() -> Self {
37        Self::new()
38    }
39}