Skip to main content

clt_database/skiplist/
equivalent.rs

1// These traits are based on `equivalent` crate, but `K` and `Q` are flipped to avoid type inference issues:
2// https://github.com/indexmap-rs/equivalent/issues/5
3
4//! Traits for key comparison in maps.
5
6use core::{borrow::Borrow, cmp::Ordering};
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 `Q`, if it is hashable.
18pub trait Equivalent<Q: ?Sized> {
19    /// Compare self to `key` and return `true` if they are equal.
20    fn equivalent(&self, key: &Q) -> bool;
21}
22
23impl<K: ?Sized, Q: ?Sized> Equivalent<Q> for K
24where
25    K: Borrow<Q>,
26    Q: Eq,
27{
28    #[inline]
29    fn equivalent(&self, key: &Q) -> bool {
30        PartialEq::eq(self.borrow(), key)
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<Q: ?Sized>: Equivalent<Q> {
41    /// Compare self to `key` and return their ordering.
42    fn compare(&self, key: &Q) -> Ordering;
43}
44
45impl<K: ?Sized, Q: ?Sized> Comparable<Q> for K
46where
47    K: Borrow<Q>,
48    Q: Ord,
49{
50    #[inline]
51    fn compare(&self, key: &Q) -> Ordering {
52        Ord::cmp(self.borrow(), key)
53    }
54}