Skip to content

Commit e88a511

Browse files
committed
improved std::hash::BuildHasher docs
Part of #29357. * split summary and explanation more clearly, while expanding the explanation to make the reason for `BuildHasher` existing more clear * added an example illustrating that `Hasher`s created by one `BuildHasher` should be identical * added links * repeated the fact that hashers produced should be identical in `build_hasher`s method docs
1 parent c199d25 commit e88a511

File tree

1 file changed

+33
-5
lines changed

1 file changed

+33
-5
lines changed

src/libcore/hash/mod.rs

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -258,12 +258,35 @@ pub trait Hasher {
258258
}
259259
}
260260

261-
/// A `BuildHasher` is typically used as a factory for instances of `Hasher`
262-
/// which a `HashMap` can then use to hash keys independently.
261+
/// A trait for creating instances of [`Hasher`].
263262
///
264-
/// Note that for each instance of `BuildHasher`, the created hashers should be
265-
/// identical. That is, if the same stream of bytes is fed into each hasher, the
266-
/// same output will also be generated.
263+
/// A `BuildHasher` is typically used (e.g. by [`HashMap`]) to create
264+
/// [`Hasher`]s for each key such that they are hashed independently of one
265+
/// another, since [`Hasher`]s contain state.
266+
///
267+
/// For each instance of `BuildHasher`, the [`Hasher`]s created by
268+
/// [`build_hasher`] should be identical. That is, if the same stream of bytes
269+
/// is fed into each hasher, the same output will also be generated.
270+
///
271+
/// # Examples
272+
///
273+
/// ```
274+
/// use std::collections::hash_map::RandomState;
275+
/// use std::hash::{BuildHasher, Hasher};
276+
///
277+
/// let s = RandomState::new();
278+
/// let mut hasher_1 = s.build_hasher();
279+
/// let mut hasher_2 = s.build_hasher();
280+
///
281+
/// hasher_1.write_u32(8128);
282+
/// hasher_2.write_u32(8128);
283+
///
284+
/// assert_eq!(hasher_1.finish(), hasher_2.finish());
285+
/// ```
286+
///
287+
/// [`build_hasher`]: #method.build_hasher
288+
/// [`Hasher`]: trait.Hasher.html
289+
/// [`HashMap`]: ../../std/collections/struct.HashMap.html
267290
#[stable(since = "1.7.0", feature = "build_hasher")]
268291
pub trait BuildHasher {
269292
/// Type of the hasher that will be created.
@@ -272,6 +295,9 @@ pub trait BuildHasher {
272295

273296
/// Creates a new hasher.
274297
///
298+
/// Each call to `build_hasher` on the same instance should produce identical
299+
/// [`Hasher`]s.
300+
///
275301
/// # Examples
276302
///
277303
/// ```
@@ -281,6 +307,8 @@ pub trait BuildHasher {
281307
/// let s = RandomState::new();
282308
/// let new_s = s.build_hasher();
283309
/// ```
310+
///
311+
/// [`Hasher`]: trait.Hasher.html
284312
#[stable(since = "1.7.0", feature = "build_hasher")]
285313
fn build_hasher(&self) -> Self::Hasher;
286314
}

0 commit comments

Comments
 (0)