I have a struct Oid
, which owns a vector of distinct objects. It also has a reverse map which maps an object to its index in the vector. Objects are never deleted from the struct. However, new objects can be added. The use case is simple: I need fast retrieval of an object by its index and of the index of a given object. Here's my attempt so far:
struct Oid<'a, T>
where
T: Eq + Hash,
{
objects: Vec<Box<T>>,
rev_map: HashMap<&'a T, usize>,
}
impl<'a, T> Oid<'a, T>
where
T: Eq + Hash,
{
pub fn insert(&mut self, t: T) -> usize {
match self.objects.get(&t) {
Some(&i) => i,
_ => {
let i = self.objects.size();
self.objects.push(Box::new(t));
self.rev_map
.insert(unsafe { &*(&*self.objects[i] as *const T) }, i);
i
}
}
}
}
As the memory locations of objects can change as the vector grows, I put each object in a Box
, which ensures address stability. The problem is in rev_map
, I can't figure out how to tell Rust that the object reference will never outlive the struct. Is there a way to do this in idiomatic Rust?