1 // Copyright 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 `#[deriving(Hash)]`:
20 //! use std::hash::Hash;
29 //! let person1 = Person { id: 5, name: "Janet".to_string(), phone: 555_666_7777 };
30 //! let person2 = Person { id: 5, name: "Bob".to_string(), phone: 555_666_7777 };
32 //! assert!(hash::hash(&person1) != hash::hash(&person2));
35 //! If you need more control over how a value is hashed, you need to implement
40 //! use std::hash::Hash;
41 //! use std::hash::sip::SipState;
49 //! impl Hash for Person {
50 //! fn hash(&self, state: &mut SipState) {
51 //! self.id.hash(state);
52 //! self.phone.hash(state);
56 //! let person1 = Person { id: 5, name: "Janet".to_string(), phone: 555_666_7777 };
57 //! let person2 = Person { id: 5, name: "Bob".to_string(), phone: 555_666_7777 };
59 //! assert!(hash::hash(&person1) == hash::hash(&person2));
64 pub use core::hash::{Hash, Hasher, Writer, hash, sip};
66 use core::kinds::Sized;
71 /// `RandomSipHasher` computes the SipHash algorithm from a stream of bytes
72 /// initialized with random keys.
74 pub struct RandomSipHasher {
75 hasher: sip::SipHasher,
78 impl RandomSipHasher {
79 /// Construct a new `RandomSipHasher` that is initialized with random keys.
81 pub fn new() -> RandomSipHasher {
82 let mut r = rand::thread_rng();
86 hasher: sip::SipHasher::new_with_keys(r0, r1),
91 impl Hasher<sip::SipState> for RandomSipHasher {
93 fn hash<Sized? T: Hash<sip::SipState>>(&self, value: &T) -> u64 {
94 self.hasher.hash(value)
99 impl Default for RandomSipHasher {
102 fn default() -> RandomSipHasher {
103 RandomSipHasher::new()