Recommendation for Hashable Rc wrapper

I want to use a hashmap with key which is a Rc<...>. I want to know what is the community or official recommended way of doing it. I saw some names like by_address, hash32 etc.

What kind of "names you saw"? An Rc just forwards its Hash and Eq impls to the wrapped type; you can put an Rc as a key into a HashMap just fine as long as you could have inserted the pointed type.

1 Like

but what if I want just pointer comparison, then also we should have a recursive trait bound on the sub-types inner to Rc ?

If you want just pointer comparison, then of course you don't need those bounds. I'd recommend creating an appropriate wrapper for that, e.g.

struct PtrHashRc<T: ?Sized>(Rc<T>);

impl<T: ?Sized> PartialEq for PtrHashRc<T> {
    …
}

impl<T: ?Sized> Hash for PtrHashRc<T> {
    …
}
1 Like

It this fine ?

use std::rc::Rc;
use std::hash::{Hash, Hasher};

struct RcWrapper<T>(Rc<T>);

impl<T> PartialEq for RcWrapper<T> {
    fn eq(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.0, &other.0)
    }
}

impl<T> Eq for RcWrapper<T> {}

impl<T> Hash for RcWrapper<T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        let ptr = Rc::as_ptr(&self.0);
        ptr.hash(state);
    }
}

@H2CO3 actually, my key are ast nodes which are wrapper of Rc<…>, so I believe mere pointer comparison can tell if the nodes are same or not, am I right?