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 #[stable(since = "1.7.0", feature = "build_hasher")]
311 pub struct BuildHasherDefault<H>(marker::PhantomData<H>);
313 #[stable(since = "1.9.0", feature = "core_impl_debug")]
314 impl<H> fmt::Debug for BuildHasherDefault<H> {
315 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
316 f.pad("BuildHasherDefault")
320 #[stable(since = "1.7.0", feature = "build_hasher")]
321 impl<H: Default + Hasher> BuildHasher for BuildHasherDefault<H> {
324 fn build_hasher(&self) -> H {
329 #[stable(since = "1.7.0", feature = "build_hasher")]
330 impl<H> Clone for BuildHasherDefault<H> {
331 fn clone(&self) -> BuildHasherDefault<H> {
332 BuildHasherDefault(marker::PhantomData)
336 #[stable(since = "1.7.0", feature = "build_hasher")]
337 impl<H> Default for BuildHasherDefault<H> {
338 fn default() -> BuildHasherDefault<H> {
339 BuildHasherDefault(marker::PhantomData)
343 //////////////////////////////////////////////////////////////////////////////
350 macro_rules! impl_write {
351 ($(($ty:ident, $meth:ident),)*) => {$(
352 #[stable(feature = "rust1", since = "1.0.0")]
354 fn hash<H: Hasher>(&self, state: &mut H) {
358 fn hash_slice<H: Hasher>(data: &[$ty], state: &mut H) {
359 let newlen = data.len() * mem::size_of::<$ty>();
360 let ptr = data.as_ptr() as *const u8;
361 state.write(unsafe { slice::from_raw_parts(ptr, newlen) })
372 (usize, write_usize),
377 (isize, write_isize),
385 #[stable(feature = "rust1", since = "1.0.0")]
387 fn hash<H: Hasher>(&self, state: &mut H) {
388 state.write_u8(*self as u8)
392 #[stable(feature = "rust1", since = "1.0.0")]
394 fn hash<H: Hasher>(&self, state: &mut H) {
395 state.write_u32(*self as u32)
399 #[stable(feature = "rust1", since = "1.0.0")]
401 fn hash<H: Hasher>(&self, state: &mut H) {
402 state.write(self.as_bytes());
407 macro_rules! impl_hash_tuple {
409 #[stable(feature = "rust1", since = "1.0.0")]
411 fn hash<H: Hasher>(&self, _state: &mut H) {}
415 ( $($name:ident)+) => (
416 #[stable(feature = "rust1", since = "1.0.0")]
417 impl<$($name: Hash),*> Hash for ($($name,)*) {
418 #[allow(non_snake_case)]
419 fn hash<S: Hasher>(&self, state: &mut S) {
420 let ($(ref $name,)*) = *self;
421 $($name.hash(state);)*
428 impl_hash_tuple! { A }
429 impl_hash_tuple! { A B }
430 impl_hash_tuple! { A B C }
431 impl_hash_tuple! { A B C D }
432 impl_hash_tuple! { A B C D E }
433 impl_hash_tuple! { A B C D E F }
434 impl_hash_tuple! { A B C D E F G }
435 impl_hash_tuple! { A B C D E F G H }
436 impl_hash_tuple! { A B C D E F G H I }
437 impl_hash_tuple! { A B C D E F G H I J }
438 impl_hash_tuple! { A B C D E F G H I J K }
439 impl_hash_tuple! { A B C D E F G H I J K L }
441 #[stable(feature = "rust1", since = "1.0.0")]
442 impl<T: Hash> Hash for [T] {
443 fn hash<H: Hasher>(&self, state: &mut H) {
444 self.len().hash(state);
445 Hash::hash_slice(self, state)
450 #[stable(feature = "rust1", since = "1.0.0")]
451 impl<'a, T: ?Sized + Hash> Hash for &'a T {
452 fn hash<H: Hasher>(&self, state: &mut H) {
453 (**self).hash(state);
457 #[stable(feature = "rust1", since = "1.0.0")]
458 impl<'a, T: ?Sized + Hash> Hash for &'a mut T {
459 fn hash<H: Hasher>(&self, state: &mut H) {
460 (**self).hash(state);
464 #[stable(feature = "rust1", since = "1.0.0")]
465 impl<T> Hash for *const T {
466 fn hash<H: Hasher>(&self, state: &mut H) {
467 state.write_usize(*self as usize)
471 #[stable(feature = "rust1", since = "1.0.0")]
472 impl<T> Hash for *mut T {
473 fn hash<H: Hasher>(&self, state: &mut H) {
474 state.write_usize(*self as usize)