Hash based on address (not value) of Rc

  1. I genuinely want to hash based on the address, not the value of a Rc.

  2. This is what I have so far:

#[derive(Clone)]
pub struct MathStringPtr(Rc<MathStringBase>);

impl Hash for MathStringPtr {
    fn hash<H: Hasher>(&self, state: &mut H) {
        let rc = &self.0;
        let ptr = Rc::into_raw(rc.clone());
        state.write_usize(ptr as usize);
        unsafe {
            let _ = Rc::from_raw(ptr);
        };
    }
}
  1. Does this look correct? Is there an idiomatic way to do this?

ptr::hash(&**self, state)

4 Likes

How does this work:

self = &Rc<>
*self = Rc<>
**self = actual object
&**self = address of actual object

?

Additional you must impl PartialEq yourself for this type, as stated in the docs.

When implementing both Hash and Eq , it is important that the following property holds:

k1 == k2 -> hash(k1) == hash(k2)

In other words, if two keys are equal, their hashes must also be equal. HashMap and HashSet both rely on this behavior.

And there’s Rc::ptr_eq

Yep, that’s how it works.

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