1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
use core::cmp::Ordering;
use core::hash::{Hash, Hasher};

/// Trait for extracting key that is a reference to internal data from a data structure.
pub trait RefKey {
    /// Type of the key.
    type Output;

    /// Extract the key from the data structure.
    fn key(&self) -> &Self::Output;
}

/// A wrapper for data structures that implements [`RefKey`](`RefKey`) trait.
#[derive(Clone, Copy, Debug, Default)]
pub struct RefKeyed<T>(pub T);

impl<T> From<T> for RefKeyed<T> {
    fn from(value: T) -> Self {
        Self(value)
    }
}

impl<T: RefKey> PartialEq for RefKeyed<T>
where
    T::Output: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.0.key().eq(other.0.key())
    }

    #[allow(clippy::partialeq_ne_impl)]
    fn ne(&self, other: &Self) -> bool {
        self.0.key().ne(other.0.key())
    }
}

impl<T: RefKey> Eq for RefKeyed<T> where T::Output: Eq {}

impl<T: RefKey> PartialOrd for RefKeyed<T>
where
    T::Output: PartialOrd,
{
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.0.key().partial_cmp(other.0.key())
    }

    fn lt(&self, other: &Self) -> bool {
        self.0.key().lt(other.0.key())
    }

    fn le(&self, other: &Self) -> bool {
        self.0.key().le(other.0.key())
    }

    fn gt(&self, other: &Self) -> bool {
        self.0.key().gt(other.0.key())
    }

    fn ge(&self, other: &Self) -> bool {
        self.0.key().ge(other.0.key())
    }
}

impl<T: RefKey> Ord for RefKeyed<T>
where
    T::Output: Ord,
{
    fn cmp(&self, other: &Self) -> Ordering {
        self.0.key().cmp(other.0.key())
    }
}

impl<T: RefKey> Hash for RefKeyed<T>
where
    T::Output: Hash,
{
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.key().hash(state)
    }
}

#[cfg(test)]
mod tests {
    use super::super::tests::{self, KeyValuePair};
    use super::{RefKey, RefKeyed};

    impl<K, V> RefKey for KeyValuePair<K, V> {
        type Output = K;

        fn key(&self) -> &Self::Output {
            &self.key
        }
    }

    #[test]
    fn test_partial_eq() {
        tests::test_partial_eq(RefKeyed);
    }

    #[test]
    fn test_eq() {
        tests::test_eq(RefKeyed);
    }

    #[test]
    fn test_partial_ord() {
        tests::test_partial_ord(RefKeyed);
    }

    #[test]
    fn test_ord() {
        tests::test_ord(RefKeyed);
    }

    #[test]
    fn test_hash() {
        tests::test_hash(RefKeyed);
    }
}