1 //! Generic hashing support.
3 //! This module provides a generic way to compute the hash of a value. The
4 //! simplest way to make a type hashable is to use `#[derive(Hash)]`:
9 //! use std::collections::hash_map::DefaultHasher;
10 //! use std::hash::{Hash, Hasher};
19 //! let person1 = Person {
21 //! name: "Janet".to_string(),
22 //! phone: 555_666_7777,
24 //! let person2 = Person {
26 //! name: "Bob".to_string(),
27 //! phone: 555_666_7777,
30 //! assert!(calculate_hash(&person1) != calculate_hash(&person2));
32 //! fn calculate_hash<T: Hash>(t: &T) -> u64 {
33 //! let mut s = DefaultHasher::new();
39 //! If you need more control over how a value is hashed, you need to implement
40 //! the [`Hash`] trait:
42 //! [`Hash`]: trait.Hash.html
45 //! use std::collections::hash_map::DefaultHasher;
46 //! use std::hash::{Hash, Hasher};
50 //! # #[allow(dead_code)]
55 //! impl Hash for Person {
56 //! fn hash<H: Hasher>(&self, state: &mut H) {
57 //! self.id.hash(state);
58 //! self.phone.hash(state);
62 //! let person1 = Person {
64 //! name: "Janet".to_string(),
65 //! phone: 555_666_7777,
67 //! let person2 = Person {
69 //! name: "Bob".to_string(),
70 //! phone: 555_666_7777,
73 //! assert_eq!(calculate_hash(&person1), calculate_hash(&person2));
75 //! fn calculate_hash<T: Hash>(t: &T) -> u64 {
76 //! let mut s = DefaultHasher::new();
82 #![stable(feature = "rust1", since = "1.0.0")]
87 #[stable(feature = "rust1", since = "1.0.0")]
89 pub use self::sip::SipHasher;
91 #[unstable(feature = "hashmap_internals", issue = "0")]
94 pub use self::sip::SipHasher13;
100 /// Types implementing `Hash` are able to be [`hash`]ed with an instance of
103 /// ## Implementing `Hash`
105 /// You can derive `Hash` with `#[derive(Hash)]` if all fields implement `Hash`.
106 /// The resulting hash will be the combination of the values from calling
107 /// [`hash`] on each field.
111 /// struct Rustacean {
117 /// If you need more control over how a value is hashed, you can of course
118 /// implement the `Hash` trait yourself:
121 /// use std::hash::{Hash, Hasher};
129 /// impl Hash for Person {
130 /// fn hash<H: Hasher>(&self, state: &mut H) {
131 /// self.id.hash(state);
132 /// self.phone.hash(state);
137 /// ## `Hash` and `Eq`
139 /// When implementing both `Hash` and [`Eq`], it is important that the following
143 /// k1 == k2 -> hash(k1) == hash(k2)
146 /// In other words, if two keys are equal, their hashes must also be equal.
147 /// [`HashMap`] and [`HashSet`] both rely on this behavior.
149 /// Thankfully, you won't need to worry about upholding this property when
150 /// deriving both [`Eq`] and `Hash` with `#[derive(PartialEq, Eq, Hash)]`.
152 /// [`Eq`]: ../../std/cmp/trait.Eq.html
153 /// [`Hasher`]: trait.Hasher.html
154 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
155 /// [`HashSet`]: ../../std/collections/struct.HashSet.html
156 /// [`hash`]: #tymethod.hash
157 #[stable(feature = "rust1", since = "1.0.0")]
159 /// Feeds this value into the given [`Hasher`].
164 /// use std::collections::hash_map::DefaultHasher;
165 /// use std::hash::{Hash, Hasher};
167 /// let mut hasher = DefaultHasher::new();
168 /// 7920.hash(&mut hasher);
169 /// println!("Hash is {:x}!", hasher.finish());
172 /// [`Hasher`]: trait.Hasher.html
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`].
181 /// use std::collections::hash_map::DefaultHasher;
182 /// use std::hash::{Hash, Hasher};
184 /// let mut hasher = DefaultHasher::new();
185 /// let numbers = [6, 28, 496, 8128];
186 /// Hash::hash_slice(&numbers, &mut hasher);
187 /// println!("Hash is {:x}!", hasher.finish());
190 /// [`Hasher`]: trait.Hasher.html
191 #[stable(feature = "hash_slice", since = "1.3.0")]
192 fn hash_slice<H: Hasher>(data: &[Self], state: &mut H)
201 /// A trait for hashing an arbitrary stream of bytes.
203 /// Instances of `Hasher` usually represent state that is changed while hashing
206 /// `Hasher` provides a fairly basic interface for retrieving the generated hash
207 /// (with [`finish`]), and writing integers as well as slices of bytes into an
208 /// instance (with [`write`] and [`write_u8`] etc.). Most of the time, `Hasher`
209 /// instances are used in conjunction with the [`Hash`] trait.
214 /// use std::collections::hash_map::DefaultHasher;
215 /// use std::hash::Hasher;
217 /// let mut hasher = DefaultHasher::new();
219 /// hasher.write_u32(1989);
220 /// hasher.write_u8(11);
221 /// hasher.write_u8(9);
222 /// hasher.write(b"Huh?");
224 /// println!("Hash is {:x}!", hasher.finish());
227 /// [`Hash`]: trait.Hash.html
228 /// [`finish`]: #tymethod.finish
229 /// [`write`]: #tymethod.write
230 /// [`write_u8`]: #method.write_u8
231 #[stable(feature = "rust1", since = "1.0.0")]
233 /// Returns the hash value for the values written so far.
235 /// Despite its name, the method does not reset the hasher’s internal
236 /// state. Additional [`write`]s will continue from the current value.
237 /// If you need to start a fresh hash value, you will have to create
243 /// use std::collections::hash_map::DefaultHasher;
244 /// use std::hash::Hasher;
246 /// let mut hasher = DefaultHasher::new();
247 /// hasher.write(b"Cool!");
249 /// println!("Hash is {:x}!", hasher.finish());
252 /// [`write`]: #tymethod.write
253 #[stable(feature = "rust1", since = "1.0.0")]
254 fn finish(&self) -> u64;
256 /// Writes some data into this `Hasher`.
261 /// use std::collections::hash_map::DefaultHasher;
262 /// use std::hash::Hasher;
264 /// let mut hasher = DefaultHasher::new();
265 /// let data = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef];
267 /// hasher.write(&data);
269 /// println!("Hash is {:x}!", hasher.finish());
271 #[stable(feature = "rust1", since = "1.0.0")]
272 fn write(&mut self, bytes: &[u8]);
274 /// Writes a single `u8` into this hasher.
276 #[stable(feature = "hasher_write", since = "1.3.0")]
277 fn write_u8(&mut self, i: u8) {
280 /// Writes a single `u16` into this hasher.
282 #[stable(feature = "hasher_write", since = "1.3.0")]
283 fn write_u16(&mut self, i: u16) {
284 self.write(&i.to_ne_bytes())
286 /// Writes a single `u32` into this hasher.
288 #[stable(feature = "hasher_write", since = "1.3.0")]
289 fn write_u32(&mut self, i: u32) {
290 self.write(&i.to_ne_bytes())
292 /// Writes a single `u64` into this hasher.
294 #[stable(feature = "hasher_write", since = "1.3.0")]
295 fn write_u64(&mut self, i: u64) {
296 self.write(&i.to_ne_bytes())
298 /// Writes a single `u128` into this hasher.
300 #[stable(feature = "i128", since = "1.26.0")]
301 fn write_u128(&mut self, i: u128) {
302 self.write(&i.to_ne_bytes())
304 /// Writes a single `usize` into this hasher.
306 #[stable(feature = "hasher_write", since = "1.3.0")]
307 fn write_usize(&mut self, i: usize) {
308 self.write(&i.to_ne_bytes())
311 /// Writes a single `i8` into this hasher.
313 #[stable(feature = "hasher_write", since = "1.3.0")]
314 fn write_i8(&mut self, i: i8) {
315 self.write_u8(i as u8)
317 /// Writes a single `i16` into this hasher.
319 #[stable(feature = "hasher_write", since = "1.3.0")]
320 fn write_i16(&mut self, i: i16) {
321 self.write(&i.to_ne_bytes())
323 /// Writes a single `i32` into this hasher.
325 #[stable(feature = "hasher_write", since = "1.3.0")]
326 fn write_i32(&mut self, i: i32) {
327 self.write(&i.to_ne_bytes())
329 /// Writes a single `i64` into this hasher.
331 #[stable(feature = "hasher_write", since = "1.3.0")]
332 fn write_i64(&mut self, i: i64) {
333 self.write(&i.to_ne_bytes())
335 /// Writes a single `i128` into this hasher.
337 #[stable(feature = "i128", since = "1.26.0")]
338 fn write_i128(&mut self, i: i128) {
339 self.write(&i.to_ne_bytes())
341 /// Writes a single `isize` into this hasher.
343 #[stable(feature = "hasher_write", since = "1.3.0")]
344 fn write_isize(&mut self, i: isize) {
345 self.write(&i.to_ne_bytes())
349 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
350 impl<H: Hasher + ?Sized> Hasher for &mut H {
351 fn finish(&self) -> u64 {
354 fn write(&mut self, bytes: &[u8]) {
355 (**self).write(bytes)
357 fn write_u8(&mut self, i: u8) {
360 fn write_u16(&mut self, i: u16) {
361 (**self).write_u16(i)
363 fn write_u32(&mut self, i: u32) {
364 (**self).write_u32(i)
366 fn write_u64(&mut self, i: u64) {
367 (**self).write_u64(i)
369 fn write_u128(&mut self, i: u128) {
370 (**self).write_u128(i)
372 fn write_usize(&mut self, i: usize) {
373 (**self).write_usize(i)
375 fn write_i8(&mut self, i: i8) {
378 fn write_i16(&mut self, i: i16) {
379 (**self).write_i16(i)
381 fn write_i32(&mut self, i: i32) {
382 (**self).write_i32(i)
384 fn write_i64(&mut self, i: i64) {
385 (**self).write_i64(i)
387 fn write_i128(&mut self, i: i128) {
388 (**self).write_i128(i)
390 fn write_isize(&mut self, i: isize) {
391 (**self).write_isize(i)
395 /// A trait for creating instances of [`Hasher`].
397 /// A `BuildHasher` is typically used (e.g., by [`HashMap`]) to create
398 /// [`Hasher`]s for each key such that they are hashed independently of one
399 /// another, since [`Hasher`]s contain state.
401 /// For each instance of `BuildHasher`, the [`Hasher`]s created by
402 /// [`build_hasher`] should be identical. That is, if the same stream of bytes
403 /// is fed into each hasher, the same output will also be generated.
408 /// use std::collections::hash_map::RandomState;
409 /// use std::hash::{BuildHasher, Hasher};
411 /// let s = RandomState::new();
412 /// let mut hasher_1 = s.build_hasher();
413 /// let mut hasher_2 = s.build_hasher();
415 /// hasher_1.write_u32(8128);
416 /// hasher_2.write_u32(8128);
418 /// assert_eq!(hasher_1.finish(), hasher_2.finish());
421 /// [`build_hasher`]: #tymethod.build_hasher
422 /// [`Hasher`]: trait.Hasher.html
423 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
424 #[stable(since = "1.7.0", feature = "build_hasher")]
425 pub trait BuildHasher {
426 /// Type of the hasher that will be created.
427 #[stable(since = "1.7.0", feature = "build_hasher")]
430 /// Creates a new hasher.
432 /// Each call to `build_hasher` on the same instance should produce identical
438 /// use std::collections::hash_map::RandomState;
439 /// use std::hash::BuildHasher;
441 /// let s = RandomState::new();
442 /// let new_s = s.build_hasher();
445 /// [`Hasher`]: trait.Hasher.html
446 #[stable(since = "1.7.0", feature = "build_hasher")]
447 fn build_hasher(&self) -> Self::Hasher;
450 /// Used to create a default [`BuildHasher`] instance for types that implement
451 /// [`Hasher`] and [`Default`].
453 /// `BuildHasherDefault<H>` can be used when a type `H` implements [`Hasher`] and
454 /// [`Default`], and you need a corresponding [`BuildHasher`] instance, but none is
457 /// Any `BuildHasherDefault` is [zero-sized]. It can be created with
458 /// [`default`][method.Default]. When using `BuildHasherDefault` with [`HashMap`] or
459 /// [`HashSet`], this doesn't need to be done, since they implement appropriate
460 /// [`Default`] instances themselves.
464 /// Using `BuildHasherDefault` to specify a custom [`BuildHasher`] for
468 /// use std::collections::HashMap;
469 /// use std::hash::{BuildHasherDefault, Hasher};
471 /// #[derive(Default)]
474 /// impl Hasher for MyHasher {
475 /// fn write(&mut self, bytes: &[u8]) {
476 /// // Your hashing algorithm goes here!
480 /// fn finish(&self) -> u64 {
481 /// // Your hashing algorithm goes here!
486 /// type MyBuildHasher = BuildHasherDefault<MyHasher>;
488 /// let hash_map = HashMap::<u32, u32, MyBuildHasher>::default();
491 /// [`BuildHasher`]: trait.BuildHasher.html
492 /// [`Default`]: ../default/trait.Default.html
493 /// [method.default]: #method.default
494 /// [`Hasher`]: trait.Hasher.html
495 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
496 /// [`HashSet`]: ../../std/collections/struct.HashSet.html
497 /// [zero-sized]: https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts
498 #[stable(since = "1.7.0", feature = "build_hasher")]
499 pub struct BuildHasherDefault<H>(marker::PhantomData<H>);
501 #[stable(since = "1.9.0", feature = "core_impl_debug")]
502 impl<H> fmt::Debug for BuildHasherDefault<H> {
503 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
504 f.pad("BuildHasherDefault")
508 #[stable(since = "1.7.0", feature = "build_hasher")]
509 impl<H: Default + Hasher> BuildHasher for BuildHasherDefault<H> {
512 fn build_hasher(&self) -> H {
517 #[stable(since = "1.7.0", feature = "build_hasher")]
518 impl<H> Clone for BuildHasherDefault<H> {
519 fn clone(&self) -> BuildHasherDefault<H> {
520 BuildHasherDefault(marker::PhantomData)
524 #[stable(since = "1.7.0", feature = "build_hasher")]
525 impl<H> Default for BuildHasherDefault<H> {
526 fn default() -> BuildHasherDefault<H> {
527 BuildHasherDefault(marker::PhantomData)
531 #[stable(since = "1.29.0", feature = "build_hasher_eq")]
532 impl<H> PartialEq for BuildHasherDefault<H> {
533 fn eq(&self, _other: &BuildHasherDefault<H>) -> bool {
538 #[stable(since = "1.29.0", feature = "build_hasher_eq")]
539 impl<H> Eq for BuildHasherDefault<H> {}
541 //////////////////////////////////////////////////////////////////////////////
549 macro_rules! impl_write {
550 ($(($ty:ident, $meth:ident),)*) => {$(
551 #[stable(feature = "rust1", since = "1.0.0")]
553 fn hash<H: Hasher>(&self, state: &mut H) {
557 fn hash_slice<H: Hasher>(data: &[$ty], state: &mut H) {
558 let newlen = data.len() * mem::size_of::<$ty>();
559 let ptr = data.as_ptr() as *const u8;
560 state.write(unsafe { slice::from_raw_parts(ptr, newlen) })
571 (usize, write_usize),
576 (isize, write_isize),
581 #[stable(feature = "rust1", since = "1.0.0")]
583 fn hash<H: Hasher>(&self, state: &mut H) {
584 state.write_u8(*self as u8)
588 #[stable(feature = "rust1", since = "1.0.0")]
590 fn hash<H: Hasher>(&self, state: &mut H) {
591 state.write_u32(*self as u32)
595 #[stable(feature = "rust1", since = "1.0.0")]
597 fn hash<H: Hasher>(&self, state: &mut H) {
598 state.write(self.as_bytes());
603 #[stable(feature = "never_hash", since = "1.29.0")]
605 fn hash<H: Hasher>(&self, _: &mut H) {
610 macro_rules! impl_hash_tuple {
612 #[stable(feature = "rust1", since = "1.0.0")]
614 fn hash<H: Hasher>(&self, _state: &mut H) {}
618 ( $($name:ident)+) => (
619 #[stable(feature = "rust1", since = "1.0.0")]
620 impl<$($name: Hash),+> Hash for ($($name,)+) where last_type!($($name,)+): ?Sized {
621 #[allow(non_snake_case)]
622 fn hash<S: Hasher>(&self, state: &mut S) {
623 let ($(ref $name,)+) = *self;
624 $($name.hash(state);)+
630 macro_rules! last_type {
631 ($a:ident,) => { $a };
632 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
636 impl_hash_tuple! { A }
637 impl_hash_tuple! { A B }
638 impl_hash_tuple! { A B C }
639 impl_hash_tuple! { A B C D }
640 impl_hash_tuple! { A B C D E }
641 impl_hash_tuple! { A B C D E F }
642 impl_hash_tuple! { A B C D E F G }
643 impl_hash_tuple! { A B C D E F G H }
644 impl_hash_tuple! { A B C D E F G H I }
645 impl_hash_tuple! { A B C D E F G H I J }
646 impl_hash_tuple! { A B C D E F G H I J K }
647 impl_hash_tuple! { A B C D E F G H I J K L }
649 #[stable(feature = "rust1", since = "1.0.0")]
650 impl<T: Hash> Hash for [T] {
651 fn hash<H: Hasher>(&self, state: &mut H) {
652 self.len().hash(state);
653 Hash::hash_slice(self, state)
658 #[stable(feature = "rust1", since = "1.0.0")]
659 impl<T: ?Sized + Hash> Hash for &T {
660 fn hash<H: Hasher>(&self, state: &mut H) {
661 (**self).hash(state);
665 #[stable(feature = "rust1", since = "1.0.0")]
666 impl<T: ?Sized + Hash> Hash for &mut T {
667 fn hash<H: Hasher>(&self, state: &mut H) {
668 (**self).hash(state);
672 #[stable(feature = "rust1", since = "1.0.0")]
673 impl<T: ?Sized> Hash for *const T {
674 fn hash<H: Hasher>(&self, state: &mut H) {
675 if mem::size_of::<Self>() == mem::size_of::<usize>() {
677 state.write_usize(*self as *const () as usize);
680 let (a, b) = unsafe {
681 *(self as *const Self as *const (usize, usize))
683 state.write_usize(a);
684 state.write_usize(b);
689 #[stable(feature = "rust1", since = "1.0.0")]
690 impl<T: ?Sized> Hash for *mut T {
691 fn hash<H: Hasher>(&self, state: &mut H) {
692 if mem::size_of::<Self>() == mem::size_of::<usize>() {
694 state.write_usize(*self as *const () as usize);
697 let (a, b) = unsafe {
698 *(self as *const Self as *const (usize, usize))
700 state.write_usize(a);
701 state.write_usize(b);