API addition: key_for
alkis opened this issue · 4 comments
This will allow getting the key from a value owned by the slab. It is unsafe because if the value is not owned by the slab it returns (at best) bogus keys.
unsafe fn key_for(val: &T) -> usize;
Since values are stored in the vector the key is address of val minus start of vector.
When memory is scarce this allows not storing the key in the value.
Thanks for the issue.
Could you explain more the rational for this API addition. I'm not entirely following the explanation.
This came up when building complex data structures using intrusive-collections and Slabs.
struct Linked<T> {
link: LinkedListLink,
data: T,
}
struct HashedList<T> {
slab: Slab<Linked<T>>,
map: HashMap<String, usize>,
list: LinkedList, // intrusive
}
At some point Linked<T>
will need to be dropped and that happens through references/pointers to each of the Linked<T>
s. To remove a Linked<T>
from the slab one needs to store the key inside of it, but this is unnecessary if we can compute the key from the reference/pointer to Linked<T>
.
Granted all this goes away when someone introduces intrusive-collections that assume the use of a Slab and use usize
as pointers across the board. Until then key_for()
seems like the only way to make this optimall in terms of memory usage.
Ok, this could be fine to implement. I don't think it needs to be unsafe
, just return an Option
.
I'd accept a PR.