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 created 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 //////////////////////////////////////////////////////////////////////////////
250 macro_rules! impl_write {
251 ($(($ty:ident, $meth:ident),)*) => {$(
252 #[stable(feature = "rust1", since = "1.0.0")]
254 fn hash<H: Hasher>(&self, state: &mut H) {
258 fn hash_slice<H: Hasher>(data: &[$ty], state: &mut H) {
259 let newlen = data.len() * mem::size_of::<$ty>();
260 let ptr = data.as_ptr() as *const u8;
261 state.write(unsafe { slice::from_raw_parts(ptr, newlen) })
272 (usize, write_usize),
277 (isize, write_isize),
280 #[stable(feature = "rust1", since = "1.0.0")]
282 fn hash<H: Hasher>(&self, state: &mut H) {
283 state.write_u8(*self as u8)
287 #[stable(feature = "rust1", since = "1.0.0")]
289 fn hash<H: Hasher>(&self, state: &mut H) {
290 state.write_u32(*self as u32)
294 #[stable(feature = "rust1", since = "1.0.0")]
296 fn hash<H: Hasher>(&self, state: &mut H) {
297 state.write(self.as_bytes());
302 macro_rules! impl_hash_tuple {
304 #[stable(feature = "rust1", since = "1.0.0")]
306 fn hash<H: Hasher>(&self, _state: &mut H) {}
310 ( $($name:ident)+) => (
311 #[stable(feature = "rust1", since = "1.0.0")]
312 impl<$($name: Hash),*> Hash for ($($name,)*) {
313 #[allow(non_snake_case)]
314 fn hash<S: Hasher>(&self, state: &mut S) {
315 let ($(ref $name,)*) = *self;
316 $($name.hash(state);)*
323 impl_hash_tuple! { A }
324 impl_hash_tuple! { A B }
325 impl_hash_tuple! { A B C }
326 impl_hash_tuple! { A B C D }
327 impl_hash_tuple! { A B C D E }
328 impl_hash_tuple! { A B C D E F }
329 impl_hash_tuple! { A B C D E F G }
330 impl_hash_tuple! { A B C D E F G H }
331 impl_hash_tuple! { A B C D E F G H I }
332 impl_hash_tuple! { A B C D E F G H I J }
333 impl_hash_tuple! { A B C D E F G H I J K }
334 impl_hash_tuple! { A B C D E F G H I J K L }
336 #[stable(feature = "rust1", since = "1.0.0")]
337 impl<T: Hash> Hash for [T] {
338 fn hash<H: Hasher>(&self, state: &mut H) {
339 self.len().hash(state);
340 Hash::hash_slice(self, state)
345 #[stable(feature = "rust1", since = "1.0.0")]
346 impl<'a, T: ?Sized + Hash> Hash for &'a T {
347 fn hash<H: Hasher>(&self, state: &mut H) {
348 (**self).hash(state);
352 #[stable(feature = "rust1", since = "1.0.0")]
353 impl<'a, T: ?Sized + Hash> Hash for &'a mut T {
354 fn hash<H: Hasher>(&self, state: &mut H) {
355 (**self).hash(state);
359 #[stable(feature = "rust1", since = "1.0.0")]
360 impl<T> Hash for *const T {
361 fn hash<H: Hasher>(&self, state: &mut H) {
362 state.write_usize(*self as usize)
366 #[stable(feature = "rust1", since = "1.0.0")]
367 impl<T> Hash for *mut T {
368 fn hash<H: Hasher>(&self, state: &mut H) {
369 state.write_usize(*self as usize)