about summary refs log tree commit diff
diff options
context:
space:
mode:
authorScott McMurray <scottmcm@users.noreply.github.com>2021-06-08 13:52:57 -0700
committerScott McMurray <scottmcm@users.noreply.github.com>2021-06-24 01:30:48 -0700
commita3eb9e3db2af13cb8c8a7542ae94514228a5417c (patch)
treefa50f8be32e1721570111ceabe8b544d21211365
parent964a81eb37db6ee33b8fc107582618bf2befe02d (diff)
downloadrust-a3eb9e3db2af13cb8c8a7542ae94514228a5417c.tar.gz
rust-a3eb9e3db2af13cb8c8a7542ae94514228a5417c.zip
Add `BuildHasher::hash_of` as unstable
-rw-r--r--library/core/src/hash/mod.rs44
1 files changed, 44 insertions, 0 deletions
diff --git a/library/core/src/hash/mod.rs b/library/core/src/hash/mod.rs
index 77d3a35b268..28f98d983c7 100644
--- a/library/core/src/hash/mod.rs
+++ b/library/core/src/hash/mod.rs
@@ -481,6 +481,50 @@ pub trait BuildHasher {
     /// ```
     #[stable(since = "1.7.0", feature = "build_hasher")]
     fn build_hasher(&self) -> Self::Hasher;
+
+    /// Calculates the hash of a single value.
+    ///
+    /// This is intended as a convenience for code which *consumes* hashes, such
+    /// as the implementation of a hash table or in unit tests that check
+    /// whether a custom [`Hash`] implementation behaves as expected.
+    ///
+    /// This must not be used in any code which *creates* hashes, such as in an
+    /// implementation of [`Hash`].  The way to create a combined hash of
+    /// multiple values is to call [`Hash::hash`] multiple times using the same
+    /// [`Hasher`], not to call this method repeatedly and combine the results.
+    ///
+    /// # Example
+    ///
+    /// ```
+    /// #![feature(build_hasher_simple_hash_of)]
+    ///
+    /// use std::cmp::{max, min};
+    /// use std::hash::{BuildHasher, Hash, Hasher};
+    /// struct OrderAmbivalentPair<T: Ord>(T, T);
+    /// impl<T: Ord + Hash> Hash for OrderAmbivalentPair<T> {
+    ///     fn hash<H: Hasher>(&self, hasher: &mut H) {
+    ///         min(&self.0, &self.1).hash(hasher);
+    ///         max(&self.0, &self.1).hash(hasher);
+    ///     }
+    /// }
+    ///
+    /// // Then later, in a `#[test]` for the type...
+    /// let bh = std::collections::hash_map::RandomState::new();
+    /// assert_eq!(
+    ///     bh.hash_of(OrderAmbivalentPair(1, 2)),
+    ///     bh.hash_of(OrderAmbivalentPair(2, 1))
+    /// );
+    /// assert_eq!(
+    ///     bh.hash_of(OrderAmbivalentPair(10, 2)),
+    ///     bh.hash_of(&OrderAmbivalentPair(2, 10))
+    /// );
+    /// ```
+    #[unstable(feature = "build_hasher_simple_hash_of", issue = "88888888")]
+    fn hash_of<T: Hash>(&self, x: T) -> u64 {
+        let mut hasher = self.build_hasher();
+        x.hash(&mut hasher);
+        hasher.finish()
+    }
 }
 
 /// Used to create a default [`BuildHasher`] instance for types that implement