1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Generic hashing support.
13 //! This module provides a generic way to compute the hash of a value. The
14 //! simplest way to make a type hashable is to use `#[derive(Hash)]`:
19 //! use std::collections::hash_map::DefaultHasher;
20 //! use std::hash::{Hash, Hasher};
29 //! let person1 = Person {
31 //! name: "Janet".to_string(),
32 //! phone: 555_666_7777,
34 //! let person2 = Person {
36 //! name: "Bob".to_string(),
37 //! phone: 555_666_7777,
40 //! assert!(calculate_hash(&person1) != calculate_hash(&person2));
42 //! fn calculate_hash<T: Hash>(t: &T) -> u64 {
43 //! let mut s = DefaultHasher::new();
49 //! If you need more control over how a value is hashed, you need to implement
50 //! the [`Hash`] trait:
52 //! [`Hash`]: trait.Hash.html
55 //! use std::collections::hash_map::DefaultHasher;
56 //! use std::hash::{Hash, Hasher};
60 //! # #[allow(dead_code)]
65 //! impl Hash for Person {
66 //! fn hash<H: Hasher>(&self, state: &mut H) {
67 //! self.id.hash(state);
68 //! self.phone.hash(state);
72 //! let person1 = Person {
74 //! name: "Janet".to_string(),
75 //! phone: 555_666_7777,
77 //! let person2 = Person {
79 //! name: "Bob".to_string(),
80 //! phone: 555_666_7777,
83 //! assert_eq!(calculate_hash(&person1), calculate_hash(&person2));
85 //! fn calculate_hash<T: Hash>(t: &T) -> u64 {
86 //! let mut s = DefaultHasher::new();
92 #![stable(feature = "rust1", since = "1.0.0")]
98 #[stable(feature = "rust1", since = "1.0.0")]
100 pub use self::sip
::SipHasher
;
102 #[unstable(feature = "sip_hash_13", issue = "34767")]
104 pub use self::sip
::{SipHasher13, SipHasher24}
;
110 /// Types implementing `Hash` are able to be [`hash`]ed with an instance of
113 /// ## Implementing `Hash`
115 /// You can derive `Hash` with `#[derive(Hash)]` if all fields implement `Hash`.
116 /// The resulting hash will be the combination of the values from calling
117 /// [`hash`] on each field.
121 /// struct Rustacean {
127 /// If you need more control over how a value is hashed, you can of course
128 /// implement the `Hash` trait yourself:
131 /// use std::hash::{Hash, Hasher};
139 /// impl Hash for Person {
140 /// fn hash<H: Hasher>(&self, state: &mut H) {
141 /// self.id.hash(state);
142 /// self.phone.hash(state);
147 /// ## `Hash` and `Eq`
149 /// When implementing both `Hash` and [`Eq`], it is important that the following
153 /// k1 == k2 -> hash(k1) == hash(k2)
156 /// In other words, if two keys are equal, their hashes must also be equal.
157 /// [`HashMap`] and [`HashSet`] both rely on this behavior.
159 /// Thankfully, you won't need to worry about upholding this property when
160 /// deriving both [`Eq`] and `Hash` with `#[derive(PartialEq, Eq, Hash)]`.
162 /// [`Eq`]: ../../std/cmp/trait.Eq.html
163 /// [`Hasher`]: trait.Hasher.html
164 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
165 /// [`HashSet`]: ../../std/collections/struct.HashSet.html
166 /// [`hash`]: #tymethod.hash
167 #[stable(feature = "rust1", since = "1.0.0")]
169 /// Feeds this value into the given [`Hasher`].
174 /// use std::collections::hash_map::DefaultHasher;
175 /// use std::hash::{Hash, Hasher};
177 /// let mut hasher = DefaultHasher::new();
178 /// 7920.hash(&mut hasher);
179 /// println!("Hash is {:x}!", hasher.finish());
182 /// [`Hasher`]: trait.Hasher.html
183 #[stable(feature = "rust1", since = "1.0.0")]
184 fn hash
<H
: Hasher
>(&self, state
: &mut H
);
186 /// Feeds a slice of this type into the given [`Hasher`].
191 /// use std::collections::hash_map::DefaultHasher;
192 /// use std::hash::{Hash, Hasher};
194 /// let mut hasher = DefaultHasher::new();
195 /// let numbers = [6, 28, 496, 8128];
196 /// Hash::hash_slice(&numbers, &mut hasher);
197 /// println!("Hash is {:x}!", hasher.finish());
200 /// [`Hasher`]: trait.Hasher.html
201 #[stable(feature = "hash_slice", since = "1.3.0")]
202 fn hash_slice
<H
: Hasher
>(data
: &[Self], state
: &mut H
)
211 /// A trait for hashing an arbitrary stream of bytes.
213 /// Instances of `Hasher` usually represent state that is changed while hashing
216 /// `Hasher` provides a fairly basic interface for retrieving the generated hash
217 /// (with [`finish`]), and writing integers as well as slices of bytes into an
218 /// instance (with [`write`] and [`write_u8`] etc.). Most of the time, `Hasher`
219 /// instances are used in conjunction with the [`Hash`] trait.
224 /// use std::collections::hash_map::DefaultHasher;
225 /// use std::hash::Hasher;
227 /// let mut hasher = DefaultHasher::new();
229 /// hasher.write_u32(1989);
230 /// hasher.write_u8(11);
231 /// hasher.write_u8(9);
232 /// hasher.write(b"Huh?");
234 /// println!("Hash is {:x}!", hasher.finish());
237 /// [`Hash`]: trait.Hash.html
238 /// [`finish`]: #tymethod.finish
239 /// [`write`]: #tymethod.write
240 /// [`write_u8`]: #method.write_u8
241 #[stable(feature = "rust1", since = "1.0.0")]
243 /// Completes a round of hashing, producing the output hash generated.
248 /// use std::collections::hash_map::DefaultHasher;
249 /// use std::hash::Hasher;
251 /// let mut hasher = DefaultHasher::new();
252 /// hasher.write(b"Cool!");
254 /// println!("Hash is {:x}!", hasher.finish());
256 #[stable(feature = "rust1", since = "1.0.0")]
257 fn finish(&self) -> u64;
259 /// Writes some data into this `Hasher`.
264 /// use std::collections::hash_map::DefaultHasher;
265 /// use std::hash::Hasher;
267 /// let mut hasher = DefaultHasher::new();
268 /// let data = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef];
270 /// hasher.write(&data);
272 /// println!("Hash is {:x}!", hasher.finish());
274 #[stable(feature = "rust1", since = "1.0.0")]
275 fn write(&mut self, bytes
: &[u8]);
277 /// Writes a single `u8` into this hasher.
279 #[stable(feature = "hasher_write", since = "1.3.0")]
280 fn write_u8(&mut self, i
: u8) {
283 /// Writes a single `u16` into this hasher.
285 #[stable(feature = "hasher_write", since = "1.3.0")]
286 fn write_u16(&mut self, i
: u16) {
287 self.write(&unsafe { mem::transmute::<_, [u8; 2]>(i) }
)
289 /// Writes a single `u32` into this hasher.
291 #[stable(feature = "hasher_write", since = "1.3.0")]
292 fn write_u32(&mut self, i
: u32) {
293 self.write(&unsafe { mem::transmute::<_, [u8; 4]>(i) }
)
295 /// Writes a single `u64` into this hasher.
297 #[stable(feature = "hasher_write", since = "1.3.0")]
298 fn write_u64(&mut self, i
: u64) {
299 self.write(&unsafe { mem::transmute::<_, [u8; 8]>(i) }
)
301 /// Writes a single `u128` into this hasher.
303 #[unstable(feature = "i128", issue = "35118")]
304 fn write_u128(&mut self, i
: u128
) {
305 self.write(&unsafe { mem::transmute::<_, [u8; 16]>(i) }
)
307 /// Writes a single `usize` into this hasher.
309 #[stable(feature = "hasher_write", since = "1.3.0")]
310 fn write_usize(&mut self, i
: usize) {
312 ::slice
::from_raw_parts(&i
as *const usize as *const u8, mem
::size_of
::<usize>())
317 /// Writes a single `i8` into this hasher.
319 #[stable(feature = "hasher_write", since = "1.3.0")]
320 fn write_i8(&mut self, i
: i8) {
321 self.write_u8(i
as u8)
323 /// Writes a single `i16` into this hasher.
325 #[stable(feature = "hasher_write", since = "1.3.0")]
326 fn write_i16(&mut self, i
: i16) {
327 self.write_u16(i
as u16)
329 /// Writes a single `i32` into this hasher.
331 #[stable(feature = "hasher_write", since = "1.3.0")]
332 fn write_i32(&mut self, i
: i32) {
333 self.write_u32(i
as u32)
335 /// Writes a single `i64` into this hasher.
337 #[stable(feature = "hasher_write", since = "1.3.0")]
338 fn write_i64(&mut self, i
: i64) {
339 self.write_u64(i
as u64)
341 /// Writes a single `i128` into this hasher.
343 #[unstable(feature = "i128", issue = "35118")]
344 fn write_i128(&mut self, i
: i128
) {
345 self.write_u128(i
as u128
)
347 /// Writes a single `isize` into this hasher.
349 #[stable(feature = "hasher_write", since = "1.3.0")]
350 fn write_isize(&mut self, i
: isize) {
351 self.write_usize(i
as usize)
355 /// A trait for creating instances of [`Hasher`].
357 /// A `BuildHasher` is typically used (e.g. by [`HashMap`]) to create
358 /// [`Hasher`]s for each key such that they are hashed independently of one
359 /// another, since [`Hasher`]s contain state.
361 /// For each instance of `BuildHasher`, the [`Hasher`]s created by
362 /// [`build_hasher`] should be identical. That is, if the same stream of bytes
363 /// is fed into each hasher, the same output will also be generated.
368 /// use std::collections::hash_map::RandomState;
369 /// use std::hash::{BuildHasher, Hasher};
371 /// let s = RandomState::new();
372 /// let mut hasher_1 = s.build_hasher();
373 /// let mut hasher_2 = s.build_hasher();
375 /// hasher_1.write_u32(8128);
376 /// hasher_2.write_u32(8128);
378 /// assert_eq!(hasher_1.finish(), hasher_2.finish());
381 /// [`build_hasher`]: #tymethod.build_hasher
382 /// [`Hasher`]: trait.Hasher.html
383 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
384 #[stable(since = "1.7.0", feature = "build_hasher")]
385 pub trait BuildHasher
{
386 /// Type of the hasher that will be created.
387 #[stable(since = "1.7.0", feature = "build_hasher")]
390 /// Creates a new hasher.
392 /// Each call to `build_hasher` on the same instance should produce identical
398 /// use std::collections::hash_map::RandomState;
399 /// use std::hash::BuildHasher;
401 /// let s = RandomState::new();
402 /// let new_s = s.build_hasher();
405 /// [`Hasher`]: trait.Hasher.html
406 #[stable(since = "1.7.0", feature = "build_hasher")]
407 fn build_hasher(&self) -> Self::Hasher
;
410 /// Used to create a default [`BuildHasher`] instance for types that implement
411 /// [`Hasher`] and [`Default`].
413 /// `BuildHasherDefault<H>` can be used when a type `H` implements [`Hasher`] and
414 /// [`Default`], and you need a corresponding [`BuildHasher`] instance, but none is
417 /// Any `BuildHasherDefault` is [zero-sized]. It can be created with
418 /// [`default`][method.Default]. When using `BuildHasherDefault` with [`HashMap`] or
419 /// [`HashSet`], this doesn't need to be done, since they implement appropriate
420 /// [`Default`] instances themselves.
424 /// Using `BuildHasherDefault` to specify a custom [`BuildHasher`] for
428 /// use std::collections::HashMap;
429 /// use std::hash::{BuildHasherDefault, Hasher};
431 /// #[derive(Default)]
434 /// impl Hasher for MyHasher {
435 /// fn write(&mut self, bytes: &[u8]) {
436 /// // Your hashing algorithm goes here!
440 /// fn finish(&self) -> u64 {
441 /// // Your hashing algorithm goes here!
446 /// type MyBuildHasher = BuildHasherDefault<MyHasher>;
448 /// let hash_map = HashMap::<u32, u32, MyBuildHasher>::default();
451 /// [`BuildHasher`]: trait.BuildHasher.html
452 /// [`Default`]: ../default/trait.Default.html
453 /// [method.default]: #method.default
454 /// [`Hasher`]: trait.Hasher.html
455 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
456 /// [`HashSet`]: ../../std/collections/struct.HashSet.html
457 /// [zero-sized]: https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts
458 #[stable(since = "1.7.0", feature = "build_hasher")]
459 pub struct BuildHasherDefault
<H
>(marker
::PhantomData
<H
>);
461 #[stable(since = "1.9.0", feature = "core_impl_debug")]
462 impl<H
> fmt
::Debug
for BuildHasherDefault
<H
> {
463 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
464 f
.pad("BuildHasherDefault")
468 #[stable(since = "1.7.0", feature = "build_hasher")]
469 impl<H
: Default
+ Hasher
> BuildHasher
for BuildHasherDefault
<H
> {
472 fn build_hasher(&self) -> H
{
477 #[stable(since = "1.7.0", feature = "build_hasher")]
478 impl<H
> Clone
for BuildHasherDefault
<H
> {
479 fn clone(&self) -> BuildHasherDefault
<H
> {
480 BuildHasherDefault(marker
::PhantomData
)
484 #[stable(since = "1.7.0", feature = "build_hasher")]
485 impl<H
> Default
for BuildHasherDefault
<H
> {
486 fn default() -> BuildHasherDefault
<H
> {
487 BuildHasherDefault(marker
::PhantomData
)
491 //////////////////////////////////////////////////////////////////////////////
498 macro_rules
! impl_write
{
499 ($
(($ty
:ident
, $meth
:ident
),)*) => {$
(
500 #[stable(feature = "rust1", since = "1.0.0")]
502 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
506 fn hash_slice
<H
: Hasher
>(data
: &[$ty
], state
: &mut H
) {
507 let newlen
= data
.len() * mem
::size_of
::<$ty
>();
508 let ptr
= data
.as_ptr() as *const u8;
509 state
.write(unsafe { slice::from_raw_parts(ptr, newlen) }
)
520 (usize, write_usize
),
525 (isize, write_isize
),
530 #[stable(feature = "rust1", since = "1.0.0")]
532 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
533 state
.write_u8(*self as u8)
537 #[stable(feature = "rust1", since = "1.0.0")]
539 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
540 state
.write_u32(*self as u32)
544 #[stable(feature = "rust1", since = "1.0.0")]
546 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
547 state
.write(self.as_bytes());
552 macro_rules
! impl_hash_tuple
{
554 #[stable(feature = "rust1", since = "1.0.0")]
556 fn hash
<H
: Hasher
>(&self, _state
: &mut H
) {}
560 ( $
($name
:ident
)+) => (
561 #[stable(feature = "rust1", since = "1.0.0")]
562 impl<$
($name
: Hash
),*> Hash
for ($
($name
,)*) where last_type
!($
($name
,)+): ?Sized
{
563 #[allow(non_snake_case)]
564 fn hash
<S
: Hasher
>(&self, state
: &mut S
) {
565 let ($
(ref $name
,)*) = *self;
566 $
($name
.hash(state
);)*
572 macro_rules
! last_type
{
573 ($a
:ident
,) => { $a }
;
574 ($a
:ident
, $
($rest_a
:ident
,)+) => { last_type!($($rest_a,)+) }
;
578 impl_hash_tuple
! { A }
579 impl_hash_tuple
! { A B }
580 impl_hash_tuple
! { A B C }
581 impl_hash_tuple
! { A B C D }
582 impl_hash_tuple
! { A B C D E }
583 impl_hash_tuple
! { A B C D E F }
584 impl_hash_tuple
! { A B C D E F G }
585 impl_hash_tuple
! { A B C D E F G H }
586 impl_hash_tuple
! { A B C D E F G H I }
587 impl_hash_tuple
! { A B C D E F G H I J }
588 impl_hash_tuple
! { A B C D E F G H I J K }
589 impl_hash_tuple
! { A B C D E F G H I J K L }
591 #[stable(feature = "rust1", since = "1.0.0")]
592 impl<T
: Hash
> Hash
for [T
] {
593 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
594 self.len().hash(state
);
595 Hash
::hash_slice(self, state
)
600 #[stable(feature = "rust1", since = "1.0.0")]
601 impl<'a
, T
: ?Sized
+ Hash
> Hash
for &'a T
{
602 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
603 (**self).hash(state
);
607 #[stable(feature = "rust1", since = "1.0.0")]
608 impl<'a
, T
: ?Sized
+ Hash
> Hash
for &'a
mut T
{
609 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
610 (**self).hash(state
);
614 #[stable(feature = "rust1", since = "1.0.0")]
615 impl<T
> Hash
for *const T
{
616 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
617 state
.write_usize(*self as usize)
621 #[stable(feature = "rust1", since = "1.0.0")]
622 impl<T
> Hash
for *mut T
{
623 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
624 state
.write_usize(*self as usize)