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.
167 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
168 /// [`HashSet`]: ../../std/collections/struct.HashSet.html
169 /// [`hash`]: Hash::hash
170 /// [impl]: ../../std/primitive.str.html#impl-Hash
171 #[stable(feature = "rust1", since = "1.0.0")]
172 #[rustc_diagnostic_item = "Hash"]
174 /// Feeds this value into the given [`Hasher`].
179 /// use std::collections::hash_map::DefaultHasher;
180 /// use std::hash::{Hash, Hasher};
182 /// let mut hasher = DefaultHasher::new();
183 /// 7920.hash(&mut hasher);
184 /// println!("Hash is {:x}!", hasher.finish());
186 #[stable(feature = "rust1", since = "1.0.0")]
187 fn hash<H: Hasher>(&self, state: &mut H);
189 /// Feeds a slice of this type into the given [`Hasher`].
191 /// This method is meant as a convenience, but its implementation is
192 /// also explicitly left unspecified. It isn't guaranteed to be
193 /// equivalent to repeated calls of [`hash`] and implementations of
194 /// [`Hash`] should keep that in mind and call [`hash`] themselves
195 /// if the slice isn't treated as a whole unit in the [`PartialEq`]
198 /// For example, a [`VecDeque`] implementation might naïvely call
199 /// [`as_slices`] and then [`hash_slice`] on each slice, but this
200 /// is wrong since the two slices can change with a call to
201 /// [`make_contiguous`] without affecting the [`PartialEq`]
202 /// result. Since these slices aren't treated as singular
203 /// units, and instead part of a larger deque, this method cannot
209 /// use std::collections::hash_map::DefaultHasher;
210 /// use std::hash::{Hash, Hasher};
212 /// let mut hasher = DefaultHasher::new();
213 /// let numbers = [6, 28, 496, 8128];
214 /// Hash::hash_slice(&numbers, &mut hasher);
215 /// println!("Hash is {:x}!", hasher.finish());
218 /// [`VecDeque`]: ../../std/collections/struct.VecDeque.html
219 /// [`as_slices`]: ../../std/collections/struct.VecDeque.html#method.as_slices
220 /// [`make_contiguous`]: ../../std/collections/struct.VecDeque.html#method.make_contiguous
221 /// [`hash`]: Hash::hash
222 /// [`hash_slice`]: Hash::hash_slice
223 #[stable(feature = "hash_slice", since = "1.3.0")]
224 fn hash_slice<H: Hasher>(data: &[Self], state: &mut H)
234 // Separate module to reexport the macro `Hash` from prelude without the trait `Hash`.
235 pub(crate) mod macros {
236 /// Derive macro generating an impl of the trait `Hash`.
237 #[rustc_builtin_macro]
238 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
239 #[allow_internal_unstable(core_intrinsics)]
240 pub macro Hash($item:item) {
241 /* compiler built-in */
244 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
246 pub use macros::Hash;
248 /// A trait for hashing an arbitrary stream of bytes.
250 /// Instances of `Hasher` usually represent state that is changed while hashing
253 /// `Hasher` provides a fairly basic interface for retrieving the generated hash
254 /// (with [`finish`]), and writing integers as well as slices of bytes into an
255 /// instance (with [`write`] and [`write_u8`] etc.). Most of the time, `Hasher`
256 /// instances are used in conjunction with the [`Hash`] trait.
258 /// This trait makes no assumptions about how the various `write_*` methods are
259 /// defined and implementations of [`Hash`] should not assume that they work one
260 /// way or another. You cannot assume, for example, that a [`write_u32`] call is
261 /// equivalent to four calls of [`write_u8`].
266 /// use std::collections::hash_map::DefaultHasher;
267 /// use std::hash::Hasher;
269 /// let mut hasher = DefaultHasher::new();
271 /// hasher.write_u32(1989);
272 /// hasher.write_u8(11);
273 /// hasher.write_u8(9);
274 /// hasher.write(b"Huh?");
276 /// println!("Hash is {:x}!", hasher.finish());
279 /// [`finish`]: Hasher::finish
280 /// [`write`]: Hasher::write
281 /// [`write_u8`]: Hasher::write_u8
282 /// [`write_u32`]: Hasher::write_u32
283 #[stable(feature = "rust1", since = "1.0.0")]
285 /// Returns the hash value for the values written so far.
287 /// Despite its name, the method does not reset the hasher’s internal
288 /// state. Additional [`write`]s will continue from the current value.
289 /// If you need to start a fresh hash value, you will have to create
295 /// use std::collections::hash_map::DefaultHasher;
296 /// use std::hash::Hasher;
298 /// let mut hasher = DefaultHasher::new();
299 /// hasher.write(b"Cool!");
301 /// println!("Hash is {:x}!", hasher.finish());
304 /// [`write`]: Hasher::write
305 #[stable(feature = "rust1", since = "1.0.0")]
306 fn finish(&self) -> u64;
308 /// Writes some data into this `Hasher`.
313 /// use std::collections::hash_map::DefaultHasher;
314 /// use std::hash::Hasher;
316 /// let mut hasher = DefaultHasher::new();
317 /// let data = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef];
319 /// hasher.write(&data);
321 /// println!("Hash is {:x}!", hasher.finish());
323 #[stable(feature = "rust1", since = "1.0.0")]
324 fn write(&mut self, bytes: &[u8]);
326 /// Writes a single `u8` into this hasher.
328 #[stable(feature = "hasher_write", since = "1.3.0")]
329 fn write_u8(&mut self, i: u8) {
332 /// Writes a single `u16` into this hasher.
334 #[stable(feature = "hasher_write", since = "1.3.0")]
335 fn write_u16(&mut self, i: u16) {
336 self.write(&i.to_ne_bytes())
338 /// Writes a single `u32` into this hasher.
340 #[stable(feature = "hasher_write", since = "1.3.0")]
341 fn write_u32(&mut self, i: u32) {
342 self.write(&i.to_ne_bytes())
344 /// Writes a single `u64` into this hasher.
346 #[stable(feature = "hasher_write", since = "1.3.0")]
347 fn write_u64(&mut self, i: u64) {
348 self.write(&i.to_ne_bytes())
350 /// Writes a single `u128` into this hasher.
352 #[stable(feature = "i128", since = "1.26.0")]
353 fn write_u128(&mut self, i: u128) {
354 self.write(&i.to_ne_bytes())
356 /// Writes a single `usize` into this hasher.
358 #[stable(feature = "hasher_write", since = "1.3.0")]
359 fn write_usize(&mut self, i: usize) {
360 self.write(&i.to_ne_bytes())
363 /// Writes a single `i8` into this hasher.
365 #[stable(feature = "hasher_write", since = "1.3.0")]
366 fn write_i8(&mut self, i: i8) {
367 self.write_u8(i as u8)
369 /// Writes a single `i16` into this hasher.
371 #[stable(feature = "hasher_write", since = "1.3.0")]
372 fn write_i16(&mut self, i: i16) {
373 self.write_u16(i as u16)
375 /// Writes a single `i32` into this hasher.
377 #[stable(feature = "hasher_write", since = "1.3.0")]
378 fn write_i32(&mut self, i: i32) {
379 self.write_u32(i as u32)
381 /// Writes a single `i64` into this hasher.
383 #[stable(feature = "hasher_write", since = "1.3.0")]
384 fn write_i64(&mut self, i: i64) {
385 self.write_u64(i as u64)
387 /// Writes a single `i128` into this hasher.
389 #[stable(feature = "i128", since = "1.26.0")]
390 fn write_i128(&mut self, i: i128) {
391 self.write_u128(i as u128)
393 /// Writes a single `isize` into this hasher.
395 #[stable(feature = "hasher_write", since = "1.3.0")]
396 fn write_isize(&mut self, i: isize) {
397 self.write_usize(i as usize)
401 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
402 impl<H: Hasher + ?Sized> Hasher for &mut H {
403 fn finish(&self) -> u64 {
406 fn write(&mut self, bytes: &[u8]) {
407 (**self).write(bytes)
409 fn write_u8(&mut self, i: u8) {
412 fn write_u16(&mut self, i: u16) {
413 (**self).write_u16(i)
415 fn write_u32(&mut self, i: u32) {
416 (**self).write_u32(i)
418 fn write_u64(&mut self, i: u64) {
419 (**self).write_u64(i)
421 fn write_u128(&mut self, i: u128) {
422 (**self).write_u128(i)
424 fn write_usize(&mut self, i: usize) {
425 (**self).write_usize(i)
427 fn write_i8(&mut self, i: i8) {
430 fn write_i16(&mut self, i: i16) {
431 (**self).write_i16(i)
433 fn write_i32(&mut self, i: i32) {
434 (**self).write_i32(i)
436 fn write_i64(&mut self, i: i64) {
437 (**self).write_i64(i)
439 fn write_i128(&mut self, i: i128) {
440 (**self).write_i128(i)
442 fn write_isize(&mut self, i: isize) {
443 (**self).write_isize(i)
447 /// A trait for creating instances of [`Hasher`].
449 /// A `BuildHasher` is typically used (e.g., by [`HashMap`]) to create
450 /// [`Hasher`]s for each key such that they are hashed independently of one
451 /// another, since [`Hasher`]s contain state.
453 /// For each instance of `BuildHasher`, the [`Hasher`]s created by
454 /// [`build_hasher`] should be identical. That is, if the same stream of bytes
455 /// is fed into each hasher, the same output will also be generated.
460 /// use std::collections::hash_map::RandomState;
461 /// use std::hash::{BuildHasher, Hasher};
463 /// let s = RandomState::new();
464 /// let mut hasher_1 = s.build_hasher();
465 /// let mut hasher_2 = s.build_hasher();
467 /// hasher_1.write_u32(8128);
468 /// hasher_2.write_u32(8128);
470 /// assert_eq!(hasher_1.finish(), hasher_2.finish());
473 /// [`build_hasher`]: BuildHasher::build_hasher
474 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
475 #[stable(since = "1.7.0", feature = "build_hasher")]
476 pub trait BuildHasher {
477 /// Type of the hasher that will be created.
478 #[stable(since = "1.7.0", feature = "build_hasher")]
481 /// Creates a new hasher.
483 /// Each call to `build_hasher` on the same instance should produce identical
489 /// use std::collections::hash_map::RandomState;
490 /// use std::hash::BuildHasher;
492 /// let s = RandomState::new();
493 /// let new_s = s.build_hasher();
495 #[stable(since = "1.7.0", feature = "build_hasher")]
496 fn build_hasher(&self) -> Self::Hasher;
498 /// Calculates the hash of a single value.
500 /// This is intended as a convenience for code which *consumes* hashes, such
501 /// as the implementation of a hash table or in unit tests that check
502 /// whether a custom [`Hash`] implementation behaves as expected.
504 /// This must not be used in any code which *creates* hashes, such as in an
505 /// implementation of [`Hash`]. The way to create a combined hash of
506 /// multiple values is to call [`Hash::hash`] multiple times using the same
507 /// [`Hasher`], not to call this method repeatedly and combine the results.
512 /// #![feature(build_hasher_simple_hash_one)]
514 /// use std::cmp::{max, min};
515 /// use std::hash::{BuildHasher, Hash, Hasher};
516 /// struct OrderAmbivalentPair<T: Ord>(T, T);
517 /// impl<T: Ord + Hash> Hash for OrderAmbivalentPair<T> {
518 /// fn hash<H: Hasher>(&self, hasher: &mut H) {
519 /// min(&self.0, &self.1).hash(hasher);
520 /// max(&self.0, &self.1).hash(hasher);
524 /// // Then later, in a `#[test]` for the type...
525 /// let bh = std::collections::hash_map::RandomState::new();
527 /// bh.hash_one(OrderAmbivalentPair(1, 2)),
528 /// bh.hash_one(OrderAmbivalentPair(2, 1))
531 /// bh.hash_one(OrderAmbivalentPair(10, 2)),
532 /// bh.hash_one(&OrderAmbivalentPair(2, 10))
535 #[unstable(feature = "build_hasher_simple_hash_one", issue = "86161")]
536 fn hash_one<T: Hash>(&self, x: T) -> u64
540 let mut hasher = self.build_hasher();
546 /// Used to create a default [`BuildHasher`] instance for types that implement
547 /// [`Hasher`] and [`Default`].
549 /// `BuildHasherDefault<H>` can be used when a type `H` implements [`Hasher`] and
550 /// [`Default`], and you need a corresponding [`BuildHasher`] instance, but none is
553 /// Any `BuildHasherDefault` is [zero-sized]. It can be created with
554 /// [`default`][method.default]. When using `BuildHasherDefault` with [`HashMap`] or
555 /// [`HashSet`], this doesn't need to be done, since they implement appropriate
556 /// [`Default`] instances themselves.
560 /// Using `BuildHasherDefault` to specify a custom [`BuildHasher`] for
564 /// use std::collections::HashMap;
565 /// use std::hash::{BuildHasherDefault, Hasher};
567 /// #[derive(Default)]
570 /// impl Hasher for MyHasher {
571 /// fn write(&mut self, bytes: &[u8]) {
572 /// // Your hashing algorithm goes here!
576 /// fn finish(&self) -> u64 {
577 /// // Your hashing algorithm goes here!
582 /// type MyBuildHasher = BuildHasherDefault<MyHasher>;
584 /// let hash_map = HashMap::<u32, u32, MyBuildHasher>::default();
587 /// [method.default]: BuildHasherDefault::default
588 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
589 /// [`HashSet`]: ../../std/collections/struct.HashSet.html
590 /// [zero-sized]: https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts
591 #[stable(since = "1.7.0", feature = "build_hasher")]
592 pub struct BuildHasherDefault<H>(marker::PhantomData<H>);
594 #[stable(since = "1.9.0", feature = "core_impl_debug")]
595 impl<H> fmt::Debug for BuildHasherDefault<H> {
596 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
597 f.debug_struct("BuildHasherDefault").finish()
601 #[stable(since = "1.7.0", feature = "build_hasher")]
602 impl<H: Default + Hasher> BuildHasher for BuildHasherDefault<H> {
605 fn build_hasher(&self) -> H {
610 #[stable(since = "1.7.0", feature = "build_hasher")]
611 impl<H> Clone for BuildHasherDefault<H> {
612 fn clone(&self) -> BuildHasherDefault<H> {
613 BuildHasherDefault(marker::PhantomData)
617 #[stable(since = "1.7.0", feature = "build_hasher")]
618 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
619 impl<H> const Default for BuildHasherDefault<H> {
620 fn default() -> BuildHasherDefault<H> {
621 BuildHasherDefault(marker::PhantomData)
625 #[stable(since = "1.29.0", feature = "build_hasher_eq")]
626 impl<H> PartialEq for BuildHasherDefault<H> {
627 fn eq(&self, _other: &BuildHasherDefault<H>) -> bool {
632 #[stable(since = "1.29.0", feature = "build_hasher_eq")]
633 impl<H> Eq for BuildHasherDefault<H> {}
641 macro_rules! impl_write {
642 ($(($ty:ident, $meth:ident),)*) => {$(
643 #[stable(feature = "rust1", since = "1.0.0")]
646 fn hash<H: Hasher>(&self, state: &mut H) {
651 fn hash_slice<H: Hasher>(data: &[$ty], state: &mut H) {
652 let newlen = data.len() * mem::size_of::<$ty>();
653 let ptr = data.as_ptr() as *const u8;
654 // SAFETY: `ptr` is valid and aligned, as this macro is only used
655 // for numeric primitives which have no padding. The new slice only
656 // spans across `data` and is never mutated, and its total size is the
657 // same as the original `data` so it can't be over `isize::MAX`.
658 state.write(unsafe { slice::from_raw_parts(ptr, newlen) })
669 (usize, write_usize),
674 (isize, write_isize),
679 #[stable(feature = "rust1", since = "1.0.0")]
682 fn hash<H: Hasher>(&self, state: &mut H) {
683 state.write_u8(*self as u8)
687 #[stable(feature = "rust1", since = "1.0.0")]
690 fn hash<H: Hasher>(&self, state: &mut H) {
691 state.write_u32(*self as u32)
695 #[stable(feature = "rust1", since = "1.0.0")]
698 fn hash<H: Hasher>(&self, state: &mut H) {
699 state.write(self.as_bytes());
704 #[stable(feature = "never_hash", since = "1.29.0")]
707 fn hash<H: Hasher>(&self, _: &mut H) {
712 macro_rules! impl_hash_tuple {
714 #[stable(feature = "rust1", since = "1.0.0")]
717 fn hash<H: Hasher>(&self, _state: &mut H) {}
721 ( $($name:ident)+) => (
722 #[stable(feature = "rust1", since = "1.0.0")]
723 impl<$($name: Hash),+> Hash for ($($name,)+) where last_type!($($name,)+): ?Sized {
724 #[allow(non_snake_case)]
726 fn hash<S: Hasher>(&self, state: &mut S) {
727 let ($(ref $name,)+) = *self;
728 $($name.hash(state);)+
734 macro_rules! last_type {
735 ($a:ident,) => { $a };
736 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
740 impl_hash_tuple! { A }
741 impl_hash_tuple! { A B }
742 impl_hash_tuple! { A B C }
743 impl_hash_tuple! { A B C D }
744 impl_hash_tuple! { A B C D E }
745 impl_hash_tuple! { A B C D E F }
746 impl_hash_tuple! { A B C D E F G }
747 impl_hash_tuple! { A B C D E F G H }
748 impl_hash_tuple! { A B C D E F G H I }
749 impl_hash_tuple! { A B C D E F G H I J }
750 impl_hash_tuple! { A B C D E F G H I J K }
751 impl_hash_tuple! { A B C D E F G H I J K L }
753 #[stable(feature = "rust1", since = "1.0.0")]
754 impl<T: Hash> Hash for [T] {
756 fn hash<H: Hasher>(&self, state: &mut H) {
757 self.len().hash(state);
758 Hash::hash_slice(self, state)
762 #[stable(feature = "rust1", since = "1.0.0")]
763 impl<T: ?Sized + Hash> Hash for &T {
765 fn hash<H: Hasher>(&self, state: &mut H) {
766 (**self).hash(state);
770 #[stable(feature = "rust1", since = "1.0.0")]
771 impl<T: ?Sized + Hash> Hash for &mut T {
773 fn hash<H: Hasher>(&self, state: &mut H) {
774 (**self).hash(state);
778 #[stable(feature = "rust1", since = "1.0.0")]
779 impl<T: ?Sized> Hash for *const T {
781 fn hash<H: Hasher>(&self, state: &mut H) {
782 let (address, metadata) = self.to_raw_parts();
783 state.write_usize(address as usize);
784 metadata.hash(state);
788 #[stable(feature = "rust1", since = "1.0.0")]
789 impl<T: ?Sized> Hash for *mut T {
791 fn hash<H: Hasher>(&self, state: &mut H) {
792 let (address, metadata) = self.to_raw_parts();
793 state.write_usize(address as usize);
794 metadata.hash(state);