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 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
157 /// [`HashSet`]: ../../std/collections/struct.HashSet.html
158 /// [`hash`]: Hash::hash
159 #[stable(feature = "rust1", since = "1.0.0")]
161 /// Feeds this value into the given [`Hasher`].
166 /// use std::collections::hash_map::DefaultHasher;
167 /// use std::hash::{Hash, Hasher};
169 /// let mut hasher = DefaultHasher::new();
170 /// 7920.hash(&mut hasher);
171 /// println!("Hash is {:x}!", hasher.finish());
173 #[stable(feature = "rust1", since = "1.0.0")]
174 fn hash
<H
: Hasher
>(&self, state
: &mut H
);
176 /// Feeds a slice of this type into the given [`Hasher`].
178 /// This method is meant as a convenience, but its implementation is
179 /// also explicitly left unspecified. It isn't guaranteed to be
180 /// equivalent to repeated calls of [`hash`] and implementations of
181 /// [`Hash`] should keep that in mind and call [`hash`] themselves
182 /// if the slice isn't treated as a whole unit in the [`PartialEq`]
185 /// For example, a [`VecDeque`] implementation might naïvely call
186 /// [`as_slices`] and then [`hash_slice`] on each slice, but this
187 /// is wrong since the two slices can change with a call to
188 /// [`make_contiguous`] without affecting the [`PartialEq`]
189 /// result. Since these slices aren't treated as singular
190 /// units, and instead part of a larger deque, this method cannot
196 /// use std::collections::hash_map::DefaultHasher;
197 /// use std::hash::{Hash, Hasher};
199 /// let mut hasher = DefaultHasher::new();
200 /// let numbers = [6, 28, 496, 8128];
201 /// Hash::hash_slice(&numbers, &mut hasher);
202 /// println!("Hash is {:x}!", hasher.finish());
205 /// [`VecDeque`]: ../../std/collections/struct.VecDeque.html
206 /// [`as_slices`]: ../../std/collections/struct.VecDeque.html#method.as_slices
207 /// [`make_contiguous`]: ../../std/collections/struct.VecDeque.html#method.make_contiguous
208 /// [`hash`]: Hash::hash
209 /// [`hash_slice`]: Hash::hash_slice
210 #[stable(feature = "hash_slice", since = "1.3.0")]
211 fn hash_slice
<H
: Hasher
>(data
: &[Self], state
: &mut H
)
221 // Separate module to reexport the macro `Hash` from prelude without the trait `Hash`.
222 pub(crate) mod macros
{
223 /// Derive macro generating an impl of the trait `Hash`.
224 #[rustc_builtin_macro]
225 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
226 #[allow_internal_unstable(core_intrinsics)]
227 pub macro Hash($item
:item
) {
228 /* compiler built-in */
231 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
233 pub use macros
::Hash
;
235 /// A trait for hashing an arbitrary stream of bytes.
237 /// Instances of `Hasher` usually represent state that is changed while hashing
240 /// `Hasher` provides a fairly basic interface for retrieving the generated hash
241 /// (with [`finish`]), and writing integers as well as slices of bytes into an
242 /// instance (with [`write`] and [`write_u8`] etc.). Most of the time, `Hasher`
243 /// instances are used in conjunction with the [`Hash`] trait.
245 /// This trait makes no assumptions about how the various `write_*` methods are
246 /// defined and implementations of [`Hash`] should not assume that they work one
247 /// way or another. You cannot assume, for example, that a [`write_u32`] call is
248 /// equivalent to four calls of [`write_u8`].
253 /// use std::collections::hash_map::DefaultHasher;
254 /// use std::hash::Hasher;
256 /// let mut hasher = DefaultHasher::new();
258 /// hasher.write_u32(1989);
259 /// hasher.write_u8(11);
260 /// hasher.write_u8(9);
261 /// hasher.write(b"Huh?");
263 /// println!("Hash is {:x}!", hasher.finish());
266 /// [`finish`]: Hasher::finish
267 /// [`write`]: Hasher::write
268 /// [`write_u8`]: Hasher::write_u8
269 /// [`write_u32`]: Hasher::write_u32
270 #[stable(feature = "rust1", since = "1.0.0")]
272 /// Returns the hash value for the values written so far.
274 /// Despite its name, the method does not reset the hasher’s internal
275 /// state. Additional [`write`]s will continue from the current value.
276 /// If you need to start a fresh hash value, you will have to create
282 /// use std::collections::hash_map::DefaultHasher;
283 /// use std::hash::Hasher;
285 /// let mut hasher = DefaultHasher::new();
286 /// hasher.write(b"Cool!");
288 /// println!("Hash is {:x}!", hasher.finish());
291 /// [`write`]: Hasher::write
292 #[stable(feature = "rust1", since = "1.0.0")]
293 fn finish(&self) -> u64;
295 /// Writes some data into this `Hasher`.
300 /// use std::collections::hash_map::DefaultHasher;
301 /// use std::hash::Hasher;
303 /// let mut hasher = DefaultHasher::new();
304 /// let data = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef];
306 /// hasher.write(&data);
308 /// println!("Hash is {:x}!", hasher.finish());
310 #[stable(feature = "rust1", since = "1.0.0")]
311 fn write(&mut self, bytes
: &[u8]);
313 /// Writes a single `u8` into this hasher.
315 #[stable(feature = "hasher_write", since = "1.3.0")]
316 fn write_u8(&mut self, i
: u8) {
319 /// Writes a single `u16` into this hasher.
321 #[stable(feature = "hasher_write", since = "1.3.0")]
322 fn write_u16(&mut self, i
: u16) {
323 self.write(&i
.to_ne_bytes())
325 /// Writes a single `u32` into this hasher.
327 #[stable(feature = "hasher_write", since = "1.3.0")]
328 fn write_u32(&mut self, i
: u32) {
329 self.write(&i
.to_ne_bytes())
331 /// Writes a single `u64` into this hasher.
333 #[stable(feature = "hasher_write", since = "1.3.0")]
334 fn write_u64(&mut self, i
: u64) {
335 self.write(&i
.to_ne_bytes())
337 /// Writes a single `u128` into this hasher.
339 #[stable(feature = "i128", since = "1.26.0")]
340 fn write_u128(&mut self, i
: u128
) {
341 self.write(&i
.to_ne_bytes())
343 /// Writes a single `usize` into this hasher.
345 #[stable(feature = "hasher_write", since = "1.3.0")]
346 fn write_usize(&mut self, i
: usize) {
347 self.write(&i
.to_ne_bytes())
350 /// Writes a single `i8` into this hasher.
352 #[stable(feature = "hasher_write", since = "1.3.0")]
353 fn write_i8(&mut self, i
: i8) {
354 self.write_u8(i
as u8)
356 /// Writes a single `i16` into this hasher.
358 #[stable(feature = "hasher_write", since = "1.3.0")]
359 fn write_i16(&mut self, i
: i16) {
360 self.write_u16(i
as u16)
362 /// Writes a single `i32` into this hasher.
364 #[stable(feature = "hasher_write", since = "1.3.0")]
365 fn write_i32(&mut self, i
: i32) {
366 self.write_u32(i
as u32)
368 /// Writes a single `i64` into this hasher.
370 #[stable(feature = "hasher_write", since = "1.3.0")]
371 fn write_i64(&mut self, i
: i64) {
372 self.write_u64(i
as u64)
374 /// Writes a single `i128` into this hasher.
376 #[stable(feature = "i128", since = "1.26.0")]
377 fn write_i128(&mut self, i
: i128
) {
378 self.write_u128(i
as u128
)
380 /// Writes a single `isize` into this hasher.
382 #[stable(feature = "hasher_write", since = "1.3.0")]
383 fn write_isize(&mut self, i
: isize) {
384 self.write_usize(i
as usize)
388 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
389 impl<H
: Hasher
+ ?Sized
> Hasher
for &mut H
{
390 fn finish(&self) -> u64 {
393 fn write(&mut self, bytes
: &[u8]) {
394 (**self).write(bytes
)
396 fn write_u8(&mut self, i
: u8) {
399 fn write_u16(&mut self, i
: u16) {
400 (**self).write_u16(i
)
402 fn write_u32(&mut self, i
: u32) {
403 (**self).write_u32(i
)
405 fn write_u64(&mut self, i
: u64) {
406 (**self).write_u64(i
)
408 fn write_u128(&mut self, i
: u128
) {
409 (**self).write_u128(i
)
411 fn write_usize(&mut self, i
: usize) {
412 (**self).write_usize(i
)
414 fn write_i8(&mut self, i
: i8) {
417 fn write_i16(&mut self, i
: i16) {
418 (**self).write_i16(i
)
420 fn write_i32(&mut self, i
: i32) {
421 (**self).write_i32(i
)
423 fn write_i64(&mut self, i
: i64) {
424 (**self).write_i64(i
)
426 fn write_i128(&mut self, i
: i128
) {
427 (**self).write_i128(i
)
429 fn write_isize(&mut self, i
: isize) {
430 (**self).write_isize(i
)
434 /// A trait for creating instances of [`Hasher`].
436 /// A `BuildHasher` is typically used (e.g., by [`HashMap`]) to create
437 /// [`Hasher`]s for each key such that they are hashed independently of one
438 /// another, since [`Hasher`]s contain state.
440 /// For each instance of `BuildHasher`, the [`Hasher`]s created by
441 /// [`build_hasher`] should be identical. That is, if the same stream of bytes
442 /// is fed into each hasher, the same output will also be generated.
447 /// use std::collections::hash_map::RandomState;
448 /// use std::hash::{BuildHasher, Hasher};
450 /// let s = RandomState::new();
451 /// let mut hasher_1 = s.build_hasher();
452 /// let mut hasher_2 = s.build_hasher();
454 /// hasher_1.write_u32(8128);
455 /// hasher_2.write_u32(8128);
457 /// assert_eq!(hasher_1.finish(), hasher_2.finish());
460 /// [`build_hasher`]: BuildHasher::build_hasher
461 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
462 #[stable(since = "1.7.0", feature = "build_hasher")]
463 pub trait BuildHasher
{
464 /// Type of the hasher that will be created.
465 #[stable(since = "1.7.0", feature = "build_hasher")]
468 /// Creates a new hasher.
470 /// Each call to `build_hasher` on the same instance should produce identical
476 /// use std::collections::hash_map::RandomState;
477 /// use std::hash::BuildHasher;
479 /// let s = RandomState::new();
480 /// let new_s = s.build_hasher();
482 #[stable(since = "1.7.0", feature = "build_hasher")]
483 fn build_hasher(&self) -> Self::Hasher
;
485 /// Calculates the hash of a single value.
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.
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.
499 /// #![feature(build_hasher_simple_hash_one)]
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);
511 /// // Then later, in a `#[test]` for the type...
512 /// let bh = std::collections::hash_map::RandomState::new();
514 /// bh.hash_one(OrderAmbivalentPair(1, 2)),
515 /// bh.hash_one(OrderAmbivalentPair(2, 1))
518 /// bh.hash_one(OrderAmbivalentPair(10, 2)),
519 /// bh.hash_one(&OrderAmbivalentPair(2, 10))
522 #[unstable(feature = "build_hasher_simple_hash_one", issue = "86161")]
523 fn hash_one
<T
: Hash
>(&self, x
: T
) -> u64
527 let mut hasher
= self.build_hasher();
533 /// Used to create a default [`BuildHasher`] instance for types that implement
534 /// [`Hasher`] and [`Default`].
536 /// `BuildHasherDefault<H>` can be used when a type `H` implements [`Hasher`] and
537 /// [`Default`], and you need a corresponding [`BuildHasher`] instance, but none is
540 /// Any `BuildHasherDefault` is [zero-sized]. It can be created with
541 /// [`default`][method.default]. When using `BuildHasherDefault` with [`HashMap`] or
542 /// [`HashSet`], this doesn't need to be done, since they implement appropriate
543 /// [`Default`] instances themselves.
547 /// Using `BuildHasherDefault` to specify a custom [`BuildHasher`] for
551 /// use std::collections::HashMap;
552 /// use std::hash::{BuildHasherDefault, Hasher};
554 /// #[derive(Default)]
557 /// impl Hasher for MyHasher {
558 /// fn write(&mut self, bytes: &[u8]) {
559 /// // Your hashing algorithm goes here!
563 /// fn finish(&self) -> u64 {
564 /// // Your hashing algorithm goes here!
569 /// type MyBuildHasher = BuildHasherDefault<MyHasher>;
571 /// let hash_map = HashMap::<u32, u32, MyBuildHasher>::default();
574 /// [method.default]: BuildHasherDefault::default
575 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
576 /// [`HashSet`]: ../../std/collections/struct.HashSet.html
577 /// [zero-sized]: https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts
578 #[stable(since = "1.7.0", feature = "build_hasher")]
579 pub struct BuildHasherDefault
<H
>(marker
::PhantomData
<H
>);
581 #[stable(since = "1.9.0", feature = "core_impl_debug")]
582 impl<H
> fmt
::Debug
for BuildHasherDefault
<H
> {
583 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
584 f
.debug_struct("BuildHasherDefault").finish()
588 #[stable(since = "1.7.0", feature = "build_hasher")]
589 impl<H
: Default
+ Hasher
> BuildHasher
for BuildHasherDefault
<H
> {
592 fn build_hasher(&self) -> H
{
597 #[stable(since = "1.7.0", feature = "build_hasher")]
598 impl<H
> Clone
for BuildHasherDefault
<H
> {
599 fn clone(&self) -> BuildHasherDefault
<H
> {
600 BuildHasherDefault(marker
::PhantomData
)
604 #[stable(since = "1.7.0", feature = "build_hasher")]
605 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
606 impl<H
> const Default
for BuildHasherDefault
<H
> {
607 fn default() -> BuildHasherDefault
<H
> {
608 BuildHasherDefault(marker
::PhantomData
)
612 #[stable(since = "1.29.0", feature = "build_hasher_eq")]
613 impl<H
> PartialEq
for BuildHasherDefault
<H
> {
614 fn eq(&self, _other
: &BuildHasherDefault
<H
>) -> bool
{
619 #[stable(since = "1.29.0", feature = "build_hasher_eq")]
620 impl<H
> Eq
for BuildHasherDefault
<H
> {}
628 macro_rules
! impl_write
{
629 ($
(($ty
:ident
, $meth
:ident
),)*) => {$
(
630 #[stable(feature = "rust1", since = "1.0.0")]
633 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
638 fn hash_slice
<H
: Hasher
>(data
: &[$ty
], state
: &mut H
) {
639 let newlen
= data
.len() * mem
::size_of
::<$ty
>();
640 let ptr
= data
.as_ptr() as *const u8;
641 // SAFETY: `ptr` is valid and aligned, as this macro is only used
642 // for numeric primitives which have no padding. The new slice only
643 // spans across `data` and is never mutated, and its total size is the
644 // same as the original `data` so it can't be over `isize::MAX`.
645 state
.write(unsafe { slice::from_raw_parts(ptr, newlen) }
)
656 (usize, write_usize
),
661 (isize, write_isize
),
666 #[stable(feature = "rust1", since = "1.0.0")]
669 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
670 state
.write_u8(*self as u8)
674 #[stable(feature = "rust1", since = "1.0.0")]
677 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
678 state
.write_u32(*self as u32)
682 #[stable(feature = "rust1", since = "1.0.0")]
685 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
686 state
.write(self.as_bytes());
691 #[stable(feature = "never_hash", since = "1.29.0")]
694 fn hash
<H
: Hasher
>(&self, _
: &mut H
) {
699 macro_rules
! impl_hash_tuple
{
701 #[stable(feature = "rust1", since = "1.0.0")]
704 fn hash
<H
: Hasher
>(&self, _state
: &mut H
) {}
708 ( $
($name
:ident
)+) => (
709 #[stable(feature = "rust1", since = "1.0.0")]
710 impl<$
($name
: Hash
),+> Hash
for ($
($name
,)+) where last_type
!($
($name
,)+): ?Sized
{
711 #[allow(non_snake_case)]
713 fn hash
<S
: Hasher
>(&self, state
: &mut S
) {
714 let ($
(ref $name
,)+) = *self;
715 $
($name
.hash(state
);)+
721 macro_rules
! last_type
{
722 ($a
:ident
,) => { $a }
;
723 ($a
:ident
, $
($rest_a
:ident
,)+) => { last_type!($($rest_a,)+) }
;
727 impl_hash_tuple
! { A }
728 impl_hash_tuple
! { A B }
729 impl_hash_tuple
! { A B C }
730 impl_hash_tuple
! { A B C D }
731 impl_hash_tuple
! { A B C D E }
732 impl_hash_tuple
! { A B C D E F }
733 impl_hash_tuple
! { A B C D E F G }
734 impl_hash_tuple
! { A B C D E F G H }
735 impl_hash_tuple
! { A B C D E F G H I }
736 impl_hash_tuple
! { A B C D E F G H I J }
737 impl_hash_tuple
! { A B C D E F G H I J K }
738 impl_hash_tuple
! { A B C D E F G H I J K L }
740 #[stable(feature = "rust1", since = "1.0.0")]
741 impl<T
: Hash
> Hash
for [T
] {
743 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
744 self.len().hash(state
);
745 Hash
::hash_slice(self, state
)
749 #[stable(feature = "rust1", since = "1.0.0")]
750 impl<T
: ?Sized
+ Hash
> Hash
for &T
{
752 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
753 (**self).hash(state
);
757 #[stable(feature = "rust1", since = "1.0.0")]
758 impl<T
: ?Sized
+ Hash
> Hash
for &mut T
{
760 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
761 (**self).hash(state
);
765 #[stable(feature = "rust1", since = "1.0.0")]
766 impl<T
: ?Sized
> Hash
for *const T
{
768 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
769 let (address
, metadata
) = self.to_raw_parts();
770 state
.write_usize(address
as usize);
771 metadata
.hash(state
);
775 #[stable(feature = "rust1", since = "1.0.0")]
776 impl<T
: ?Sized
> Hash
for *mut T
{
778 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
779 let (address
, metadata
) = self.to_raw_parts();
780 state
.write_usize(address
as usize);
781 metadata
.hash(state
);