Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Abstract key lookup trait, so that it can be extended #10

Merged
merged 1 commit into from
Sep 11, 2017
Merged

Conversation

bluss
Copy link
Member

@bluss bluss commented Nov 14, 2016

/// Key equivalence trait.
///
/// This trait allows hash table lookup to be customized.
/// It has one blanket implementation that uses the regular `Borrow` solution,
/// just like `HashMap` and `BTreeMap` do, so that you can pass `&str` to lookup
/// into a map with `String` keys and so on.
///
/// # Contract
///
/// The implementor must hash like `K`, if applicable.
pub trait Equivalent<K> {
    /// Compare self to `key` and return `true` if they are equal.
    fn equivalent(&self, key: &K) -> bool;
}

Example usage:

     pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
        where Q: Hash + Equivalent<K>,

Example impl:

#[derive(Debug, Hash)]
pub struct Pair<A, B>(pub A, pub B);

impl<A, B, C, D> PartialEq<(A, B)> for Pair<C, D>
    where C: PartialEq<A>,
          D: PartialEq<B>,
{
    fn eq(&self, rhs: &(A, B)) -> bool {
        self.0 == rhs.0 &&
        self.1 == rhs.1 &&
        true
    }
}

impl<A, B, X> Equivalent<X> for Pair<A, B>
    where Pair<A, B>: PartialEq<X>,
          A: Hash + Eq,
          B: Hash + Eq,
{
    fn equivalent(&self, other: &X) -> bool {
        *self == *other
    }
}

@bluss bluss force-pushed the lookup-trait branch 3 times, most recently from f4d4a33 to 43ec4fc Compare November 21, 2016 13:09
@bluss bluss mentioned this pull request Mar 25, 2017
@Techcable
Copy link
Contributor

Techcable commented Jun 26, 2017

Could you please pull this? I can't implement Borrow for my type due to rust-lang/rust#39125
I've rebased this to master in my fork's rebased/lookup-trait branch, so all you have to do is merge that and bump the version.
I'm using this in my own project via a git reference to my branch, and it seems to work fine.

Note: It's a type inference break for the case of ``.remove(&&K)`` which
previously compiled (due to deref coercion?)
@bluss
Copy link
Member Author

bluss commented Sep 11, 2017

I'm merging stuff into master preparing for version 0.3.0!

# for free to join this conversation on GitHub. Already have an account? # to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants