rustrict
rustrict copied to clipboard
Example: How to use trie
Motivation
add_word is marked deprecated and i have no how to add custom word with Trie, or Cencor::with_trie like it suggests. Small simple example would be great.
Im trying to initialize empty trie with only few custom words:
fn main() {
let mut trie = Trie::new();
trie.set("bad word", Type::OFFENSIVE);
let t = Censor::from_str("contains bad word").with_trie(&trie).analyze();
assert_eq!(t, Type::OFFENSIVE);
}
I get:
trie does not live long enough
borrowed value does not live long enough
Found solution:
let trie = unsafe { Trie::customize_default() };
trie.clone_from(&Trie::new());
trie.set("bad word", Type::OFFENSIVE);
let t = Censor::from_str("contains offensive bad word").with_trie(trie).analyze();
assert_eq!(t, Type::OFFENSIVE);
Hello, thanks for the issue!
Due to the current &'static lifetime requirement of Censor::with_trie, it's necessary to do a hack like what you found or Box::leak(Box::new(Trie::new())), which doesn't use unsafe.
In the future, I hope to improve the API and/or the documentation.