Crate equivalent

source ·
Expand description

Equivalent and Comparable are traits for key comparison in maps.

These may be used in the implementation of maps where the lookup type Q may be different than the stored key type K.

  • Q: Equivalent<K> checks for equality, similar to the HashMap<K, V> constraint K: Borrow<Q>, Q: Eq.
  • Q: Comparable<K> checks the ordering, similar to the BTreeMap<K, V> constraint K: Borrow<Q>, Q: Ord.

These traits are not used by the maps in the standard library, but they may add more flexibility in third-party map implementations, especially in situations where a strict K: Borrow<Q> relationship is not available.


use equivalent::*;
use std::cmp::Ordering;

pub struct Pair<A, B>(pub A, pub B);

impl<'a, A: ?Sized, B: ?Sized, C, D> Equivalent<(C, D)> for Pair<&'a A, &'a B>
    A: Equivalent<C>,
    B: Equivalent<D>,
    fn equivalent(&self, key: &(C, D)) -> bool {
        self.0.equivalent(&key.0) && self.1.equivalent(&key.1)

impl<'a, A: ?Sized, B: ?Sized, C, D> Comparable<(C, D)> for Pair<&'a A, &'a B>
    A: Comparable<C>,
    B: Comparable<D>,
    fn compare(&self, key: &(C, D)) -> Ordering {
        match {
            Ordering::Equal =>,
            not_equal => not_equal,

fn main() {
    let key = (String::from("foo"), String::from("bar"));
    let q1 = Pair("foo", "bar");
    let q2 = Pair("boo", "bar");
    let q3 = Pair("foo", "baz");


    assert_eq!(, Ordering::Equal);
    assert_eq!(, Ordering::Less);
    assert_eq!(, Ordering::Greater);