Skip to content

Commit f6c234f

Browse files
committed
Document properties for Eq + Hash
Fixes rust-lang#23320
1 parent 242ed0b commit f6c234f

File tree

3 files changed

+28
-2
lines changed

3 files changed

+28
-2
lines changed

src/libcore/hash/mod.rs

+10
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,16 @@ mod sip;
7373
///
7474
/// The `H` type parameter is an abstract hash state that is used by the `Hash`
7575
/// to compute the hash.
76+
///
77+
/// If you are also implementing `Eq`, there is an additional property that
78+
/// is important:
79+
///
80+
/// ```text
81+
/// k1 == k2 -> hash(k1) == hash(k2)
82+
/// ```
83+
///
84+
/// In other words, if two keys are equal, their hashes should also be equal.
85+
/// `HashMap` and `HashSet` both rely on this behavior.
7686
#[stable(feature = "rust1", since = "1.0.0")]
7787
pub trait Hash {
7888
/// Feeds this value into the state given, updating the hasher as necessary.

src/libstd/collections/hash/map.rs

+8-1
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,14 @@ fn test_resize_policy() {
214214
/// overridden with one of the constructors.
215215
///
216216
/// It is required that the keys implement the `Eq` and `Hash` traits, although
217-
/// this can frequently be achieved by using `#[derive(Eq, Hash)]`.
217+
/// this can frequently be achieved by using `#[derive(Eq, Hash)]`. If you
218+
/// implement these yourself, it is important that the following property holds:
219+
///
220+
/// ```text
221+
/// k1 == k2 -> hash(k1) == hash(k2)
222+
/// ```
223+
///
224+
/// In other words, if two keys are equal, their hashes must be equal.
218225
///
219226
/// It is a logic error for a key to be modified in such a way that the key's
220227
/// hash, as determined by the `Hash` trait, or its equality, as determined by

src/libstd/collections/hash/set.rs

+10-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,16 @@ use super::state::HashState;
3636

3737
/// An implementation of a hash set using the underlying representation of a
3838
/// HashMap where the value is (). As with the `HashMap` type, a `HashSet`
39-
/// requires that the elements implement the `Eq` and `Hash` traits.
39+
/// requires that the elements implement the `Eq` and `Hash` traits. This can
40+
/// frequently be achieved by using `#[derive(Eq, Hash)]`. If you implement
41+
/// these yourself, it is important that the following property holds:
42+
///
43+
/// ```text
44+
/// k1 == k2 -> hash(k1) == hash(k2)
45+
/// ```
46+
///
47+
/// In other words, if two keys are equal, their hashes must be equal.
48+
///
4049
///
4150
/// It is a logic error for an item to be modified in such a way that the
4251
/// item's hash, as determined by the `Hash` trait, or its equality, as

0 commit comments

Comments
 (0)