Skip to content

Commit

Permalink
Auto merge of rust-lang#350 - timothee-haudebourg:equivalent-trait, r…
Browse files Browse the repository at this point in the history
…=Amanieu

`Equivalent` trait

This PR introduces an `Equivalent` trait, as requested in rust-lang#345, to customize lookup operations without requiring a `Borrow` implementation. It provides a blanket implementation that covers the `Borrow` case so it should not break anything.

The `hash_map::EntryRef` API, although it uses the `Borrow` trait, remains unchanged as this would introduce some breaking changes.
  • Loading branch information
bors committed Sep 2, 2022
2 parents 1d2c1a8 + f9df820 commit 22c7dbc
Show file tree
Hide file tree
Showing 4 changed files with 147 additions and 94 deletions.
33 changes: 33 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,39 @@ pub mod hash_set {
pub use crate::map::HashMap;
pub use crate::set::HashSet;

/// Key equivalence trait.
///
/// This trait defines the function used to compare the input value with the
/// map keys (or set values) during a lookup operation such as [`HashMap::get`]
/// or [`HashSet::contains`].
/// It is provided with a blanket implementation based on the
/// [`Borrow`](core::borrow::Borrow) trait.
///
/// # Correctness
///
/// Equivalent values must hash to the same value.
pub trait Equivalent<K: ?Sized> {
/// Checks if this value is equivalent to the given key.
///
/// Returns `true` if both values are equivalent, and `false` otherwise.
///
/// # Correctness
///
/// When this function returns `true`, both `self` and `key` must hash to
/// the same value.
fn equivalent(&self, key: &K) -> bool;
}

impl<Q: ?Sized, K: ?Sized> Equivalent<K> for Q
where
Q: Eq,
K: core::borrow::Borrow<Q>,
{
fn equivalent(&self, key: &K) -> bool {
self == key.borrow()
}
}

/// The error type for `try_reserve` methods.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum TryReserveError {
Expand Down

0 comments on commit 22c7dbc

Please sign in to comment.