| 1 |
|
| 2 |
|
| 3 |
use string_cache::DefaultAtom; |
| 4 |
|
| 5 |
fn main() { |
| 6 |
let mut interned_stuff = Vec::new(); |
| 7 |
let text = "here is a sentence of text that will be tokenised and interned and some repeated \ |
| 8 |
tokens is of text and"; |
| 9 |
for word in text.split_whitespace() { |
| 10 |
let seen_before = interned_stuff |
| 11 |
.iter() |
| 12 |
// We can use impl PartialEq<T> where T is anything string-like to compare to |
| 13 |
// interned strings to either other interned strings, or actual strings Comparing two |
| 14 |
// interned strings is very fast (normally a single cpu operation). |
| 15 |
.filter(|interned_word| interned_word == &word) |
| 16 |
.count(); |
| 17 |
if seen_before > 0 { |
| 18 |
println!(r#"Seen the word "{}" {} times"#, word, seen_before); |
| 19 |
} else { |
| 20 |
println!(r#"Not seen the word "{}" before"#, word); |
| 21 |
} |
| 22 |
// We use the impl From<(Cow<'a, str>, or &'a str, or String) for Atom<Static> to intern a |
| 23 |
// new string |
| 24 |
interned_stuff.push(DefaultAtom::from(word)); |
| 25 |
} |
| 26 |
} |