I believe that a Weak<T>
points to a struct that contains
{
weak_count: usize,
strong_count: usize,
actual data: T; // maybe Box<T>
}
Now my question -- is there a way to get the address of this "triplet" ?
EDIT: the XY problem is that I want to keep a collection of Weak<T>
but also avoid duplicates; one way to solve this is to use the address of the RcBox (as a usize) for eq/hash
alice
December 25, 2019, 7:29pm
2
Using this data for a hash is an unstable feature, but you can use ptr_eq
to compare them.
I see how ptr_eq allows impl Eq, but how does it help with impl Hash?
alice
December 25, 2019, 7:39pm
4
It doesn't. If you are on nightly you could use the hash of the pointer , but on stable you'd have to do this:
Upgrade it to an Rc
. (you can consider all failing upgrades as equal)
Obtain the pointer using Rc::into_raw
and cache it as an integer you can hash.
Turn the pointer back into an Rc
using Rc::from_raw
to avoid a memory leak from step 2 and immediately drop the resulting Rc
.
Then you can save the pointer and use it to compute the hash.
I'm not sure if we are discussing the same issue. Looking at the sources:
struct RcBox<T: ?Sized> {
strong: Cell<usize>,
weak: Cell<usize>,
value: T,
}
It sounds like what you are describing gets us a ptr to T
, but what I want is a ptr to RcBox<T>
Is this correct?
I do concede that given the layout of RcBox<T>
, we can probably get one from the other via very unsafe methods.
alice
December 25, 2019, 9:26pm
6
Why does it have to be a pointer to the RcBox
? If all you need it for is hashing, isn't a pointer to one of its fields just as good?
1 Like
You're right, a pointer to the value: T
field works just as well.
system
Closed
March 25, 2020, 5:46am
9
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.