1 // Copyright 2012-2015 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 //! An implementation of SipHash.
15 use marker::PhantomData;
20 /// An implementation of SipHash 1-3.
22 /// This is currently the default hashing function used by standard library
23 /// (eg. `collections::HashMap` uses it by default).
25 /// See: https://131002.net/siphash/
26 #[unstable(feature = "sip_hash_13", issue = "34767")]
27 #[rustc_deprecated(since = "1.13.0",
28 reason = "use `std::collections::hash_map::DefaultHasher` instead")]
29 #[derive(Debug, Clone, Default)]
30 pub struct SipHasher13 {
31 hasher: Hasher<Sip13Rounds>,
34 /// An implementation of SipHash 2-4.
36 /// See: https://131002.net/siphash/
37 #[unstable(feature = "sip_hash_13", issue = "34767")]
38 #[rustc_deprecated(since = "1.13.0",
39 reason = "use `std::collections::hash_map::DefaultHasher` instead")]
40 #[derive(Debug, Clone, Default)]
41 pub struct SipHasher24 {
42 hasher: Hasher<Sip24Rounds>,
45 /// An implementation of SipHash 2-4.
47 /// See: https://131002.net/siphash/
49 /// SipHash is a general-purpose hashing function: it runs at a good
50 /// speed (competitive with Spooky and City) and permits strong _keyed_
51 /// hashing. This lets you key your hashtables from a strong RNG, such as
52 /// [`rand::os::OsRng`](https://doc.rust-lang.org/rand/rand/os/struct.OsRng.html).
54 /// Although the SipHash algorithm is considered to be generally strong,
55 /// it is not intended for cryptographic purposes. As such, all
56 /// cryptographic uses of this implementation are _strongly discouraged_.
57 #[stable(feature = "rust1", since = "1.0.0")]
58 #[rustc_deprecated(since = "1.13.0",
59 reason = "use `std::collections::hash_map::DefaultHasher` instead")]
60 #[derive(Debug, Clone, Default)]
61 pub struct SipHasher(SipHasher24);
64 struct Hasher<S: Sip> {
67 length: usize, // how many bytes we've processed
68 state: State, // hash State
69 tail: u64, // unprocessed bytes le
70 ntail: usize, // how many bytes in tail are valid
71 _marker: PhantomData<S>,
74 #[derive(Debug, Clone, Copy)]
77 // v0, v2 and v1, v3 show up in pairs in the algorithm,
78 // and simd implementations of SipHash will use vectors
79 // of v02 and v13. By placing them in this order in the struct,
80 // the compiler can pick up on just a few simd optimizations by itself.
87 macro_rules! compress {
89 compress!($state.v0, $state.v1, $state.v2, $state.v3)
91 ($v0:expr, $v1:expr, $v2:expr, $v3:expr) =>
93 $v0 = $v0.wrapping_add($v1); $v1 = $v1.rotate_left(13); $v1 ^= $v0;
94 $v0 = $v0.rotate_left(32);
95 $v2 = $v2.wrapping_add($v3); $v3 = $v3.rotate_left(16); $v3 ^= $v2;
96 $v0 = $v0.wrapping_add($v3); $v3 = $v3.rotate_left(21); $v3 ^= $v0;
97 $v2 = $v2.wrapping_add($v1); $v1 = $v1.rotate_left(17); $v1 ^= $v2;
98 $v2 = $v2.rotate_left(32);
102 /// Load an integer of the desired type from a byte stream, in LE order. Uses
103 /// `copy_nonoverlapping` to let the compiler generate the most efficient way
104 /// to load it from a possibly unaligned address.
106 /// Unsafe because: unchecked indexing at i..i+size_of(int_ty)
107 macro_rules! load_int_le {
108 ($buf:expr, $i:expr, $int_ty:ident) =>
110 debug_assert!($i + mem::size_of::<$int_ty>() <= $buf.len());
111 let mut data = 0 as $int_ty;
112 ptr::copy_nonoverlapping($buf.get_unchecked($i),
113 &mut data as *mut _ as *mut u8,
114 mem::size_of::<$int_ty>());
119 /// Load an u64 using up to 7 bytes of a byte slice.
121 /// Unsafe because: unchecked indexing at start..start+len
123 unsafe fn u8to64_le(buf: &[u8], start: usize, len: usize) -> u64 {
124 debug_assert!(len < 8);
125 let mut i = 0; // current byte index (from LSB) in the output u64
128 out = load_int_le!(buf, start + i, u32) as u64;
132 out |= (load_int_le!(buf, start + i, u16) as u64) << (i * 8);
136 out |= (*buf.get_unchecked(start + i) as u64) << (i * 8);
139 debug_assert_eq!(i, len);
144 /// Creates a new `SipHasher` with the two initial keys set to 0.
146 #[stable(feature = "rust1", since = "1.0.0")]
147 #[rustc_deprecated(since = "1.13.0",
148 reason = "use `std::collections::hash_map::DefaultHasher` instead")]
149 pub fn new() -> SipHasher {
150 SipHasher::new_with_keys(0, 0)
153 /// Creates a `SipHasher` that is keyed off the provided keys.
155 #[stable(feature = "rust1", since = "1.0.0")]
156 #[rustc_deprecated(since = "1.13.0",
157 reason = "use `std::collections::hash_map::DefaultHasher` instead")]
158 pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher {
159 SipHasher(SipHasher24::new_with_keys(key0, key1))
164 /// Creates a new `SipHasher13` with the two initial keys set to 0.
166 #[unstable(feature = "sip_hash_13", issue = "34767")]
167 #[rustc_deprecated(since = "1.13.0",
168 reason = "use `std::collections::hash_map::DefaultHasher` instead")]
169 pub fn new() -> SipHasher13 {
170 SipHasher13::new_with_keys(0, 0)
173 /// Creates a `SipHasher13` that is keyed off the provided keys.
175 #[unstable(feature = "sip_hash_13", issue = "34767")]
176 #[rustc_deprecated(since = "1.13.0",
177 reason = "use `std::collections::hash_map::DefaultHasher` instead")]
178 pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher13 {
180 hasher: Hasher::new_with_keys(key0, key1)
186 /// Creates a new `SipHasher24` with the two initial keys set to 0.
188 #[unstable(feature = "sip_hash_13", issue = "34767")]
189 #[rustc_deprecated(since = "1.13.0",
190 reason = "use `std::collections::hash_map::DefaultHasher` instead")]
191 pub fn new() -> SipHasher24 {
192 SipHasher24::new_with_keys(0, 0)
195 /// Creates a `SipHasher24` that is keyed off the provided keys.
197 #[unstable(feature = "sip_hash_13", issue = "34767")]
198 #[rustc_deprecated(since = "1.13.0",
199 reason = "use `std::collections::hash_map::DefaultHasher` instead")]
200 pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher24 {
202 hasher: Hasher::new_with_keys(key0, key1)
207 impl<S: Sip> Hasher<S> {
209 fn new_with_keys(key0: u64, key1: u64) -> Hasher<S> {
210 let mut state = Hasher {
222 _marker: PhantomData,
229 fn reset(&mut self) {
231 self.state.v0 = self.k0 ^ 0x736f6d6570736575;
232 self.state.v1 = self.k1 ^ 0x646f72616e646f6d;
233 self.state.v2 = self.k0 ^ 0x6c7967656e657261;
234 self.state.v3 = self.k1 ^ 0x7465646279746573;
238 // Specialized write function that is only valid for buffers with len <= 8.
239 // It's used to force inlining of write_u8 and write_usize, those would normally be inlined
240 // except for composite types (that includes slices and str hashing because of delimiter).
241 // Without this extra push the compiler is very reluctant to inline delimiter writes,
242 // degrading performance substantially for the most common use cases.
244 fn short_write(&mut self, msg: &[u8]) {
245 debug_assert!(msg.len() <= 8);
246 let length = msg.len();
247 self.length += length;
249 let needed = 8 - self.ntail;
250 let fill = cmp::min(length, needed);
252 self.tail = unsafe { load_int_le!(msg, 0, u64) };
254 self.tail |= unsafe { u8to64_le(msg, 0, fill) } << (8 * self.ntail);
256 self.ntail += length;
260 self.state.v3 ^= self.tail;
261 S::c_rounds(&mut self.state);
262 self.state.v0 ^= self.tail;
264 // Buffered tail is now flushed, process new input.
265 self.ntail = length - needed;
266 self.tail = unsafe { u8to64_le(msg, needed, self.ntail) };
270 #[stable(feature = "rust1", since = "1.0.0")]
271 impl super::Hasher for SipHasher {
273 fn write(&mut self, msg: &[u8]) {
278 fn finish(&self) -> u64 {
283 #[unstable(feature = "sip_hash_13", issue = "34767")]
284 impl super::Hasher for SipHasher13 {
286 fn write(&mut self, msg: &[u8]) {
287 self.hasher.write(msg)
291 fn finish(&self) -> u64 {
296 #[unstable(feature = "sip_hash_13", issue = "34767")]
297 impl super::Hasher for SipHasher24 {
299 fn write(&mut self, msg: &[u8]) {
300 self.hasher.write(msg)
304 fn finish(&self) -> u64 {
309 impl<S: Sip> super::Hasher for Hasher<S> {
310 // see short_write comment for explanation
312 fn write_usize(&mut self, i: usize) {
314 ::slice::from_raw_parts(&i as *const usize as *const u8, mem::size_of::<usize>())
316 self.short_write(bytes);
319 // see short_write comment for explanation
321 fn write_u8(&mut self, i: u8) {
322 self.short_write(&[i]);
326 fn write(&mut self, msg: &[u8]) {
327 let length = msg.len();
328 self.length += length;
333 needed = 8 - self.ntail;
334 self.tail |= unsafe { u8to64_le(msg, 0, cmp::min(length, needed)) } << 8 * self.ntail;
336 self.ntail += length;
339 self.state.v3 ^= self.tail;
340 S::c_rounds(&mut self.state);
341 self.state.v0 ^= self.tail;
346 // Buffered tail is now flushed, process new input.
347 let len = length - needed;
348 let left = len & 0x7;
351 while i < len - left {
352 let mi = unsafe { load_int_le!(msg, i, u64) };
355 S::c_rounds(&mut self.state);
361 self.tail = unsafe { u8to64_le(msg, i, left) };
366 fn finish(&self) -> u64 {
367 let mut state = self.state;
369 let b: u64 = ((self.length as u64 & 0xff) << 56) | self.tail;
372 S::c_rounds(&mut state);
376 S::d_rounds(&mut state);
378 state.v0 ^ state.v1 ^ state.v2 ^ state.v3
382 impl<S: Sip> Clone for Hasher<S> {
384 fn clone(&self) -> Hasher<S> {
392 _marker: self._marker,
397 impl<S: Sip> Default for Hasher<S> {
398 /// Creates a `Hasher<S>` with the two initial keys set to 0.
400 fn default() -> Hasher<S> {
401 Hasher::new_with_keys(0, 0)
407 fn c_rounds(_: &mut State);
408 fn d_rounds(_: &mut State);
411 #[derive(Debug, Clone, Default)]
414 impl Sip for Sip13Rounds {
416 fn c_rounds(state: &mut State) {
421 fn d_rounds(state: &mut State) {
428 #[derive(Debug, Clone, Default)]
431 impl Sip for Sip24Rounds {
433 fn c_rounds(state: &mut State) {
439 fn d_rounds(state: &mut State) {