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")]
88 #[stable(feature = "rust1", since = "1.0.0")]
90 pub use self::sip::SipHasher;
92 #[unstable(feature = "hashmap_internals", issue = "0")]
95 pub use self::sip::SipHasher13;
101 /// Types implementing `Hash` are able to be [`hash`]ed with an instance of
104 /// ## Implementing `Hash`
106 /// You can derive `Hash` with `#[derive(Hash)]` if all fields implement `Hash`.
107 /// The resulting hash will be the combination of the values from calling
108 /// [`hash`] on each field.
112 /// struct Rustacean {
118 /// If you need more control over how a value is hashed, you can of course
119 /// implement the `Hash` trait yourself:
122 /// use std::hash::{Hash, Hasher};
130 /// impl Hash for Person {
131 /// fn hash<H: Hasher>(&self, state: &mut H) {
132 /// self.id.hash(state);
133 /// self.phone.hash(state);
138 /// ## `Hash` and `Eq`
140 /// When implementing both `Hash` and [`Eq`], it is important that the following
144 /// k1 == k2 -> hash(k1) == hash(k2)
147 /// In other words, if two keys are equal, their hashes must also be equal.
148 /// [`HashMap`] and [`HashSet`] both rely on this behavior.
150 /// Thankfully, you won't need to worry about upholding this property when
151 /// deriving both [`Eq`] and `Hash` with `#[derive(PartialEq, Eq, Hash)]`.
153 /// [`Eq`]: ../../std/cmp/trait.Eq.html
154 /// [`Hasher`]: trait.Hasher.html
155 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
156 /// [`HashSet`]: ../../std/collections/struct.HashSet.html
157 /// [`hash`]: #tymethod.hash
158 #[stable(feature = "rust1", since = "1.0.0")]
160 /// Feeds this value into the given [`Hasher`].
165 /// use std::collections::hash_map::DefaultHasher;
166 /// use std::hash::{Hash, Hasher};
168 /// let mut hasher = DefaultHasher::new();
169 /// 7920.hash(&mut hasher);
170 /// println!("Hash is {:x}!", hasher.finish());
173 /// [`Hasher`]: trait.Hasher.html
174 #[stable(feature = "rust1", since = "1.0.0")]
175 fn hash<H: Hasher>(&self, state: &mut H);
177 /// Feeds a slice of this type into the given [`Hasher`].
182 /// use std::collections::hash_map::DefaultHasher;
183 /// use std::hash::{Hash, Hasher};
185 /// let mut hasher = DefaultHasher::new();
186 /// let numbers = [6, 28, 496, 8128];
187 /// Hash::hash_slice(&numbers, &mut hasher);
188 /// println!("Hash is {:x}!", hasher.finish());
191 /// [`Hasher`]: trait.Hasher.html
192 #[stable(feature = "hash_slice", since = "1.3.0")]
193 fn hash_slice<H: Hasher>(data: &[Self], state: &mut H)
202 /// A trait for hashing an arbitrary stream of bytes.
204 /// Instances of `Hasher` usually represent state that is changed while hashing
207 /// `Hasher` provides a fairly basic interface for retrieving the generated hash
208 /// (with [`finish`]), and writing integers as well as slices of bytes into an
209 /// instance (with [`write`] and [`write_u8`] etc.). Most of the time, `Hasher`
210 /// instances are used in conjunction with the [`Hash`] trait.
215 /// use std::collections::hash_map::DefaultHasher;
216 /// use std::hash::Hasher;
218 /// let mut hasher = DefaultHasher::new();
220 /// hasher.write_u32(1989);
221 /// hasher.write_u8(11);
222 /// hasher.write_u8(9);
223 /// hasher.write(b"Huh?");
225 /// println!("Hash is {:x}!", hasher.finish());
228 /// [`Hash`]: trait.Hash.html
229 /// [`finish`]: #tymethod.finish
230 /// [`write`]: #tymethod.write
231 /// [`write_u8`]: #method.write_u8
232 #[stable(feature = "rust1", since = "1.0.0")]
234 /// Returns the hash value for the values written so far.
236 /// Despite its name, the method does not reset the hasher’s internal
237 /// state. Additional [`write`]s will continue from the current value.
238 /// If you need to start a fresh hash value, you will have to create
244 /// use std::collections::hash_map::DefaultHasher;
245 /// use std::hash::Hasher;
247 /// let mut hasher = DefaultHasher::new();
248 /// hasher.write(b"Cool!");
250 /// println!("Hash is {:x}!", hasher.finish());
253 /// [`write`]: #tymethod.write
254 #[stable(feature = "rust1", since = "1.0.0")]
255 fn finish(&self) -> u64;
257 /// Writes some data into this `Hasher`.
262 /// use std::collections::hash_map::DefaultHasher;
263 /// use std::hash::Hasher;
265 /// let mut hasher = DefaultHasher::new();
266 /// let data = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef];
268 /// hasher.write(&data);
270 /// println!("Hash is {:x}!", hasher.finish());
272 #[stable(feature = "rust1", since = "1.0.0")]
273 fn write(&mut self, bytes: &[u8]);
275 /// Writes a single `u8` into this hasher.
277 #[stable(feature = "hasher_write", since = "1.3.0")]
278 fn write_u8(&mut self, i: u8) {
281 /// Writes a single `u16` into this hasher.
283 #[stable(feature = "hasher_write", since = "1.3.0")]
284 fn write_u16(&mut self, i: u16) {
285 self.write(&unsafe { mem::transmute::<_, [u8; 2]>(i) })
287 /// Writes a single `u32` into this hasher.
289 #[stable(feature = "hasher_write", since = "1.3.0")]
290 fn write_u32(&mut self, i: u32) {
291 self.write(&unsafe { mem::transmute::<_, [u8; 4]>(i) })
293 /// Writes a single `u64` into this hasher.
295 #[stable(feature = "hasher_write", since = "1.3.0")]
296 fn write_u64(&mut self, i: u64) {
297 self.write(&unsafe { mem::transmute::<_, [u8; 8]>(i) })
299 /// Writes a single `u128` into this hasher.
301 #[stable(feature = "i128", since = "1.26.0")]
302 fn write_u128(&mut self, i: u128) {
303 self.write(&unsafe { mem::transmute::<_, [u8; 16]>(i) })
305 /// Writes a single `usize` into this hasher.
307 #[stable(feature = "hasher_write", since = "1.3.0")]
308 fn write_usize(&mut self, i: usize) {
310 ::slice::from_raw_parts(&i as *const usize as *const u8, mem::size_of::<usize>())
315 /// Writes a single `i8` into this hasher.
317 #[stable(feature = "hasher_write", since = "1.3.0")]
318 fn write_i8(&mut self, i: i8) {
319 self.write_u8(i as u8)
321 /// Writes a single `i16` into this hasher.
323 #[stable(feature = "hasher_write", since = "1.3.0")]
324 fn write_i16(&mut self, i: i16) {
325 self.write_u16(i as u16)
327 /// Writes a single `i32` into this hasher.
329 #[stable(feature = "hasher_write", since = "1.3.0")]
330 fn write_i32(&mut self, i: i32) {
331 self.write_u32(i as u32)
333 /// Writes a single `i64` into this hasher.
335 #[stable(feature = "hasher_write", since = "1.3.0")]
336 fn write_i64(&mut self, i: i64) {
337 self.write_u64(i as u64)
339 /// Writes a single `i128` into this hasher.
341 #[stable(feature = "i128", since = "1.26.0")]
342 fn write_i128(&mut self, i: i128) {
343 self.write_u128(i as u128)
345 /// Writes a single `isize` into this hasher.
347 #[stable(feature = "hasher_write", since = "1.3.0")]
348 fn write_isize(&mut self, i: isize) {
349 self.write_usize(i as usize)
353 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
354 impl<H: Hasher + ?Sized> Hasher for &mut H {
355 fn finish(&self) -> u64 {
358 fn write(&mut self, bytes: &[u8]) {
359 (**self).write(bytes)
361 fn write_u8(&mut self, i: u8) {
364 fn write_u16(&mut self, i: u16) {
365 (**self).write_u16(i)
367 fn write_u32(&mut self, i: u32) {
368 (**self).write_u32(i)
370 fn write_u64(&mut self, i: u64) {
371 (**self).write_u64(i)
373 fn write_u128(&mut self, i: u128) {
374 (**self).write_u128(i)
376 fn write_usize(&mut self, i: usize) {
377 (**self).write_usize(i)
379 fn write_i8(&mut self, i: i8) {
382 fn write_i16(&mut self, i: i16) {
383 (**self).write_i16(i)
385 fn write_i32(&mut self, i: i32) {
386 (**self).write_i32(i)
388 fn write_i64(&mut self, i: i64) {
389 (**self).write_i64(i)
391 fn write_i128(&mut self, i: i128) {
392 (**self).write_i128(i)
394 fn write_isize(&mut self, i: isize) {
395 (**self).write_isize(i)
399 /// A trait for creating instances of [`Hasher`].
401 /// A `BuildHasher` is typically used (e.g., by [`HashMap`]) to create
402 /// [`Hasher`]s for each key such that they are hashed independently of one
403 /// another, since [`Hasher`]s contain state.
405 /// For each instance of `BuildHasher`, the [`Hasher`]s created by
406 /// [`build_hasher`] should be identical. That is, if the same stream of bytes
407 /// is fed into each hasher, the same output will also be generated.
412 /// use std::collections::hash_map::RandomState;
413 /// use std::hash::{BuildHasher, Hasher};
415 /// let s = RandomState::new();
416 /// let mut hasher_1 = s.build_hasher();
417 /// let mut hasher_2 = s.build_hasher();
419 /// hasher_1.write_u32(8128);
420 /// hasher_2.write_u32(8128);
422 /// assert_eq!(hasher_1.finish(), hasher_2.finish());
425 /// [`build_hasher`]: #tymethod.build_hasher
426 /// [`Hasher`]: trait.Hasher.html
427 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
428 #[stable(since = "1.7.0", feature = "build_hasher")]
429 pub trait BuildHasher {
430 /// Type of the hasher that will be created.
431 #[stable(since = "1.7.0", feature = "build_hasher")]
434 /// Creates a new hasher.
436 /// Each call to `build_hasher` on the same instance should produce identical
442 /// use std::collections::hash_map::RandomState;
443 /// use std::hash::BuildHasher;
445 /// let s = RandomState::new();
446 /// let new_s = s.build_hasher();
449 /// [`Hasher`]: trait.Hasher.html
450 #[stable(since = "1.7.0", feature = "build_hasher")]
451 fn build_hasher(&self) -> Self::Hasher;
454 /// Used to create a default [`BuildHasher`] instance for types that implement
455 /// [`Hasher`] and [`Default`].
457 /// `BuildHasherDefault<H>` can be used when a type `H` implements [`Hasher`] and
458 /// [`Default`], and you need a corresponding [`BuildHasher`] instance, but none is
461 /// Any `BuildHasherDefault` is [zero-sized]. It can be created with
462 /// [`default`][method.Default]. When using `BuildHasherDefault` with [`HashMap`] or
463 /// [`HashSet`], this doesn't need to be done, since they implement appropriate
464 /// [`Default`] instances themselves.
468 /// Using `BuildHasherDefault` to specify a custom [`BuildHasher`] for
472 /// use std::collections::HashMap;
473 /// use std::hash::{BuildHasherDefault, Hasher};
475 /// #[derive(Default)]
478 /// impl Hasher for MyHasher {
479 /// fn write(&mut self, bytes: &[u8]) {
480 /// // Your hashing algorithm goes here!
484 /// fn finish(&self) -> u64 {
485 /// // Your hashing algorithm goes here!
490 /// type MyBuildHasher = BuildHasherDefault<MyHasher>;
492 /// let hash_map = HashMap::<u32, u32, MyBuildHasher>::default();
495 /// [`BuildHasher`]: trait.BuildHasher.html
496 /// [`Default`]: ../default/trait.Default.html
497 /// [method.default]: #method.default
498 /// [`Hasher`]: trait.Hasher.html
499 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
500 /// [`HashSet`]: ../../std/collections/struct.HashSet.html
501 /// [zero-sized]: https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts
502 #[stable(since = "1.7.0", feature = "build_hasher")]
503 pub struct BuildHasherDefault<H>(marker::PhantomData<H>);
505 #[stable(since = "1.9.0", feature = "core_impl_debug")]
506 impl<H> fmt::Debug for BuildHasherDefault<H> {
507 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
508 f.pad("BuildHasherDefault")
512 #[stable(since = "1.7.0", feature = "build_hasher")]
513 impl<H: Default + Hasher> BuildHasher for BuildHasherDefault<H> {
516 fn build_hasher(&self) -> H {
521 #[stable(since = "1.7.0", feature = "build_hasher")]
522 impl<H> Clone for BuildHasherDefault<H> {
523 fn clone(&self) -> BuildHasherDefault<H> {
524 BuildHasherDefault(marker::PhantomData)
528 #[stable(since = "1.7.0", feature = "build_hasher")]
529 impl<H> Default for BuildHasherDefault<H> {
530 fn default() -> BuildHasherDefault<H> {
531 BuildHasherDefault(marker::PhantomData)
535 #[stable(since = "1.29.0", feature = "build_hasher_eq")]
536 impl<H> PartialEq for BuildHasherDefault<H> {
537 fn eq(&self, _other: &BuildHasherDefault<H>) -> bool {
542 #[stable(since = "1.29.0", feature = "build_hasher_eq")]
543 impl<H> Eq for BuildHasherDefault<H> {}
545 //////////////////////////////////////////////////////////////////////////////
552 macro_rules! impl_write {
553 ($(($ty:ident, $meth:ident),)*) => {$(
554 #[stable(feature = "rust1", since = "1.0.0")]
556 fn hash<H: Hasher>(&self, state: &mut H) {
560 fn hash_slice<H: Hasher>(data: &[$ty], state: &mut H) {
561 let newlen = data.len() * mem::size_of::<$ty>();
562 let ptr = data.as_ptr() as *const u8;
563 state.write(unsafe { slice::from_raw_parts(ptr, newlen) })
574 (usize, write_usize),
579 (isize, write_isize),
584 #[stable(feature = "rust1", since = "1.0.0")]
586 fn hash<H: Hasher>(&self, state: &mut H) {
587 state.write_u8(*self as u8)
591 #[stable(feature = "rust1", since = "1.0.0")]
593 fn hash<H: Hasher>(&self, state: &mut H) {
594 state.write_u32(*self as u32)
598 #[stable(feature = "rust1", since = "1.0.0")]
600 fn hash<H: Hasher>(&self, state: &mut H) {
601 state.write(self.as_bytes());
606 #[stable(feature = "never_hash", since = "1.29.0")]
608 fn hash<H: Hasher>(&self, _: &mut H) {
613 macro_rules! impl_hash_tuple {
615 #[stable(feature = "rust1", since = "1.0.0")]
617 fn hash<H: Hasher>(&self, _state: &mut H) {}
621 ( $($name:ident)+) => (
622 #[stable(feature = "rust1", since = "1.0.0")]
623 impl<$($name: Hash),*> Hash for ($($name,)*) where last_type!($($name,)+): ?Sized {
624 #[allow(non_snake_case)]
625 fn hash<S: Hasher>(&self, state: &mut S) {
626 let ($(ref $name,)*) = *self;
627 $($name.hash(state);)*
633 macro_rules! last_type {
634 ($a:ident,) => { $a };
635 ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
639 impl_hash_tuple! { A }
640 impl_hash_tuple! { A B }
641 impl_hash_tuple! { A B C }
642 impl_hash_tuple! { A B C D }
643 impl_hash_tuple! { A B C D E }
644 impl_hash_tuple! { A B C D E F }
645 impl_hash_tuple! { A B C D E F G }
646 impl_hash_tuple! { A B C D E F G H }
647 impl_hash_tuple! { A B C D E F G H I }
648 impl_hash_tuple! { A B C D E F G H I J }
649 impl_hash_tuple! { A B C D E F G H I J K }
650 impl_hash_tuple! { A B C D E F G H I J K L }
652 #[stable(feature = "rust1", since = "1.0.0")]
653 impl<T: Hash> Hash for [T] {
654 fn hash<H: Hasher>(&self, state: &mut H) {
655 self.len().hash(state);
656 Hash::hash_slice(self, state)
661 #[stable(feature = "rust1", since = "1.0.0")]
662 impl<T: ?Sized + Hash> Hash for &T {
663 fn hash<H: Hasher>(&self, state: &mut H) {
664 (**self).hash(state);
668 #[stable(feature = "rust1", since = "1.0.0")]
669 impl<T: ?Sized + Hash> Hash for &mut T {
670 fn hash<H: Hasher>(&self, state: &mut H) {
671 (**self).hash(state);
675 #[stable(feature = "rust1", since = "1.0.0")]
676 impl<T: ?Sized> Hash for *const T {
677 fn hash<H: Hasher>(&self, state: &mut H) {
678 if mem::size_of::<Self>() == mem::size_of::<usize>() {
680 state.write_usize(*self as *const () as usize);
683 let (a, b) = unsafe {
684 *(self as *const Self as *const (usize, usize))
686 state.write_usize(a);
687 state.write_usize(b);
692 #[stable(feature = "rust1", since = "1.0.0")]
693 impl<T: ?Sized> Hash for *mut T {
694 fn hash<H: Hasher>(&self, state: &mut H) {
695 if mem::size_of::<Self>() == mem::size_of::<usize>() {
697 state.write_usize(*self as *const () as usize);
700 let (a, b) = unsafe {
701 *(self as *const Self as *const (usize, usize))
703 state.write_usize(a);
704 state.write_usize(b);