Address of a Weak<T>

  1. 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

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?

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:

  1. Upgrade it to an Rc. (you can consider all failing upgrades as equal)
  2. Obtain the pointer using Rc::into_raw and cache it as an integer you can hash.
  3. 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.

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.