1 //! Generic hashing support.
3 //! This module provides a generic way to compute the [hash] of a value.
4 //! Hashes are most commonly used with [`HashMap`] and [`HashSet`].
6 //! [hash]: https://en.wikipedia.org/wiki/Hash_function
7 //! [`HashMap`]: ../../std/collections/struct.HashMap.html
8 //! [`HashSet`]: ../../std/collections/struct.HashSet.html
10 //! The simplest way to make a type hashable is to use `#[derive(Hash)]`:
15 //! use std::collections::hash_map::DefaultHasher;
16 //! use std::hash::{Hash, Hasher};
25 //! let person1 = Person {
27 //! name: "Janet".to_string(),
28 //! phone: 555_666_7777,
30 //! let person2 = Person {
32 //! name: "Bob".to_string(),
33 //! phone: 555_666_7777,
36 //! assert!(calculate_hash(&person1) != calculate_hash(&person2));
38 //! fn calculate_hash<T: Hash>(t: &T) -> u64 {
39 //! let mut s = DefaultHasher::new();
45 //! If you need more control over how a value is hashed, you need to implement
46 //! the [`Hash`] trait:
49 //! use std::collections::hash_map::DefaultHasher;
50 //! use std::hash::{Hash, Hasher};
54 //! # #[allow(dead_code)]
59 //! impl Hash for Person {
60 //! fn hash<H: Hasher>(&self, state: &mut H) {
61 //! self.id.hash(state);
62 //! self.phone.hash(state);
66 //! let person1 = Person {
68 //! name: "Janet".to_string(),
69 //! phone: 555_666_7777,
71 //! let person2 = Person {
73 //! name: "Bob".to_string(),
74 //! phone: 555_666_7777,
77 //! assert_eq!(calculate_hash(&person1), calculate_hash(&person2));
79 //! fn calculate_hash<T: Hash>(t: &T) -> u64 {
80 //! let mut s = DefaultHasher::new();
86 #![stable(feature = "rust1", since = "1.0.0")]
91 #[stable(feature = "rust1", since = "1.0.0")]
93 pub use self::sip::SipHasher;
95 #[unstable(feature = "hashmap_internals", issue = "none")]
98 pub use self::sip::SipHasher13;
104 /// Types implementing `Hash` are able to be [`hash`]ed with an instance of
107 /// ## Implementing `Hash`
109 /// You can derive `Hash` with `#[derive(Hash)]` if all fields implement `Hash`.
110 /// The resulting hash will be the combination of the values from calling
111 /// [`hash`] on each field.
115 /// struct Rustacean {
121 /// If you need more control over how a value is hashed, you can of course
122 /// implement the `Hash` trait yourself:
125 /// use std::hash::{Hash, Hasher};
133 /// impl Hash for Person {
134 /// fn hash<H: Hasher>(&self, state: &mut H) {
135 /// self.id.hash(state);
136 /// self.phone.hash(state);
141 /// ## `Hash` and `Eq`
143 /// When implementing both `Hash` and [`Eq`], it is important that the following
147 /// k1 == k2 -> hash(k1) == hash(k2)
150 /// In other words, if two keys are equal, their hashes must also be equal.
151 /// [`HashMap`] and [`HashSet`] both rely on this behavior.
153 /// Thankfully, you won't need to worry about upholding this property when
154 /// deriving both [`Eq`] and `Hash` with `#[derive(PartialEq, Eq, Hash)]`.
156 /// ## Prefix collisions
158 /// Implementations of `hash` should ensure that the data they
159 /// pass to the `Hasher` are prefix-free. That is,
160 /// unequal values should cause two different sequences of values to be written,
161 /// and neither of the two sequences should be a prefix of the other.
163 /// For example, the standard implementation of [`Hash` for `&str`][impl] passes an extra
164 /// `0xFF` byte to the `Hasher` so that the values `("ab", "c")` and `("a",
165 /// "bc")` hash differently.
169 /// Due to differences in endianness and type sizes, data fed by `Hash` to a `Hasher`
170 /// should not be considered portable across platforms. Additionally the data passed by most
171 /// standard library types should not be considered stable between compiler versions.
173 /// This means tests shouldn't probe hard-coded hash values or data fed to a `Hasher` and
174 /// instead should check consistency with `Eq`.
176 /// Serialization formats intended to be portable between platforms or compiler versions should
177 /// either avoid encoding hashes or only rely on `Hash` and `Hasher` implementations that
178 /// provide additional guarantees.
180 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
181 /// [`HashSet`]: ../../std/collections/struct.HashSet.html
182 /// [`hash`]: Hash::hash
183 /// [impl]: ../../std/primitive.str.html#impl-Hash
184 #[stable(feature = "rust1", since = "1.0.0")]
185 #[rustc_diagnostic_item = "Hash"]
187 /// Feeds this value into the given [`Hasher`].
192 /// use std::collections::hash_map::DefaultHasher;
193 /// use std::hash::{Hash, Hasher};
195 /// let mut hasher = DefaultHasher::new();
196 /// 7920.hash(&mut hasher);
197 /// println!("Hash is {:x}!", hasher.finish());
199 #[stable(feature = "rust1", since = "1.0.0")]
200 fn hash<H: Hasher>(&self, state: &mut H);
202 /// Feeds a slice of this type into the given [`Hasher`].
204 /// This method is meant as a convenience, but its implementation is
205 /// also explicitly left unspecified. It isn't guaranteed to be
206 /// equivalent to repeated calls of [`hash`] and implementations of
207 /// [`Hash`] should keep that in mind and call [`hash`] themselves
208 /// if the slice isn't treated as a whole unit in the [`PartialEq`]
211 /// For example, a [`VecDeque`] implementation might naïvely call
212 /// [`as_slices`] and then [`hash_slice`] on each slice, but this
213 /// is wrong since the two slices can change with a call to
214 /// [`make_contiguous`] without affecting the [`PartialEq`]
215 /// result. Since these slices aren't treated as singular
216 /// units, and instead part of a larger deque, this method cannot
222 /// use std::collections::hash_map::DefaultHasher;
223 /// use std::hash::{Hash, Hasher};
225 /// let mut hasher = DefaultHasher::new();
226 /// let numbers = [6, 28, 496, 8128];
227 /// Hash::hash_slice(&numbers, &mut hasher);
228 /// println!("Hash is {:x}!", hasher.finish());
231 /// [`VecDeque`]: ../../std/collections/struct.VecDeque.html
232 /// [`as_slices`]: ../../std/collections/struct.VecDeque.html#method.as_slices
233 /// [`make_contiguous`]: ../../std/collections/struct.VecDeque.html#method.make_contiguous
234 /// [`hash`]: Hash::hash
235 /// [`hash_slice`]: Hash::hash_slice
236 #[stable(feature = "hash_slice", since = "1.3.0")]
237 fn hash_slice<H: Hasher>(data: &[Self], state: &mut H)
247 // Separate module to reexport the macro `Hash` from prelude without the trait `Hash`.
248 pub(crate) mod macros {
249 /// Derive macro generating an impl of the trait `Hash`.
250 #[rustc_builtin_macro]
251 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
252 #[allow_internal_unstable(core_intrinsics)]
253 pub macro Hash($item:item) {
254 /* compiler built-in */
257 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
259 pub use macros::Hash;
261 /// A trait for hashing an arbitrary stream of bytes.
263 /// Instances of `Hasher` usually represent state that is changed while hashing
266 /// `Hasher` provides a fairly basic interface for retrieving the generated hash
267 /// (with [`finish`]), and writing integers as well as slices of bytes into an
268 /// instance (with [`write`] and [`write_u8`] etc.). Most of the time, `Hasher`
269 /// instances are used in conjunction with the [`Hash`] trait.
271 /// This trait makes no assumptions about how the various `write_*` methods are
272 /// defined and implementations of [`Hash`] should not assume that they work one
273 /// way or another. You cannot assume, for example, that a [`write_u32`] call is
274 /// equivalent to four calls of [`write_u8`].
279 /// use std::collections::hash_map::DefaultHasher;
280 /// use std::hash::Hasher;
282 /// let mut hasher = DefaultHasher::new();
284 /// hasher.write_u32(1989);
285 /// hasher.write_u8(11);
286 /// hasher.write_u8(9);
287 /// hasher.write(b"Huh?");
289 /// println!("Hash is {:x}!", hasher.finish());
292 /// [`finish`]: Hasher::finish
293 /// [`write`]: Hasher::write
294 /// [`write_u8`]: Hasher::write_u8
295 /// [`write_u32`]: Hasher::write_u32
296 #[stable(feature = "rust1", since = "1.0.0")]
298 /// Returns the hash value for the values written so far.
300 /// Despite its name, the method does not reset the hasher’s internal
301 /// state. Additional [`write`]s will continue from the current value.
302 /// If you need to start a fresh hash value, you will have to create
308 /// use std::collections::hash_map::DefaultHasher;
309 /// use std::hash::Hasher;
311 /// let mut hasher = DefaultHasher::new();
312 /// hasher.write(b"Cool!");
314 /// println!("Hash is {:x}!", hasher.finish());
317 /// [`write`]: Hasher::write
318 #[stable(feature = "rust1", since = "1.0.0")]
319 fn finish(&self) -> u64;
321 /// Writes some data into this `Hasher`.
326 /// use std::collections::hash_map::DefaultHasher;
327 /// use std::hash::Hasher;
329 /// let mut hasher = DefaultHasher::new();
330 /// let data = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef];
332 /// hasher.write(&data);
334 /// println!("Hash is {:x}!", hasher.finish());
336 #[stable(feature = "rust1", since = "1.0.0")]
337 fn write(&mut self, bytes: &[u8]);
339 /// Writes a single `u8` into this hasher.
341 #[stable(feature = "hasher_write", since = "1.3.0")]
342 fn write_u8(&mut self, i: u8) {
345 /// Writes a single `u16` into this hasher.
347 #[stable(feature = "hasher_write", since = "1.3.0")]
348 fn write_u16(&mut self, i: u16) {
349 self.write(&i.to_ne_bytes())
351 /// Writes a single `u32` into this hasher.
353 #[stable(feature = "hasher_write", since = "1.3.0")]
354 fn write_u32(&mut self, i: u32) {
355 self.write(&i.to_ne_bytes())
357 /// Writes a single `u64` into this hasher.
359 #[stable(feature = "hasher_write", since = "1.3.0")]
360 fn write_u64(&mut self, i: u64) {
361 self.write(&i.to_ne_bytes())
363 /// Writes a single `u128` into this hasher.
365 #[stable(feature = "i128", since = "1.26.0")]
366 fn write_u128(&mut self, i: u128) {
367 self.write(&i.to_ne_bytes())
369 /// Writes a single `usize` into this hasher.
371 #[stable(feature = "hasher_write", since = "1.3.0")]
372 fn write_usize(&mut self, i: usize) {
373 self.write(&i.to_ne_bytes())
376 /// Writes a single `i8` into this hasher.
378 #[stable(feature = "hasher_write", since = "1.3.0")]
379 fn write_i8(&mut self, i: i8) {
380 self.write_u8(i as u8)
382 /// Writes a single `i16` into this hasher.
384 #[stable(feature = "hasher_write", since = "1.3.0")]
385 fn write_i16(&mut self, i: i16) {
386 self.write_u16(i as u16)
388 /// Writes a single `i32` into this hasher.
390 #[stable(feature = "hasher_write", since = "1.3.0")]
391 fn write_i32(&mut self, i: i32) {
392 self.write_u32(i as u32)
394 /// Writes a single `i64` into this hasher.
396 #[stable(feature = "hasher_write", since = "1.3.0")]
397 fn write_i64(&mut self, i: i64) {
398 self.write_u64(i as u64)
400 /// Writes a single `i128` into this hasher.
402 #[stable(feature = "i128", since = "1.26.0")]
403 fn write_i128(&mut self, i: i128) {
404 self.write_u128(i as u128)
406 /// Writes a single `isize` into this hasher.
408 #[stable(feature = "hasher_write", since = "1.3.0")]
409 fn write_isize(&mut self, i: isize) {
410 self.write_usize(i as usize)
414 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
415 impl<H: Hasher + ?Sized> Hasher for &mut H {
416 fn finish(&self) -> u64 {
419 fn write(&mut self, bytes: &[u8]) {
420 (**self).write(bytes)
422 fn write_u8(&mut self, i: u8) {
425 fn write_u16(&mut self, i: u16) {
426 (**self).write_u16(i)
428 fn write_u32(&mut self, i: u32) {
429 (**self).write_u32(i)
431 fn write_u64(&mut self, i: u64) {
432 (**self).write_u64(i)
434 fn write_u128(&mut self, i: u128) {
435 (**self).write_u128(i)
437 fn write_usize(&mut self, i: usize) {
438 (**self).write_usize(i)
440 fn write_i8(&mut self, i: i8) {
443 fn write_i16(&mut self, i: i16) {
444 (**self).write_i16(i)
446 fn write_i32(&mut self, i: i32) {
447 (**self).write_i32(i)
449 fn write_i64(&mut self, i: i64) {
450 (**self).write_i64(i)
452 fn write_i128(&mut self, i: i128) {
453 (**self).write_i128(i)
455 fn write_isize(&mut self, i: isize) {
456 (**self).write_isize(i)
460 /// A trait for creating instances of [`Hasher`].
462 /// A `BuildHasher` is typically used (e.g., by [`HashMap`]) to create
463 /// [`Hasher`]s for each key such that they are hashed independently of one
464 /// another, since [`Hasher`]s contain state.
466 /// For each instance of `BuildHasher`, the [`Hasher`]s created by
467 /// [`build_hasher`] should be identical. That is, if the same stream of bytes
468 /// is fed into each hasher, the same output will also be generated.
473 /// use std::collections::hash_map::RandomState;
474 /// use std::hash::{BuildHasher, Hasher};
476 /// let s = RandomState::new();
477 /// let mut hasher_1 = s.build_hasher();
478 /// let mut hasher_2 = s.build_hasher();
480 /// hasher_1.write_u32(8128);
481 /// hasher_2.write_u32(8128);
483 /// assert_eq!(hasher_1.finish(), hasher_2.finish());
486 /// [`build_hasher`]: BuildHasher::build_hasher
487 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
488 #[stable(since = "1.7.0", feature = "build_hasher")]
489 pub trait BuildHasher {
490 /// Type of the hasher that will be created.
491 #[stable(since = "1.7.0", feature = "build_hasher")]
494 /// Creates a new hasher.
496 /// Each call to `build_hasher` on the same instance should produce identical
502 /// use std::collections::hash_map::RandomState;
503 /// use std::hash::BuildHasher;
505 /// let s = RandomState::new();
506 /// let new_s = s.build_hasher();
508 #[stable(since = "1.7.0", feature = "build_hasher")]
509 fn build_hasher(&self) -> Self::Hasher;
511 /// Calculates the hash of a single value.
513 /// This is intended as a convenience for code which *consumes* hashes, such
514 /// as the implementation of a hash table or in unit tests that check
515 /// whether a custom [`Hash`] implementation behaves as expected.
517 /// This must not be used in any code which *creates* hashes, such as in an
518 /// implementation of [`Hash`]. The way to create a combined hash of
519 /// multiple values is to call [`Hash::hash`] multiple times using the same
520 /// [`Hasher`], not to call this method repeatedly and combine the results.
525 /// #![feature(build_hasher_simple_hash_one)]
527 /// use std::cmp::{max, min};
528 /// use std::hash::{BuildHasher, Hash, Hasher};
529 /// struct OrderAmbivalentPair<T: Ord>(T, T);
530 /// impl<T: Ord + Hash> Hash for OrderAmbivalentPair<T> {
531 /// fn hash<H: Hasher>(&self, hasher: &mut H) {
532 /// min(&self.0, &self.1).hash(hasher);
533 /// max(&self.0, &self.1).hash(hasher);
537 /// // Then later, in a `#[test]` for the type...
538 /// let bh = std::collections::hash_map::RandomState::new();
540 /// bh.hash_one(OrderAmbivalentPair(1, 2)),
541 /// bh.hash_one(OrderAmbivalentPair(2, 1))
544 /// bh.hash_one(OrderAmbivalentPair(10, 2)),
545 /// bh.hash_one(&OrderAmbivalentPair(2, 10))
548 #[unstable(feature = "build_hasher_simple_hash_one", issue = "86161")]
549 fn hash_one<T: Hash>(&self, x: T) -> u64
553 let mut hasher = self.build_hasher();
559 /// Used to create a default [`BuildHasher`] instance for types that implement
560 /// [`Hasher`] and [`Default`].
562 /// `BuildHasherDefault<H>` can be used when a type `H` implements [`Hasher`] and
563 /// [`Default`], and you need a corresponding [`BuildHasher`] instance, but none is
566 /// Any `BuildHasherDefault` is [zero-sized]. It can be created with
567 /// [`default`][method.default]. When using `BuildHasherDefault` with [`HashMap`] or
568 /// [`HashSet`], this doesn't need to be done, since they implement appropriate
569 /// [`Default`] instances themselves.
573 /// Using `BuildHasherDefault` to specify a custom [`BuildHasher`] for
577 /// use std::collections::HashMap;
578 /// use std::hash::{BuildHasherDefault, Hasher};
580 /// #[derive(Default)]
583 /// impl Hasher for MyHasher {
584 /// fn write(&mut self, bytes: &[u8]) {
585 /// // Your hashing algorithm goes here!
589 /// fn finish(&self) -> u64 {
590 /// // Your hashing algorithm goes here!
595 /// type MyBuildHasher = BuildHasherDefault<MyHasher>;
597 /// let hash_map = HashMap::<u32, u32, MyBuildHasher>::default();
600 /// [method.default]: BuildHasherDefault::default
601 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
602 /// [`HashSet`]: ../../std/collections/struct.HashSet.html
603 /// [zero-sized]: https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts
604 #[stable(since = "1.7.0", feature = "build_hasher")]
605 pub struct BuildHasherDefault<H>(marker::PhantomData<H>);
607 #[stable(since = "1.9.0", feature = "core_impl_debug")]
608 impl<H> fmt::Debug for BuildHasherDefault<H> {
609 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
610 f.debug_struct("BuildHasherDefault").finish()
614 #[stable(since = "1.7.0", feature = "build_hasher")]
615 impl<H: Default + Hasher> BuildHasher for BuildHasherDefault<H> {
618 fn build_hasher(&self) -> H {
623 #[stable(since = "1.7.0", feature = "build_hasher")]
624 impl<H> Clone for BuildHasherDefault<H> {
625 fn clone(&self) -> BuildHasherDefault<H> {
626 BuildHasherDefault(marker::PhantomData)
630 #[stable(since = "1.7.0", feature = "build_hasher")]
631 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
632 impl<H> const Default for BuildHasherDefault<H> {
633 fn default() -> BuildHasherDefault<H> {
634 BuildHasherDefault(marker::PhantomData)
638 #[stable(since = "1.29.0", feature = "build_hasher_eq")]
639 impl<H> PartialEq for BuildHasherDefault<H> {
640 fn eq(&self, _other: &BuildHasherDefault<H>) -> bool {
645 #[stable(since = "1.29.0", feature = "build_hasher_eq")]
646 impl<H> Eq for BuildHasherDefault<H> {}
654 macro_rules! impl_write {
655 ($(($ty:ident, $meth:ident),)*) => {$(
656 #[stable(feature = "rust1", since = "1.0.0")]
659 fn hash<H: Hasher>(&self, state: &mut H) {
664 fn hash_slice<H: Hasher>(data: &[$ty], state: &mut H) {
665 let newlen = data.len() * mem::size_of::<$ty>();
666 let ptr = data.as_ptr() as *const u8;
667 // SAFETY: `ptr` is valid and aligned, as this macro is only used
668 // for numeric primitives which have no padding. The new slice only
669 // spans across `data` and is never mutated, and its total size is the
670 // same as the original `data` so it can't be over `isize::MAX`.
671 state.write(unsafe { slice::from_raw_parts(ptr, newlen) })
682 (usize, write_usize),
687 (isize, write_isize),
692 #[stable(feature = "rust1", since = "1.0.0")]
695 fn hash<H: Hasher>(&self, state: &mut H) {
696 state.write_u8(*self as u8)
700 #[stable(feature = "rust1", since = "1.0.0")]
703 fn hash<H: Hasher>(&self, state: &mut H) {
704 state.write_u32(*self as u32)
708 #[stable(feature = "rust1", since = "1.0.0")]
711 fn hash<H: Hasher>(&self, state: &mut H) {
712 state.write(self.as_bytes());
717 #[stable(feature = "never_hash", since = "1.29.0")]
720 fn hash<H: Hasher>(&self, _: &mut H) {
725 macro_rules! impl_hash_tuple {
727 #[stable(feature = "rust1", since = "1.0.0")]
730 fn hash<H: Hasher>(&self, _state: &mut H) {}
734 ( $($name:ident)+) => (
735 #[stable(feature = "rust1", since = "1.0.0")]
736 impl<$($name: Hash),+> Hash for ($($name,)+) where last_type!($($name,)+): ?Sized {
737 #[allow(non_snake_case)]
739 fn hash<S: Hasher>(&self, state: &mut S) {
740 let ($(ref $name,)+) = *self;
741 $($name.hash(state);)+
747 macro_rules! last_type {
748 ($a:ident,) => { $a };
749 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
753 impl_hash_tuple! { A }
754 impl_hash_tuple! { A B }
755 impl_hash_tuple! { A B C }
756 impl_hash_tuple! { A B C D }
757 impl_hash_tuple! { A B C D E }
758 impl_hash_tuple! { A B C D E F }
759 impl_hash_tuple! { A B C D E F G }
760 impl_hash_tuple! { A B C D E F G H }
761 impl_hash_tuple! { A B C D E F G H I }
762 impl_hash_tuple! { A B C D E F G H I J }
763 impl_hash_tuple! { A B C D E F G H I J K }
764 impl_hash_tuple! { A B C D E F G H I J K L }
766 #[stable(feature = "rust1", since = "1.0.0")]
767 impl<T: Hash> Hash for [T] {
769 fn hash<H: Hasher>(&self, state: &mut H) {
770 self.len().hash(state);
771 Hash::hash_slice(self, state)
775 #[stable(feature = "rust1", since = "1.0.0")]
776 impl<T: ?Sized + Hash> Hash for &T {
778 fn hash<H: Hasher>(&self, state: &mut H) {
779 (**self).hash(state);
783 #[stable(feature = "rust1", since = "1.0.0")]
784 impl<T: ?Sized + Hash> Hash for &mut T {
786 fn hash<H: Hasher>(&self, state: &mut H) {
787 (**self).hash(state);
791 #[stable(feature = "rust1", since = "1.0.0")]
792 impl<T: ?Sized> Hash for *const T {
794 fn hash<H: Hasher>(&self, state: &mut H) {
795 let (address, metadata) = self.to_raw_parts();
796 state.write_usize(address as usize);
797 metadata.hash(state);
801 #[stable(feature = "rust1", since = "1.0.0")]
802 impl<T: ?Sized> Hash for *mut T {
804 fn hash<H: Hasher>(&self, state: &mut H) {
805 let (address, metadata) = self.to_raw_parts();
806 state.write_usize(address as usize);
807 metadata.hash(state);