I need to build an index, where first I check if a string already exists in the store
vector, or if not, add it to the store
and get its position in it.
Once done, I will need to consume the store, and discard the index. I would like to avoid creating each string twice (once for the index and once for the store).
struct StringIndex {
store: Vec<String>,
index: HashMap<&'this str, usize>,
}
impl StringIndex {
pub fn get_or_insert(&mut self, key: &str) -> usize {
match self.index.entry(key) {
Occupied(v) => v.key(),
Vacant(v) => {
let idx = self.store.len();
self.store.push(key.to_string()); // Create a new clone
v.insert(idx);
idx
}
}
}
}
I looked at self_cell and ouroboros, but neither seem to be targetting this use case... or not?