Skip to main content

indexmap/
equivalent.rs

1//! Key equivalence for hash table lookups.
2//!
3//! This module is a vendored, dependency-free version of the `equivalent`
4//! crate (<https://github.com/indexmap-rs/equivalent>). It is kept internal so
5//! that `indexmap` has no external dependency for its public [`Equivalent`]
6//! trait, while preserving the exact public API of the original crate.
7
8use core::borrow::Borrow;
9
10/// Key equivalence trait.
11///
12/// This trait allows hash table lookup to be customized. It has one blanket
13/// implementation that uses the regular solution with `Borrow` and `Eq`, just
14/// like `HashMap` does, so that you can pass `&str` to lookup into a map with
15/// `String` keys and so on.
16///
17/// # Contract
18///
19/// The implementor **must** hash like `K`, if it is hashable.
20pub trait Equivalent<K: ?Sized> {
21    /// Compare self to `key` and return `true` if they are equal.
22    fn equivalent(&self, key: &K) -> bool;
23}
24
25impl<Q: ?Sized, K: ?Sized> Equivalent<K> for Q
26where
27    Q: Eq,
28    K: Borrow<Q>,
29{
30    #[inline]
31    fn equivalent(&self, key: &K) -> bool {
32        PartialEq::eq(self, key.borrow())
33    }
34}