spider_network_blocker/
trie.rs1#[derive(Default, Debug)]
3pub struct TrieNode {
4 #[cfg(feature = "hashbrown")]
5 pub children: hashbrown::HashMap<char, TrieNode>,
7 #[cfg(not(feature = "hashbrown"))]
8 pub children: std::hash::HashMap<char, TrieNode>,
10 pub is_end_of_word: bool,
12}
13
14#[derive(Debug)]
16pub struct Trie {
17 pub root: TrieNode,
19}
20
21impl Trie {
22 pub fn new() -> Self {
24 Trie {
25 root: TrieNode::default(),
26 }
27 }
28 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 #[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}