rustrict icon indicating copy to clipboard operation
rustrict copied to clipboard

Example: How to use trie

Open aalhitennf opened this issue 2 years ago • 3 comments

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.

aalhitennf avatar Jul 26 '23 12:07 aalhitennf

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

aalhitennf avatar Jul 26 '23 15:07 aalhitennf

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);

aalhitennf avatar Jul 26 '23 15:07 aalhitennf

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.

finnbear avatar Jul 26 '23 15:07 finnbear