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)]
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 {
160 hasher: Hasher::new_with_keys(key0, key1)
166 /// Creates a new `SipHasher13` with the two initial keys set to 0.
168 #[unstable(feature = "sip_hash_13", issue = "34767")]
169 #[rustc_deprecated(since = "1.13.0",
170 reason = "use `std::collections::hash_map::DefaultHasher` instead")]
171 pub fn new() -> SipHasher13 {
172 SipHasher13::new_with_keys(0, 0)
175 /// Creates a `SipHasher13` that is keyed off the provided keys.
177 #[unstable(feature = "sip_hash_13", issue = "34767")]
178 #[rustc_deprecated(since = "1.13.0",
179 reason = "use `std::collections::hash_map::DefaultHasher` instead")]
180 pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher13 {
182 hasher: Hasher::new_with_keys(key0, key1)
187 impl<S: Sip> Hasher<S> {
189 fn new_with_keys(key0: u64, key1: u64) -> Hasher<S> {
190 let mut state = Hasher {
202 _marker: PhantomData,
209 fn reset(&mut self) {
211 self.state.v0 = self.k0 ^ 0x736f6d6570736575;
212 self.state.v1 = self.k1 ^ 0x646f72616e646f6d;
213 self.state.v2 = self.k0 ^ 0x6c7967656e657261;
214 self.state.v3 = self.k1 ^ 0x7465646279746573;
218 // Specialized write function that is only valid for buffers with len <= 8.
219 // It's used to force inlining of write_u8 and write_usize, those would normally be inlined
220 // except for composite types (that includes slices and str hashing because of delimiter).
221 // Without this extra push the compiler is very reluctant to inline delimiter writes,
222 // degrading performance substantially for the most common use cases.
224 fn short_write(&mut self, msg: &[u8]) {
225 debug_assert!(msg.len() <= 8);
226 let length = msg.len();
227 self.length += length;
229 let needed = 8 - self.ntail;
230 let fill = cmp::min(length, needed);
232 self.tail = unsafe { load_int_le!(msg, 0, u64) };
234 self.tail |= unsafe { u8to64_le(msg, 0, fill) } << (8 * self.ntail);
236 self.ntail += length;
240 self.state.v3 ^= self.tail;
241 S::c_rounds(&mut self.state);
242 self.state.v0 ^= self.tail;
244 // Buffered tail is now flushed, process new input.
245 self.ntail = length - needed;
246 self.tail = unsafe { u8to64_le(msg, needed, self.ntail) };
250 #[stable(feature = "rust1", since = "1.0.0")]
251 impl super::Hasher for SipHasher {
253 fn write(&mut self, msg: &[u8]) {
254 self.0.hasher.write(msg)
258 fn finish(&self) -> u64 {
259 self.0.hasher.finish()
263 #[unstable(feature = "sip_hash_13", issue = "34767")]
264 impl super::Hasher for SipHasher13 {
266 fn write(&mut self, msg: &[u8]) {
267 self.hasher.write(msg)
271 fn finish(&self) -> u64 {
276 impl<S: Sip> super::Hasher for Hasher<S> {
277 // see short_write comment for explanation
279 fn write_usize(&mut self, i: usize) {
281 ::slice::from_raw_parts(&i as *const usize as *const u8, mem::size_of::<usize>())
283 self.short_write(bytes);
286 // see short_write comment for explanation
288 fn write_u8(&mut self, i: u8) {
289 self.short_write(&[i]);
293 fn write(&mut self, msg: &[u8]) {
294 let length = msg.len();
295 self.length += length;
300 needed = 8 - self.ntail;
301 self.tail |= unsafe { u8to64_le(msg, 0, cmp::min(length, needed)) } << 8 * self.ntail;
303 self.ntail += length;
306 self.state.v3 ^= self.tail;
307 S::c_rounds(&mut self.state);
308 self.state.v0 ^= self.tail;
313 // Buffered tail is now flushed, process new input.
314 let len = length - needed;
315 let left = len & 0x7;
318 while i < len - left {
319 let mi = unsafe { load_int_le!(msg, i, u64) };
322 S::c_rounds(&mut self.state);
328 self.tail = unsafe { u8to64_le(msg, i, left) };
333 fn finish(&self) -> u64 {
334 let mut state = self.state;
336 let b: u64 = ((self.length as u64 & 0xff) << 56) | self.tail;
339 S::c_rounds(&mut state);
343 S::d_rounds(&mut state);
345 state.v0 ^ state.v1 ^ state.v2 ^ state.v3
349 impl<S: Sip> Clone for Hasher<S> {
351 fn clone(&self) -> Hasher<S> {
359 _marker: self._marker,
364 impl<S: Sip> Default for Hasher<S> {
365 /// Creates a `Hasher<S>` with the two initial keys set to 0.
367 fn default() -> Hasher<S> {
368 Hasher::new_with_keys(0, 0)
374 fn c_rounds(_: &mut State);
375 fn d_rounds(_: &mut State);
378 #[derive(Debug, Clone, Default)]
381 impl Sip for Sip13Rounds {
383 fn c_rounds(state: &mut State) {
388 fn d_rounds(state: &mut State) {
395 #[derive(Debug, Clone, Default)]
398 impl Sip for Sip24Rounds {
400 fn c_rounds(state: &mut State) {
406 fn d_rounds(state: &mut State) {