#[derive(Default, Debug)]
pub struct TrieNode {
#[cfg(feature = "hashbrown")]
pub children: hashbrown::HashMap<u8, TrieNode>,
#[cfg(not(feature = "hashbrown"))]
pub children: std::collections::HashMap<u8, TrieNode>,
pub is_end_of_word: bool,
}
#[derive(Debug)]
pub struct Trie {
pub root: TrieNode,
}
impl Trie {
pub fn new() -> Self {
Trie {
root: TrieNode::default(),
}
}
pub fn insert(&mut self, word: &str) {
let mut node = &mut self.root;
for &b in word.as_bytes() {
node = node.children.entry(b).or_default();
}
node.is_end_of_word = true;
}
#[inline]
pub fn contains_prefix(&self, text: &str) -> bool {
let bytes = text.as_bytes();
let mut node = &self.root;
for &b in bytes {
if let Some(next_node) = node.children.get(&b) {
node = next_node;
if node.is_end_of_word {
return true;
}
} else {
break;
}
}
false
}
}