Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example: How to use trie #13

Open
aalhitennf opened this issue Jul 26, 2023 · 3 comments
Open

Example: How to use trie #13

aalhitennf opened this issue Jul 26, 2023 · 3 comments
Assignees
Labels
feature New feature

Comments

@aalhitennf
Copy link

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 aalhitennf added the feature New feature label Jul 26, 2023
@aalhitennf
Copy link
Author

aalhitennf commented Jul 26, 2023

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
Copy link
Author

aalhitennf commented Jul 26, 2023

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

@finnbear
Copy link
Owner

finnbear commented Jul 26, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature New feature
Projects
None yet
Development

No branches or pull requests

2 participants