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")]
78 #[stable(feature = "rust1", since = "1.0.0")]
79 pub use self::sip::SipHasher;
81 #[unstable(feature = "sip_hash_13", issue = "29754")]
82 pub use self::sip::{SipHasher13, SipHasher24};
88 /// The `H` type parameter is an abstract hash state that is used by the `Hash`
89 /// to compute the hash.
91 /// If you are also implementing `Eq`, there is an additional property that
95 /// k1 == k2 -> hash(k1) == hash(k2)
98 /// In other words, if two keys are equal, their hashes should also be equal.
99 /// `HashMap` and `HashSet` both rely on this behavior.
103 /// This trait can be used with `#[derive]` if all fields implement `Hash`.
104 /// When `derive`d, the resulting hash will be the combination of the values
105 /// from calling `.hash()` on each field.
107 /// ## How can I implement `Hash`?
109 /// If you need more control over how a value is hashed, you need to implement
110 /// the `Hash` trait:
113 /// use std::hash::{Hash, Hasher};
121 /// impl Hash for Person {
122 /// fn hash<H: Hasher>(&self, state: &mut H) {
123 /// self.id.hash(state);
124 /// self.phone.hash(state);
128 #[stable(feature = "rust1", since = "1.0.0")]
130 /// Feeds this value into the state given, updating the hasher as necessary.
131 #[stable(feature = "rust1", since = "1.0.0")]
132 fn hash<H: Hasher>(&self, state: &mut H);
134 /// Feeds a slice of this type into the state provided.
135 #[stable(feature = "hash_slice", since = "1.3.0")]
136 fn hash_slice<H: Hasher>(data: &[Self], state: &mut H)
145 /// A trait which represents the ability to hash an arbitrary stream of bytes.
146 #[stable(feature = "rust1", since = "1.0.0")]
148 /// Completes a round of hashing, producing the output hash generated.
149 #[stable(feature = "rust1", since = "1.0.0")]
150 fn finish(&self) -> u64;
152 /// Writes some data into this `Hasher`
153 #[stable(feature = "rust1", since = "1.0.0")]
154 fn write(&mut self, bytes: &[u8]);
156 /// Write a single `u8` into this hasher
158 #[stable(feature = "hasher_write", since = "1.3.0")]
159 fn write_u8(&mut self, i: u8) {
162 /// Write a single `u16` into this hasher.
164 #[stable(feature = "hasher_write", since = "1.3.0")]
165 fn write_u16(&mut self, i: u16) {
166 self.write(&unsafe { mem::transmute::<_, [u8; 2]>(i) })
168 /// Write a single `u32` into this hasher.
170 #[stable(feature = "hasher_write", since = "1.3.0")]
171 fn write_u32(&mut self, i: u32) {
172 self.write(&unsafe { mem::transmute::<_, [u8; 4]>(i) })
174 /// Write a single `u64` into this hasher.
176 #[stable(feature = "hasher_write", since = "1.3.0")]
177 fn write_u64(&mut self, i: u64) {
178 self.write(&unsafe { mem::transmute::<_, [u8; 8]>(i) })
180 /// Write a single `usize` into this hasher.
182 #[stable(feature = "hasher_write", since = "1.3.0")]
183 fn write_usize(&mut self, i: usize) {
185 ::slice::from_raw_parts(&i as *const usize as *const u8, mem::size_of::<usize>())
190 /// Write a single `i8` into this hasher.
192 #[stable(feature = "hasher_write", since = "1.3.0")]
193 fn write_i8(&mut self, i: i8) {
194 self.write_u8(i as u8)
196 /// Write a single `i16` into this hasher.
198 #[stable(feature = "hasher_write", since = "1.3.0")]
199 fn write_i16(&mut self, i: i16) {
200 self.write_u16(i as u16)
202 /// Write a single `i32` into this hasher.
204 #[stable(feature = "hasher_write", since = "1.3.0")]
205 fn write_i32(&mut self, i: i32) {
206 self.write_u32(i as u32)
208 /// Write a single `i64` into this hasher.
210 #[stable(feature = "hasher_write", since = "1.3.0")]
211 fn write_i64(&mut self, i: i64) {
212 self.write_u64(i as u64)
214 /// Write a single `isize` into this hasher.
216 #[stable(feature = "hasher_write", since = "1.3.0")]
217 fn write_isize(&mut self, i: isize) {
218 self.write_usize(i as usize)
222 /// A `BuildHasher` is typically used as a factory for instances of `Hasher`
223 /// which a `HashMap` can then use to hash keys independently.
225 /// Note that for each instance of `BuildHasher`, the created hashers should be
226 /// identical. That is, if the same stream of bytes is fed into each hasher, the
227 /// same output will also be generated.
228 #[stable(since = "1.7.0", feature = "build_hasher")]
229 pub trait BuildHasher {
230 /// Type of the hasher that will be created.
231 #[stable(since = "1.7.0", feature = "build_hasher")]
234 /// Creates a new hasher.
239 /// use std::collections::hash_map::RandomState;
240 /// use std::hash::BuildHasher;
242 /// let s = RandomState::new();
243 /// let new_s = s.build_hasher();
245 #[stable(since = "1.7.0", feature = "build_hasher")]
246 fn build_hasher(&self) -> Self::Hasher;
249 /// A structure which implements `BuildHasher` for all `Hasher` types which also
250 /// implement `Default`.
252 /// This struct is 0-sized and does not need construction.
253 #[stable(since = "1.7.0", feature = "build_hasher")]
254 pub struct BuildHasherDefault<H>(marker::PhantomData<H>);
256 #[stable(since = "1.9.0", feature = "core_impl_debug")]
257 impl<H> fmt::Debug for BuildHasherDefault<H> {
258 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
259 f.pad("BuildHasherDefault")
263 #[stable(since = "1.7.0", feature = "build_hasher")]
264 impl<H: Default + Hasher> BuildHasher for BuildHasherDefault<H> {
267 fn build_hasher(&self) -> H {
272 #[stable(since = "1.7.0", feature = "build_hasher")]
273 impl<H> Clone for BuildHasherDefault<H> {
274 fn clone(&self) -> BuildHasherDefault<H> {
275 BuildHasherDefault(marker::PhantomData)
279 #[stable(since = "1.7.0", feature = "build_hasher")]
280 impl<H> Default for BuildHasherDefault<H> {
281 fn default() -> BuildHasherDefault<H> {
282 BuildHasherDefault(marker::PhantomData)
286 //////////////////////////////////////////////////////////////////////////////
293 macro_rules! impl_write {
294 ($(($ty:ident, $meth:ident),)*) => {$(
295 #[stable(feature = "rust1", since = "1.0.0")]
297 fn hash<H: Hasher>(&self, state: &mut H) {
301 fn hash_slice<H: Hasher>(data: &[$ty], state: &mut H) {
302 let newlen = data.len() * mem::size_of::<$ty>();
303 let ptr = data.as_ptr() as *const u8;
304 state.write(unsafe { slice::from_raw_parts(ptr, newlen) })
315 (usize, write_usize),
320 (isize, write_isize),
323 #[stable(feature = "rust1", since = "1.0.0")]
325 fn hash<H: Hasher>(&self, state: &mut H) {
326 state.write_u8(*self as u8)
330 #[stable(feature = "rust1", since = "1.0.0")]
332 fn hash<H: Hasher>(&self, state: &mut H) {
333 state.write_u32(*self as u32)
337 #[stable(feature = "rust1", since = "1.0.0")]
339 fn hash<H: Hasher>(&self, state: &mut H) {
340 state.write(self.as_bytes());
345 macro_rules! impl_hash_tuple {
347 #[stable(feature = "rust1", since = "1.0.0")]
349 fn hash<H: Hasher>(&self, _state: &mut H) {}
353 ( $($name:ident)+) => (
354 #[stable(feature = "rust1", since = "1.0.0")]
355 impl<$($name: Hash),*> Hash for ($($name,)*) {
356 #[allow(non_snake_case)]
357 fn hash<S: Hasher>(&self, state: &mut S) {
358 let ($(ref $name,)*) = *self;
359 $($name.hash(state);)*
366 impl_hash_tuple! { A }
367 impl_hash_tuple! { A B }
368 impl_hash_tuple! { A B C }
369 impl_hash_tuple! { A B C D }
370 impl_hash_tuple! { A B C D E }
371 impl_hash_tuple! { A B C D E F }
372 impl_hash_tuple! { A B C D E F G }
373 impl_hash_tuple! { A B C D E F G H }
374 impl_hash_tuple! { A B C D E F G H I }
375 impl_hash_tuple! { A B C D E F G H I J }
376 impl_hash_tuple! { A B C D E F G H I J K }
377 impl_hash_tuple! { A B C D E F G H I J K L }
379 #[stable(feature = "rust1", since = "1.0.0")]
380 impl<T: Hash> Hash for [T] {
381 fn hash<H: Hasher>(&self, state: &mut H) {
382 self.len().hash(state);
383 Hash::hash_slice(self, state)
388 #[stable(feature = "rust1", since = "1.0.0")]
389 impl<'a, T: ?Sized + Hash> Hash for &'a T {
390 fn hash<H: Hasher>(&self, state: &mut H) {
391 (**self).hash(state);
395 #[stable(feature = "rust1", since = "1.0.0")]
396 impl<'a, T: ?Sized + Hash> Hash for &'a mut T {
397 fn hash<H: Hasher>(&self, state: &mut H) {
398 (**self).hash(state);
402 #[stable(feature = "rust1", since = "1.0.0")]
403 impl<T> Hash for *const T {
404 fn hash<H: Hasher>(&self, state: &mut H) {
405 state.write_usize(*self as usize)
409 #[stable(feature = "rust1", since = "1.0.0")]
410 impl<T> Hash for *mut T {
411 fn hash<H: Hasher>(&self, state: &mut H) {
412 state.write_usize(*self as usize)