Skip to content

Commit 22c7dbc

Browse files
committed
Auto merge of #350 - timothee-haudebourg:equivalent-trait, r=Amanieu
`Equivalent` trait This PR introduces an `Equivalent` trait, as requested in #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.
2 parents 1d2c1a8 + f9df820 commit 22c7dbc

File tree

4 files changed

+147
-94
lines changed

4 files changed

+147
-94
lines changed

src/lib.rs

+33
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,39 @@ pub mod hash_set {
117117
pub use crate::map::HashMap;
118118
pub use crate::set::HashSet;
119119

120+
/// Key equivalence trait.
121+
///
122+
/// This trait defines the function used to compare the input value with the
123+
/// map keys (or set values) during a lookup operation such as [`HashMap::get`]
124+
/// or [`HashSet::contains`].
125+
/// It is provided with a blanket implementation based on the
126+
/// [`Borrow`](core::borrow::Borrow) trait.
127+
///
128+
/// # Correctness
129+
///
130+
/// Equivalent values must hash to the same value.
131+
pub trait Equivalent<K: ?Sized> {
132+
/// Checks if this value is equivalent to the given key.
133+
///
134+
/// Returns `true` if both values are equivalent, and `false` otherwise.
135+
///
136+
/// # Correctness
137+
///
138+
/// When this function returns `true`, both `self` and `key` must hash to
139+
/// the same value.
140+
fn equivalent(&self, key: &K) -> bool;
141+
}
142+
143+
impl<Q: ?Sized, K: ?Sized> Equivalent<K> for Q
144+
where
145+
Q: Eq,
146+
K: core::borrow::Borrow<Q>,
147+
{
148+
fn equivalent(&self, key: &K) -> bool {
149+
self == key.borrow()
150+
}
151+
}
152+
120153
/// The error type for `try_reserve` methods.
121154
#[derive(Clone, PartialEq, Eq, Debug)]
122155
pub enum TryReserveError {

0 commit comments

Comments
 (0)