Skip to content

Commit a3eb9e3

Browse files
committed
Add BuildHasher::hash_of as unstable
1 parent 964a81e commit a3eb9e3

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

library/core/src/hash/mod.rs

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -481,6 +481,50 @@ pub trait BuildHasher {
481481
/// ```
482482
#[stable(since = "1.7.0", feature = "build_hasher")]
483483
fn build_hasher(&self) -> Self::Hasher;
484+
485+
/// Calculates the hash of a single value.
486+
///
487+
/// This is intended as a convenience for code which *consumes* hashes, such
488+
/// as the implementation of a hash table or in unit tests that check
489+
/// whether a custom [`Hash`] implementation behaves as expected.
490+
///
491+
/// This must not be used in any code which *creates* hashes, such as in an
492+
/// implementation of [`Hash`]. The way to create a combined hash of
493+
/// multiple values is to call [`Hash::hash`] multiple times using the same
494+
/// [`Hasher`], not to call this method repeatedly and combine the results.
495+
///
496+
/// # Example
497+
///
498+
/// ```
499+
/// #![feature(build_hasher_simple_hash_of)]
500+
///
501+
/// use std::cmp::{max, min};
502+
/// use std::hash::{BuildHasher, Hash, Hasher};
503+
/// struct OrderAmbivalentPair<T: Ord>(T, T);
504+
/// impl<T: Ord + Hash> Hash for OrderAmbivalentPair<T> {
505+
/// fn hash<H: Hasher>(&self, hasher: &mut H) {
506+
/// min(&self.0, &self.1).hash(hasher);
507+
/// max(&self.0, &self.1).hash(hasher);
508+
/// }
509+
/// }
510+
///
511+
/// // Then later, in a `#[test]` for the type...
512+
/// let bh = std::collections::hash_map::RandomState::new();
513+
/// assert_eq!(
514+
/// bh.hash_of(OrderAmbivalentPair(1, 2)),
515+
/// bh.hash_of(OrderAmbivalentPair(2, 1))
516+
/// );
517+
/// assert_eq!(
518+
/// bh.hash_of(OrderAmbivalentPair(10, 2)),
519+
/// bh.hash_of(&OrderAmbivalentPair(2, 10))
520+
/// );
521+
/// ```
522+
#[unstable(feature = "build_hasher_simple_hash_of", issue = "88888888")]
523+
fn hash_of<T: Hash>(&self, x: T) -> u64 {
524+
let mut hasher = self.build_hasher();
525+
x.hash(&mut hasher);
526+
hasher.finish()
527+
}
484528
}
485529

486530
/// Used to create a default [`BuildHasher`] instance for types that implement

0 commit comments

Comments
 (0)