A question about reference validity and vector/hashmap types

If I were to pass a mutable reference to an element in a vector type, the moment that someone else removes an element from the vector, the entire thing is shifted downwards. This would invalidate a mutable reference, causing a dangling reference, correct? (supposing the element removed has an index less than the index of the element which has an active mutable borrow)

If so, then would a hashmap alleviate this problem? I need to pass out mutable references to downstream consumers (the program has to use some unsafe to convert an unbounded lifetime to a bounded lifetime in order to pass the borrow checks), and the logic of the code gaurantees that at most one mutable reference for a specific element exists at a time. However, my biggest concern is that by passing a mutable reference from a vector/hashmap type, the referrent's position may change during item removal and thus the reference becomes dangling.

Important note: I am using a ThreadPool for the async event loop which happens to drive the mutable passing of information. As such, it is likely that multiple threads may be active at once, raising the concern: would this make it necessary to use a concurrent hashmap?

Obtaining unique access to the element requires unique access to the vector. Inserting/removing element from the vector requires unique access to the vector. A unique access can't be aliased so one can't concurrently (even on single thread) perform both operation to the same vector.

1 Like

Concurrent hashmap it is

(I am needing to store packets btw)

Even on concurrent hash map it should be unsafe fn to obtain &mut Elem from &Map as it's possible to obtain aliased unique access to the element by querying it twice with the same key.

Right that makes sense. However, my program's setup guarantees that a single key's element can't be operated upon mutably more than once at a time

Not with unsafe, it should be possible to add elements to a Vec as long as there is space and remove from it as long as the borrow elements are before the removed one. And there is swap_remove too.
Miri doesn't complain about this playground for example.

Since @nologik has an unbound lifetime there has to be something like this going on, am I right?
I'm not saying it's the way to go but I think it's interesting.

I am forced to transmute an unbounded mutable reference of self to a bounded mutable reference of self because I am invoking a method call from a trait function that has an unbounded lifetime (in this case, that trait function is Sink::poll(&mut self), yet, I must execute MyStruct::send_mut_ref(&'driver mut self). i am using futures 0.1, however, maybe using futures 0.3 will fix the problem because it uses self: Pin<&mut Self>?

Note: MyStruct implements Sink, thus self points to the same struct is memory

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.