dashmap icon indicating copy to clipboard operation
dashmap copied to clipboard

Equivalence trait instead of Borrow

Open stepancheg opened this issue 3 years ago • 8 comments
trafficstars

See how IndexMap is doing it: https://docs.rs/indexmap/latest/indexmap/map/struct.IndexMap.html#method.get

Equivalent trait is implemented automatically for Borrow, but additionally it can be implemented for complex types. Consider this example:

struct Key {
  k0: String,
  k1: String,
}

let map: DashMap<Key, u32> = ...

struct KeyRef<'a> {
  k0: &'a str,
  k1: &'a str,
}

let key_ref: KeyRef = ...

map.get(???)

With indexmap it is possible to implement KeyRef: Equivalent<Key> and query by KeyRef.

It is not possible to implement reasonable Borrow for Key (without allocating).

stepancheg avatar Feb 10 '22 20:02 stepancheg

Looked into this. It seems to be currently blocked by https://github.com/rust-lang/rust/issues/56167 as we use the std hashmap under the hood.

xacrimon avatar Feb 28 '22 14:02 xacrimon

Now unblocked as we've switched to hashbrown.

xacrimon avatar Apr 27 '22 12:04 xacrimon

@xacrimon This one's pretty straightforward. PR and merge?

tomkarw avatar Aug 09 '23 19:08 tomkarw

Common Equivalent now lives in a separate crate by the way: https://docs.rs/equivalent/latest/equivalent/

stepancheg avatar Aug 09 '23 21:08 stepancheg

Common Equivalent now lives in a separate crate by the way: https://docs.rs/equivalent/latest/equivalent/

That's true, but we care about whatever Equivalent trait hashbrown uses. So I think it's correct that the reexport chain is equivalent -> hashbrown -> dashmap.

tomkarw avatar Aug 10 '23 09:08 tomkarw

we care about whatever Equivalent trait hashbrown uses

Users of indexmap may prefer to implement Equivalent for their types from equivalent trait once for all possible map implementations using equivalent, without dependency on hashbrown, or indexmap, or dashmap.

stepancheg avatar Aug 10 '23 16:08 stepancheg

Users of indexmap may prefer to implement Equivalent for their types from equivalent trait once for all possible map implementations using equivalent, without dependency on hashbrown, or indexmap, or dashmap.

That's true, however, they are free to do that. Even if we reexport the trait as dashmap::Equivalent for convenience, they can depend on equivalent::Equivalent, implement that and have it work in dashmap as well as other implementations.

Just to be clear, is your preferred solution different from this?

tomkarw avatar Aug 10 '23 19:08 tomkarw

@tomkarw well, this crate exports hashbrown HashMap in public API, then you are correct, it should be hashbrown's Equivalent. I just learned it now.

stepancheg avatar Aug 10 '23 19:08 stepancheg