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
44 //! use std::hash::{Hash, Hasher, SipHasher};
48 //! # #[allow(dead_code)]
53 //! impl Hash for Person {
54 //! fn hash<H: Hasher>(&self, state: &mut H) {
55 //! self.id.hash(state);
56 //! self.phone.hash(state);
60 //! let person1 = Person { id: 5, name: "Janet".to_string(), phone: 555_666_7777 };
61 //! let person2 = Person { id: 5, name: "Bob".to_string(), phone: 555_666_7777 };
63 //! assert_eq!(hash(&person1), hash(&person2));
65 //! fn hash<T: Hash>(t: &T) -> u64 {
66 //! let mut s = SipHasher::new();
72 #![stable(feature = "rust1", since = "1.0.0")]
79 #[stable(feature = "rust1", since = "1.0.0")]
80 pub use self::sip::SipHasher;
86 /// The `H` type parameter is an abstract hash state that is used by the `Hash`
87 /// to compute the hash.
89 /// If you are also implementing `Eq`, there is an additional property that
93 /// k1 == k2 -> hash(k1) == hash(k2)
96 /// In other words, if two keys are equal, their hashes should also be equal.
97 /// `HashMap` and `HashSet` both rely on this behavior.
99 /// This trait can be used with `#[derive]`.
100 #[stable(feature = "rust1", since = "1.0.0")]
102 /// Feeds this value into the state given, updating the hasher as necessary.
103 #[stable(feature = "rust1", since = "1.0.0")]
104 fn hash<H: Hasher>(&self, state: &mut H);
106 /// Feeds a slice of this type into the state provided.
107 #[stable(feature = "hash_slice", since = "1.3.0")]
108 fn hash_slice<H: Hasher>(data: &[Self], state: &mut H)
117 /// A trait which represents the ability to hash an arbitrary stream of bytes.
118 #[stable(feature = "rust1", since = "1.0.0")]
120 /// Completes a round of hashing, producing the output hash generated.
121 #[stable(feature = "rust1", since = "1.0.0")]
122 fn finish(&self) -> u64;
124 /// Writes some data into this `Hasher`
125 #[stable(feature = "rust1", since = "1.0.0")]
126 fn write(&mut self, bytes: &[u8]);
128 /// Write a single `u8` into this hasher
130 #[stable(feature = "hasher_write", since = "1.3.0")]
131 fn write_u8(&mut self, i: u8) {
134 /// Write a single `u16` into this hasher.
136 #[stable(feature = "hasher_write", since = "1.3.0")]
137 fn write_u16(&mut self, i: u16) {
138 self.write(&unsafe { mem::transmute::<_, [u8; 2]>(i) })
140 /// Write a single `u32` into this hasher.
142 #[stable(feature = "hasher_write", since = "1.3.0")]
143 fn write_u32(&mut self, i: u32) {
144 self.write(&unsafe { mem::transmute::<_, [u8; 4]>(i) })
146 /// Write a single `u64` into this hasher.
148 #[stable(feature = "hasher_write", since = "1.3.0")]
149 fn write_u64(&mut self, i: u64) {
150 self.write(&unsafe { mem::transmute::<_, [u8; 8]>(i) })
152 /// Write a single `usize` into this hasher.
154 #[stable(feature = "hasher_write", since = "1.3.0")]
155 fn write_usize(&mut self, i: usize) {
157 ::slice::from_raw_parts(&i as *const usize as *const u8, mem::size_of::<usize>())
162 /// Write a single `i8` into this hasher.
164 #[stable(feature = "hasher_write", since = "1.3.0")]
165 fn write_i8(&mut self, i: i8) {
166 self.write_u8(i as u8)
168 /// Write a single `i16` into this hasher.
170 #[stable(feature = "hasher_write", since = "1.3.0")]
171 fn write_i16(&mut self, i: i16) {
172 self.write_u16(i as u16)
174 /// Write a single `i32` into this hasher.
176 #[stable(feature = "hasher_write", since = "1.3.0")]
177 fn write_i32(&mut self, i: i32) {
178 self.write_u32(i as u32)
180 /// Write a single `i64` into this hasher.
182 #[stable(feature = "hasher_write", since = "1.3.0")]
183 fn write_i64(&mut self, i: i64) {
184 self.write_u64(i as u64)
186 /// Write a single `isize` into this hasher.
188 #[stable(feature = "hasher_write", since = "1.3.0")]
189 fn write_isize(&mut self, i: isize) {
190 self.write_usize(i as usize)
194 /// A `BuildHasher` is typically used as a factory for instances of `Hasher`
195 /// which a `HashMap` can then use to hash keys independently.
197 /// Note that for each instance of `BuildHasher` the create hashers should be
198 /// identical. That is if the same stream of bytes is fed into each hasher the
199 /// same output will also be generated.
200 #[stable(since = "1.7.0", feature = "build_hasher")]
201 pub trait BuildHasher {
202 /// Type of the hasher that will be created.
203 #[stable(since = "1.7.0", feature = "build_hasher")]
206 /// Creates a new hasher.
207 #[stable(since = "1.7.0", feature = "build_hasher")]
208 fn build_hasher(&self) -> Self::Hasher;
211 /// A structure which implements `BuildHasher` for all `Hasher` types which also
212 /// implement `Default`.
214 /// This struct is 0-sized and does not need construction.
215 #[stable(since = "1.7.0", feature = "build_hasher")]
216 pub struct BuildHasherDefault<H>(marker::PhantomData<H>);
218 #[stable(since = "1.7.0", feature = "build_hasher")]
219 impl<H: Default + Hasher> BuildHasher for BuildHasherDefault<H> {
222 fn build_hasher(&self) -> H {
227 #[stable(since = "1.7.0", feature = "build_hasher")]
228 impl<H> Clone for BuildHasherDefault<H> {
229 fn clone(&self) -> BuildHasherDefault<H> {
230 BuildHasherDefault(marker::PhantomData)
234 #[stable(since = "1.7.0", feature = "build_hasher")]
235 impl<H> Default for BuildHasherDefault<H> {
236 fn default() -> BuildHasherDefault<H> {
237 BuildHasherDefault(marker::PhantomData)
241 // The HashState trait is super deprecated, but it's here to have the blanket
242 // impl that goes from HashState -> BuildHasher
244 /// Deprecated, renamed to `BuildHasher`
245 #[unstable(feature = "hashmap_hasher", reason = "hasher stuff is unclear",
247 #[rustc_deprecated(since = "1.7.0", reason = "support moved to std::hash and \
248 renamed to BuildHasher")]
249 pub trait HashState {
250 /// Type of the hasher that will be created.
253 /// Creates a new hasher based on the given state of this object.
254 fn hasher(&self) -> Self::Hasher;
257 #[unstable(feature = "hashmap_hasher", reason = "hasher stuff is unclear",
260 impl<T: HashState> BuildHasher for T {
261 type Hasher = T::Hasher;
262 fn build_hasher(&self) -> T::Hasher { self.hasher() }
265 //////////////////////////////////////////////////////////////////////////////
274 macro_rules! impl_write {
275 ($(($ty:ident, $meth:ident),)*) => {$(
276 #[stable(feature = "rust1", since = "1.0.0")]
278 fn hash<H: Hasher>(&self, state: &mut H) {
282 fn hash_slice<H: Hasher>(data: &[$ty], state: &mut H) {
283 let newlen = data.len() * mem::size_of::<$ty>();
284 let ptr = data.as_ptr() as *const u8;
285 state.write(unsafe { slice::from_raw_parts(ptr, newlen) })
296 (usize, write_usize),
301 (isize, write_isize),
304 #[stable(feature = "rust1", since = "1.0.0")]
306 fn hash<H: Hasher>(&self, state: &mut H) {
307 state.write_u8(*self as u8)
311 #[stable(feature = "rust1", since = "1.0.0")]
313 fn hash<H: Hasher>(&self, state: &mut H) {
314 state.write_u32(*self as u32)
318 #[stable(feature = "rust1", since = "1.0.0")]
320 fn hash<H: Hasher>(&self, state: &mut H) {
321 state.write(self.as_bytes());
326 macro_rules! impl_hash_tuple {
328 #[stable(feature = "rust1", since = "1.0.0")]
330 fn hash<H: Hasher>(&self, _state: &mut H) {}
334 ( $($name:ident)+) => (
335 #[stable(feature = "rust1", since = "1.0.0")]
336 impl<$($name: Hash),*> Hash for ($($name,)*) {
337 #[allow(non_snake_case)]
338 fn hash<S: Hasher>(&self, state: &mut S) {
339 let ($(ref $name,)*) = *self;
340 $($name.hash(state);)*
347 impl_hash_tuple! { A }
348 impl_hash_tuple! { A B }
349 impl_hash_tuple! { A B C }
350 impl_hash_tuple! { A B C D }
351 impl_hash_tuple! { A B C D E }
352 impl_hash_tuple! { A B C D E F }
353 impl_hash_tuple! { A B C D E F G }
354 impl_hash_tuple! { A B C D E F G H }
355 impl_hash_tuple! { A B C D E F G H I }
356 impl_hash_tuple! { A B C D E F G H I J }
357 impl_hash_tuple! { A B C D E F G H I J K }
358 impl_hash_tuple! { A B C D E F G H I J K L }
360 #[stable(feature = "rust1", since = "1.0.0")]
361 impl<T: Hash> Hash for [T] {
362 fn hash<H: Hasher>(&self, state: &mut H) {
363 self.len().hash(state);
364 Hash::hash_slice(self, state)
369 #[stable(feature = "rust1", since = "1.0.0")]
370 impl<'a, T: ?Sized + Hash> Hash for &'a T {
371 fn hash<H: Hasher>(&self, state: &mut H) {
372 (**self).hash(state);
376 #[stable(feature = "rust1", since = "1.0.0")]
377 impl<'a, T: ?Sized + Hash> Hash for &'a mut T {
378 fn hash<H: Hasher>(&self, state: &mut H) {
379 (**self).hash(state);
383 #[stable(feature = "rust1", since = "1.0.0")]
384 impl<T> Hash for *const T {
385 fn hash<H: Hasher>(&self, state: &mut H) {
386 state.write_usize(*self as usize)
390 #[stable(feature = "rust1", since = "1.0.0")]
391 impl<T> Hash for *mut T {
392 fn hash<H: Hasher>(&self, state: &mut H) {
393 state.write_usize(*self as usize)