precomputed_map/equivalent.rs
1//! fork from <https://github.com/indexmap-rs/equivalent/blob/v1.0.2/src/lib.rs>
2
3use core::hash::Hash;
4use core::cmp::Ordering;
5use core::borrow::Borrow;
6use crate::phf::HashOne;
7
8/// Key equivalence trait.
9///
10/// This trait allows hash table lookup to be customized. It has one blanket
11/// implementation that uses the regular solution with `Borrow` and `Eq`, just
12/// like `HashMap` does, so that you can pass `&str` to lookup into a map with
13/// `String` keys and so on.
14///
15/// # Contract
16///
17/// The implementor **must** hash like `K`, if it is hashable.
18pub trait Equivalent<K: ?Sized> {
19 /// Compare self to `key` and return `true` if they are equal.
20 fn equivalent(&self, key: &K) -> bool;
21}
22
23impl<Q: ?Sized, K: ?Sized> Equivalent<K> for Q
24where
25 Q: Eq,
26 K: Borrow<Q>,
27{
28 #[inline]
29 fn equivalent(&self, key: &K) -> bool {
30 PartialEq::eq(self, key.borrow())
31 }
32}
33
34/// Key ordering trait.
35///
36/// This trait allows ordered map lookup to be customized. It has one blanket
37/// implementation that uses the regular solution with `Borrow` and `Ord`, just
38/// like `BTreeMap` does, so that you can pass `&str` to lookup into a map with
39/// `String` keys and so on.
40pub trait Comparable<K: ?Sized>: Equivalent<K> {
41 /// Compare self to `key` and return their ordering.
42 fn compare(&self, key: &K) -> Ordering;
43}
44
45impl<Q: ?Sized, K: ?Sized> Comparable<K> for Q
46where
47 Q: Ord,
48 K: Borrow<Q>,
49{
50 #[inline]
51 fn compare(&self, key: &K) -> Ordering {
52 Ord::cmp(self, key.borrow())
53 }
54}
55
56/// Hashable trait.
57pub trait Hashable<H: HashOne> {
58 fn hash(&self, seed: u64) -> u64;
59}
60
61impl<T: Hash + ?Sized, H: HashOne> Hashable<H> for T {
62 fn hash(&self, seed: u64) -> u64 {
63 H::hash_one(seed, self)
64 }
65}