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)]
76 // v0, v2 and v1, v3 show up in pairs in the algorithm,
77 // and simd implementations of SipHash will use vectors
78 // of v02 and v13. By placing them in this order in the struct,
79 // the compiler can pick up on just a few simd optimizations by itself.
86 macro_rules! compress {
88 compress!($state.v0, $state.v1, $state.v2, $state.v3)
90 ($v0:expr, $v1:expr, $v2:expr, $v3:expr) =>
92 $v0 = $v0.wrapping_add($v1); $v1 = $v1.rotate_left(13); $v1 ^= $v0;
93 $v0 = $v0.rotate_left(32);
94 $v2 = $v2.wrapping_add($v3); $v3 = $v3.rotate_left(16); $v3 ^= $v2;
95 $v0 = $v0.wrapping_add($v3); $v3 = $v3.rotate_left(21); $v3 ^= $v0;
96 $v2 = $v2.wrapping_add($v1); $v1 = $v1.rotate_left(17); $v1 ^= $v2;
97 $v2 = $v2.rotate_left(32);
101 /// Load an integer of the desired type from a byte stream, in LE order. Uses
102 /// `copy_nonoverlapping` to let the compiler generate the most efficient way
103 /// to load it from a possibly unaligned address.
105 /// Unsafe because: unchecked indexing at i..i+size_of(int_ty)
106 macro_rules! load_int_le {
107 ($buf:expr, $i:expr, $int_ty:ident) =>
109 debug_assert!($i + mem::size_of::<$int_ty>() <= $buf.len());
110 let mut data = 0 as $int_ty;
111 ptr::copy_nonoverlapping($buf.get_unchecked($i),
112 &mut data as *mut _ as *mut u8,
113 mem::size_of::<$int_ty>());
118 /// Load an u64 using up to 7 bytes of a byte slice.
120 /// Unsafe because: unchecked indexing at start..start+len
122 unsafe fn u8to64_le(buf: &[u8], start: usize, len: usize) -> u64 {
123 debug_assert!(len < 8);
124 let mut i = 0; // current byte index (from LSB) in the output u64
127 out = load_int_le!(buf, start + i, u32) as u64;
131 out |= (load_int_le!(buf, start + i, u16) as u64) << (i * 8);
135 out |= (*buf.get_unchecked(start + i) as u64) << (i * 8);
138 debug_assert_eq!(i, len);
143 /// Creates a new `SipHasher` with the two initial keys set to 0.
145 #[stable(feature = "rust1", since = "1.0.0")]
146 #[rustc_deprecated(since = "1.13.0",
147 reason = "use `std::collections::hash_map::DefaultHasher` instead")]
148 pub fn new() -> SipHasher {
149 SipHasher::new_with_keys(0, 0)
152 /// Creates a `SipHasher` that is keyed off the provided keys.
154 #[stable(feature = "rust1", since = "1.0.0")]
155 #[rustc_deprecated(since = "1.13.0",
156 reason = "use `std::collections::hash_map::DefaultHasher` instead")]
157 pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher {
158 SipHasher(SipHasher24::new_with_keys(key0, key1))
163 /// Creates a new `SipHasher13` with the two initial keys set to 0.
165 #[unstable(feature = "sip_hash_13", issue = "34767")]
166 #[rustc_deprecated(since = "1.13.0",
167 reason = "use `std::collections::hash_map::DefaultHasher` instead")]
168 pub fn new() -> SipHasher13 {
169 SipHasher13::new_with_keys(0, 0)
172 /// Creates a `SipHasher13` that is keyed off the provided keys.
174 #[unstable(feature = "sip_hash_13", issue = "34767")]
175 #[rustc_deprecated(since = "1.13.0",
176 reason = "use `std::collections::hash_map::DefaultHasher` instead")]
177 pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher13 {
179 hasher: Hasher::new_with_keys(key0, key1)
185 /// Creates a new `SipHasher24` with the two initial keys set to 0.
187 #[unstable(feature = "sip_hash_13", issue = "34767")]
188 #[rustc_deprecated(since = "1.13.0",
189 reason = "use `std::collections::hash_map::DefaultHasher` instead")]
190 pub fn new() -> SipHasher24 {
191 SipHasher24::new_with_keys(0, 0)
194 /// Creates a `SipHasher24` that is keyed off the provided keys.
196 #[unstable(feature = "sip_hash_13", issue = "34767")]
197 #[rustc_deprecated(since = "1.13.0",
198 reason = "use `std::collections::hash_map::DefaultHasher` instead")]
199 pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher24 {
201 hasher: Hasher::new_with_keys(key0, key1)
206 impl<S: Sip> Hasher<S> {
208 fn new_with_keys(key0: u64, key1: u64) -> Hasher<S> {
209 let mut state = Hasher {
221 _marker: PhantomData,
228 fn reset(&mut self) {
230 self.state.v0 = self.k0 ^ 0x736f6d6570736575;
231 self.state.v1 = self.k1 ^ 0x646f72616e646f6d;
232 self.state.v2 = self.k0 ^ 0x6c7967656e657261;
233 self.state.v3 = self.k1 ^ 0x7465646279746573;
237 // Specialized write function that is only valid for buffers with len <= 8.
238 // It's used to force inlining of write_u8 and write_usize, those would normally be inlined
239 // except for composite types (that includes slices and str hashing because of delimiter).
240 // Without this extra push the compiler is very reluctant to inline delimiter writes,
241 // degrading performance substantially for the most common use cases.
243 fn short_write(&mut self, msg: &[u8]) {
244 debug_assert!(msg.len() <= 8);
245 let length = msg.len();
246 self.length += length;
248 let needed = 8 - self.ntail;
249 let fill = cmp::min(length, needed);
251 self.tail = unsafe { load_int_le!(msg, 0, u64) };
253 self.tail |= unsafe { u8to64_le(msg, 0, fill) } << (8 * self.ntail);
255 self.ntail += length;
259 self.state.v3 ^= self.tail;
260 S::c_rounds(&mut self.state);
261 self.state.v0 ^= self.tail;
263 // Buffered tail is now flushed, process new input.
264 self.ntail = length - needed;
265 self.tail = unsafe { u8to64_le(msg, needed, self.ntail) };
269 #[stable(feature = "rust1", since = "1.0.0")]
270 impl super::Hasher for SipHasher {
272 fn write(&mut self, msg: &[u8]) {
277 fn finish(&self) -> u64 {
282 #[unstable(feature = "sip_hash_13", issue = "34767")]
283 impl super::Hasher for SipHasher13 {
285 fn write(&mut self, msg: &[u8]) {
286 self.hasher.write(msg)
290 fn finish(&self) -> u64 {
295 #[unstable(feature = "sip_hash_13", issue = "34767")]
296 impl super::Hasher for SipHasher24 {
298 fn write(&mut self, msg: &[u8]) {
299 self.hasher.write(msg)
303 fn finish(&self) -> u64 {
308 impl<S: Sip> super::Hasher for Hasher<S> {
309 // see short_write comment for explanation
311 fn write_usize(&mut self, i: usize) {
313 ::slice::from_raw_parts(&i as *const usize as *const u8, mem::size_of::<usize>())
315 self.short_write(bytes);
318 // see short_write comment for explanation
320 fn write_u8(&mut self, i: u8) {
321 self.short_write(&[i]);
325 fn write(&mut self, msg: &[u8]) {
326 let length = msg.len();
327 self.length += length;
332 needed = 8 - self.ntail;
333 self.tail |= unsafe { u8to64_le(msg, 0, cmp::min(length, needed)) } << 8 * self.ntail;
335 self.ntail += length;
338 self.state.v3 ^= self.tail;
339 S::c_rounds(&mut self.state);
340 self.state.v0 ^= self.tail;
345 // Buffered tail is now flushed, process new input.
346 let len = length - needed;
347 let left = len & 0x7;
350 while i < len - left {
351 let mi = unsafe { load_int_le!(msg, i, u64) };
354 S::c_rounds(&mut self.state);
360 self.tail = unsafe { u8to64_le(msg, i, left) };
365 fn finish(&self) -> u64 {
366 let mut state = self.state;
368 let b: u64 = ((self.length as u64 & 0xff) << 56) | self.tail;
371 S::c_rounds(&mut state);
375 S::d_rounds(&mut state);
377 state.v0 ^ state.v1 ^ state.v2 ^ state.v3
381 impl<S: Sip> Clone for Hasher<S> {
383 fn clone(&self) -> Hasher<S> {
391 _marker: self._marker,
396 impl<S: Sip> Default for Hasher<S> {
397 /// Creates a `Hasher<S>` with the two initial keys set to 0.
399 fn default() -> Hasher<S> {
400 Hasher::new_with_keys(0, 0)
406 fn c_rounds(_: &mut State);
407 fn d_rounds(_: &mut State);
410 #[derive(Debug, Clone, Default)]
413 impl Sip for Sip13Rounds {
415 fn c_rounds(state: &mut State) {
420 fn d_rounds(state: &mut State) {
427 #[derive(Debug, Clone, Default)]
430 impl Sip for Sip24Rounds {
432 fn c_rounds(state: &mut State) {
438 fn d_rounds(state: &mut State) {