spider_network_blocker/
trie.rs

1/// Trie node for ignore.
2#[derive(Default, Debug)]
3pub struct TrieNode {
4    #[cfg(feature = "hashbrown")]
5    /// Children for trie.
6    pub children: hashbrown::HashMap<char, TrieNode>,
7    #[cfg(not(feature = "hashbrown"))]
8    /// Children for trie.
9    pub children: std::hash::HashMap<char, TrieNode>,
10    /// End of word match.
11    pub is_end_of_word: bool,
12}
13
14/// Basic Ignore trie.
15#[derive(Debug)]
16pub struct Trie {
17    /// The trie node.
18    pub root: TrieNode,
19}
20
21impl Trie {
22    /// Setup a new trie.
23    pub fn new() -> Self {
24        Trie {
25            root: TrieNode::default(),
26        }
27    }
28    // Insert a word into the Trie.
29    pub fn insert(&mut self, word: &str) {
30        let mut node = &mut self.root;
31        for ch in word.chars() {
32            node = node.children.entry(ch).or_insert_with(TrieNode::default);
33        }
34        node.is_end_of_word = true;
35    }
36
37    // Check if the Trie contains any prefix of the given string.
38    #[inline]
39    pub fn contains_prefix(&self, text: &str) -> bool {
40        let mut node = &self.root;
41
42        for ch in text.chars() {
43            if let Some(next_node) = node.children.get(&ch) {
44                node = next_node;
45                if node.is_end_of_word {
46                    return true;
47                }
48            } else {
49                break;
50            }
51        }
52
53        false
54    }
55}