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::hash::{Hash, SipHasher, Hasher};
28 //! let person1 = Person { id: 5, name: "Janet".to_string(), phone: 555_666_7777 };
29 //! let person2 = Person { id: 5, name: "Bob".to_string(), phone: 555_666_7777 };
31 //! assert!(hash(&person1) != hash(&person2));
33 //! fn hash<T: Hash>(t: &T) -> u64 {
34 //! let mut s = SipHasher::new();
40 //! If you need more control over how a value is hashed, you need to implement
41 //! the [`Hash`] trait:
43 //! [`Hash`]: trait.Hash.html
46 //! use std::hash::{Hash, Hasher, SipHasher};
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 { id: 5, name: "Janet".to_string(), phone: 555_666_7777 };
63 //! let person2 = Person { id: 5, name: "Bob".to_string(), phone: 555_666_7777 };
65 //! assert_eq!(hash(&person1), hash(&person2));
67 //! fn hash<T: Hash>(t: &T) -> u64 {
68 //! let mut s = SipHasher::new();
74 #![stable(feature = "rust1", since = "1.0.0")]
80 #[stable(feature = "rust1", since = "1.0.0")]
82 pub use self::sip
::SipHasher
;
84 #[unstable(feature = "sip_hash_13", issue = "29754")]
86 pub use self::sip
::{SipHasher13, SipHasher24}
;
92 /// The `H` type parameter is an abstract hash state that is used by the `Hash`
93 /// to compute the hash.
95 /// If you are also implementing [`Eq`], there is an additional property that
99 /// k1 == k2 -> hash(k1) == hash(k2)
102 /// In other words, if two keys are equal, their hashes should also be equal.
103 /// [`HashMap`] and [`HashSet`] both rely on this behavior.
107 /// This trait can be used with `#[derive]` if all fields implement `Hash`.
108 /// When `derive`d, the resulting hash will be the combination of the values
109 /// from calling [`.hash()`] on each field.
111 /// ## How can I implement `Hash`?
113 /// If you need more control over how a value is hashed, you need to implement
114 /// the `Hash` trait:
117 /// use std::hash::{Hash, Hasher};
125 /// impl Hash for Person {
126 /// fn hash<H: Hasher>(&self, state: &mut H) {
127 /// self.id.hash(state);
128 /// self.phone.hash(state);
133 /// [`Eq`]: ../../std/cmp/trait.Eq.html
134 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
135 /// [`HashSet`]: ../../std/collections/struct.HashSet.html
136 /// [`.hash()`]: #tymethod.hash
137 #[stable(feature = "rust1", since = "1.0.0")]
139 /// Feeds this value into the state given, updating the hasher as necessary.
140 #[stable(feature = "rust1", since = "1.0.0")]
141 fn hash
<H
: Hasher
>(&self, state
: &mut H
);
143 /// Feeds a slice of this type into the state provided.
144 #[stable(feature = "hash_slice", since = "1.3.0")]
145 fn hash_slice
<H
: Hasher
>(data
: &[Self], state
: &mut H
)
154 /// A trait which represents the ability to hash an arbitrary stream of bytes.
155 #[stable(feature = "rust1", since = "1.0.0")]
157 /// Completes a round of hashing, producing the output hash generated.
158 #[stable(feature = "rust1", since = "1.0.0")]
159 fn finish(&self) -> u64;
161 /// Writes some data into this `Hasher`.
162 #[stable(feature = "rust1", since = "1.0.0")]
163 fn write(&mut self, bytes
: &[u8]);
165 /// Write a single `u8` into this hasher.
167 #[stable(feature = "hasher_write", since = "1.3.0")]
168 fn write_u8(&mut self, i
: u8) {
171 /// Writes a single `u16` into this hasher.
173 #[stable(feature = "hasher_write", since = "1.3.0")]
174 fn write_u16(&mut self, i
: u16) {
175 self.write(&unsafe { mem::transmute::<_, [u8; 2]>(i) }
)
177 /// Writes a single `u32` into this hasher.
179 #[stable(feature = "hasher_write", since = "1.3.0")]
180 fn write_u32(&mut self, i
: u32) {
181 self.write(&unsafe { mem::transmute::<_, [u8; 4]>(i) }
)
183 /// Writes a single `u64` into this hasher.
185 #[stable(feature = "hasher_write", since = "1.3.0")]
186 fn write_u64(&mut self, i
: u64) {
187 self.write(&unsafe { mem::transmute::<_, [u8; 8]>(i) }
)
190 /// Writes a single `u128` into this hasher.
192 #[unstable(feature = "i128", issue = "35118")]
193 fn write_u128(&mut self, i
: u128
) {
194 self.write(&unsafe { mem::transmute::<_, [u8; 16]>(i) }
)
196 /// Writes a single `usize` into this hasher.
198 #[stable(feature = "hasher_write", since = "1.3.0")]
199 fn write_usize(&mut self, i
: usize) {
201 ::slice
::from_raw_parts(&i
as *const usize as *const u8, mem
::size_of
::<usize>())
206 /// Writes a single `i8` into this hasher.
208 #[stable(feature = "hasher_write", since = "1.3.0")]
209 fn write_i8(&mut self, i
: i8) {
210 self.write_u8(i
as u8)
212 /// Writes a single `i16` into this hasher.
214 #[stable(feature = "hasher_write", since = "1.3.0")]
215 fn write_i16(&mut self, i
: i16) {
216 self.write_u16(i
as u16)
218 /// Writes a single `i32` into this hasher.
220 #[stable(feature = "hasher_write", since = "1.3.0")]
221 fn write_i32(&mut self, i
: i32) {
222 self.write_u32(i
as u32)
224 /// Writes a single `i64` into this hasher.
226 #[stable(feature = "hasher_write", since = "1.3.0")]
227 fn write_i64(&mut self, i
: i64) {
228 self.write_u64(i
as u64)
231 /// Writes a single `i128` into this hasher.
233 #[unstable(feature = "i128", issue = "35118")]
234 fn write_i128(&mut self, i
: i128
) {
235 self.write_u128(i
as u128
)
237 /// Writes a single `isize` into this hasher.
239 #[stable(feature = "hasher_write", since = "1.3.0")]
240 fn write_isize(&mut self, i
: isize) {
241 self.write_usize(i
as usize)
245 /// A `BuildHasher` is typically used as a factory for instances of `Hasher`
246 /// which a `HashMap` can then use to hash keys independently.
248 /// Note that for each instance of `BuildHasher`, the created hashers should be
249 /// identical. That is, if the same stream of bytes is fed into each hasher, the
250 /// same output will also be generated.
251 #[stable(since = "1.7.0", feature = "build_hasher")]
252 pub trait BuildHasher
{
253 /// Type of the hasher that will be created.
254 #[stable(since = "1.7.0", feature = "build_hasher")]
257 /// Creates a new hasher.
262 /// use std::collections::hash_map::RandomState;
263 /// use std::hash::BuildHasher;
265 /// let s = RandomState::new();
266 /// let new_s = s.build_hasher();
268 #[stable(since = "1.7.0", feature = "build_hasher")]
269 fn build_hasher(&self) -> Self::Hasher
;
272 /// The `BuildHasherDefault` structure is used in scenarios where one has a
273 /// type that implements [`Hasher`] and [`Default`], but needs that type to
274 /// implement [`BuildHasher`].
276 /// This structure is zero-sized and does not need construction.
280 /// Using `BuildHasherDefault` to specify a custom [`BuildHasher`] for
284 /// use std::collections::HashMap;
285 /// use std::hash::{BuildHasherDefault, Hasher};
287 /// #[derive(Default)]
290 /// impl Hasher for MyHasher {
291 /// fn write(&mut self, bytes: &[u8]) {
292 /// // Your hashing algorithm goes here!
296 /// fn finish(&self) -> u64 {
297 /// // Your hashing algorithm goes here!
302 /// type MyBuildHasher = BuildHasherDefault<MyHasher>;
304 /// let hash_map = HashMap::<u32, u32, MyBuildHasher>::default();
307 /// [`BuildHasher`]: trait.BuildHasher.html
308 /// [`Default`]: ../default/trait.Default.html
309 /// [`Hasher`]: trait.Hasher.html
310 /// [`HashMap`]: ../../std/collections/struct.HashMap.html
311 #[stable(since = "1.7.0", feature = "build_hasher")]
312 pub struct BuildHasherDefault
<H
>(marker
::PhantomData
<H
>);
314 #[stable(since = "1.9.0", feature = "core_impl_debug")]
315 impl<H
> fmt
::Debug
for BuildHasherDefault
<H
> {
316 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
317 f
.pad("BuildHasherDefault")
321 #[stable(since = "1.7.0", feature = "build_hasher")]
322 impl<H
: Default
+ Hasher
> BuildHasher
for BuildHasherDefault
<H
> {
325 fn build_hasher(&self) -> H
{
330 #[stable(since = "1.7.0", feature = "build_hasher")]
331 impl<H
> Clone
for BuildHasherDefault
<H
> {
332 fn clone(&self) -> BuildHasherDefault
<H
> {
333 BuildHasherDefault(marker
::PhantomData
)
337 #[stable(since = "1.7.0", feature = "build_hasher")]
338 impl<H
> Default
for BuildHasherDefault
<H
> {
339 fn default() -> BuildHasherDefault
<H
> {
340 BuildHasherDefault(marker
::PhantomData
)
344 //////////////////////////////////////////////////////////////////////////////
351 macro_rules
! impl_write
{
352 ($
(($ty
:ident
, $meth
:ident
),)*) => {$
(
353 #[stable(feature = "rust1", since = "1.0.0")]
355 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
359 fn hash_slice
<H
: Hasher
>(data
: &[$ty
], state
: &mut H
) {
360 let newlen
= data
.len() * mem
::size_of
::<$ty
>();
361 let ptr
= data
.as_ptr() as *const u8;
362 state
.write(unsafe { slice::from_raw_parts(ptr, newlen) }
)
373 (usize, write_usize
),
378 (isize, write_isize
),
386 #[stable(feature = "rust1", since = "1.0.0")]
388 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
389 state
.write_u8(*self as u8)
393 #[stable(feature = "rust1", since = "1.0.0")]
395 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
396 state
.write_u32(*self as u32)
400 #[stable(feature = "rust1", since = "1.0.0")]
402 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
403 state
.write(self.as_bytes());
408 macro_rules
! impl_hash_tuple
{
410 #[stable(feature = "rust1", since = "1.0.0")]
412 fn hash
<H
: Hasher
>(&self, _state
: &mut H
) {}
416 ( $
($name
:ident
)+) => (
417 #[stable(feature = "rust1", since = "1.0.0")]
418 impl<$
($name
: Hash
),*> Hash
for ($
($name
,)*) {
419 #[allow(non_snake_case)]
420 fn hash
<S
: Hasher
>(&self, state
: &mut S
) {
421 let ($
(ref $name
,)*) = *self;
422 $
($name
.hash(state
);)*
429 impl_hash_tuple
! { A }
430 impl_hash_tuple
! { A B }
431 impl_hash_tuple
! { A B C }
432 impl_hash_tuple
! { A B C D }
433 impl_hash_tuple
! { A B C D E }
434 impl_hash_tuple
! { A B C D E F }
435 impl_hash_tuple
! { A B C D E F G }
436 impl_hash_tuple
! { A B C D E F G H }
437 impl_hash_tuple
! { A B C D E F G H I }
438 impl_hash_tuple
! { A B C D E F G H I J }
439 impl_hash_tuple
! { A B C D E F G H I J K }
440 impl_hash_tuple
! { A B C D E F G H I J K L }
442 #[stable(feature = "rust1", since = "1.0.0")]
443 impl<T
: Hash
> Hash
for [T
] {
444 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
445 self.len().hash(state
);
446 Hash
::hash_slice(self, state
)
451 #[stable(feature = "rust1", since = "1.0.0")]
452 impl<'a
, T
: ?Sized
+ Hash
> Hash
for &'a T
{
453 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
454 (**self).hash(state
);
458 #[stable(feature = "rust1", since = "1.0.0")]
459 impl<'a
, T
: ?Sized
+ Hash
> Hash
for &'a
mut T
{
460 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
461 (**self).hash(state
);
465 #[stable(feature = "rust1", since = "1.0.0")]
466 impl<T
> Hash
for *const T
{
467 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
468 state
.write_usize(*self as usize)
472 #[stable(feature = "rust1", since = "1.0.0")]
473 impl<T
> Hash
for *mut T
{
474 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
475 state
.write_usize(*self as usize)