1 //! An implementation of SipHash.
3 #![allow(deprecated)] // the types in this module are deprecated
6 use crate::marker::PhantomData;
10 /// An implementation of SipHash 1-3.
12 /// This is currently the default hashing function used by standard library
13 /// (e.g., `collections::HashMap` uses it by default).
15 /// See: <https://131002.net/siphash>
16 #[unstable(feature = "hashmap_internals", issue = "none")]
17 #[deprecated(since = "1.13.0", note = "use `std::collections::hash_map::DefaultHasher` instead")]
18 #[derive(Debug, Clone, Default)]
20 pub struct SipHasher13 {
21 hasher: Hasher<Sip13Rounds>,
24 /// An implementation of SipHash 2-4.
26 /// See: <https://131002.net/siphash/>
27 #[unstable(feature = "hashmap_internals", issue = "none")]
28 #[deprecated(since = "1.13.0", note = "use `std::collections::hash_map::DefaultHasher` instead")]
29 #[derive(Debug, Clone, Default)]
31 hasher: Hasher<Sip24Rounds>,
34 /// An implementation of SipHash 2-4.
36 /// See: <https://131002.net/siphash/>
38 /// SipHash is a general-purpose hashing function: it runs at a good
39 /// speed (competitive with Spooky and City) and permits strong _keyed_
40 /// hashing. This lets you key your hash tables from a strong RNG, such as
41 /// [`rand::os::OsRng`](https://docs.rs/rand/latest/rand/rngs/struct.OsRng.html).
43 /// Although the SipHash algorithm is considered to be generally strong,
44 /// it is not intended for cryptographic purposes. As such, all
45 /// cryptographic uses of this implementation are _strongly discouraged_.
46 #[stable(feature = "rust1", since = "1.0.0")]
47 #[deprecated(since = "1.13.0", note = "use `std::collections::hash_map::DefaultHasher` instead")]
48 #[derive(Debug, Clone, Default)]
49 pub struct SipHasher(SipHasher24);
52 struct Hasher<S: Sip> {
55 length: usize, // how many bytes we've processed
56 state: State, // hash State
57 tail: u64, // unprocessed bytes le
58 ntail: usize, // how many bytes in tail are valid
59 _marker: PhantomData<S>,
62 #[derive(Debug, Clone, Copy)]
65 // v0, v2 and v1, v3 show up in pairs in the algorithm,
66 // and simd implementations of SipHash will use vectors
67 // of v02 and v13. By placing them in this order in the struct,
68 // the compiler can pick up on just a few simd optimizations by itself.
75 macro_rules! compress {
76 ($state:expr) => {{ compress!($state.v0, $state.v1, $state.v2, $state.v3) }};
77 ($v0:expr, $v1:expr, $v2:expr, $v3:expr) => {{
78 $v0 = $v0.wrapping_add($v1);
79 $v1 = $v1.rotate_left(13);
81 $v0 = $v0.rotate_left(32);
82 $v2 = $v2.wrapping_add($v3);
83 $v3 = $v3.rotate_left(16);
85 $v0 = $v0.wrapping_add($v3);
86 $v3 = $v3.rotate_left(21);
88 $v2 = $v2.wrapping_add($v1);
89 $v1 = $v1.rotate_left(17);
91 $v2 = $v2.rotate_left(32);
95 /// Loads an integer of the desired type from a byte stream, in LE order. Uses
96 /// `copy_nonoverlapping` to let the compiler generate the most efficient way
97 /// to load it from a possibly unaligned address.
99 /// Safety: this performs unchecked indexing of `$buf` at
100 /// `$i..$i+size_of::<$int_ty>()`, so that must be in-bounds.
101 macro_rules! load_int_le {
102 ($buf:expr, $i:expr, $int_ty:ident) => {{
103 debug_assert!($i + mem::size_of::<$int_ty>() <= $buf.len());
104 let mut data = 0 as $int_ty;
105 ptr::copy_nonoverlapping(
106 $buf.as_ptr().add($i),
107 &mut data as *mut _ as *mut u8,
108 mem::size_of::<$int_ty>(),
114 /// Loads a u64 using up to 7 bytes of a byte slice. It looks clumsy but the
115 /// `copy_nonoverlapping` calls that occur (via `load_int_le!`) all have fixed
116 /// sizes and avoid calling `memcpy`, which is good for speed.
118 /// Safety: this performs unchecked indexing of `buf` at `start..start+len`, so
119 /// that must be in-bounds.
121 unsafe fn u8to64_le(buf: &[u8], start: usize, len: usize) -> u64 {
122 debug_assert!(len < 8);
123 let mut i = 0; // current byte index (from LSB) in the output u64
126 // SAFETY: `i` cannot be greater than `len`, and the caller must guarantee
127 // that the index start..start+len is in bounds.
128 out = unsafe { load_int_le!(buf, start + i, u32) } as u64;
132 // SAFETY: same as above.
133 out |= (unsafe { load_int_le!(buf, start + i, u16) } as u64) << (i * 8);
137 // SAFETY: same as above.
138 out |= (unsafe { *buf.get_unchecked(start + i) } as u64) << (i * 8);
141 debug_assert_eq!(i, len);
146 /// Creates a new `SipHasher` with the two initial keys set to 0.
148 #[stable(feature = "rust1", since = "1.0.0")]
151 note = "use `std::collections::hash_map::DefaultHasher` instead"
154 pub fn new() -> SipHasher {
155 SipHasher::new_with_keys(0, 0)
158 /// Creates a `SipHasher` that is keyed off the provided keys.
160 #[stable(feature = "rust1", since = "1.0.0")]
163 note = "use `std::collections::hash_map::DefaultHasher` instead"
166 pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher {
167 SipHasher(SipHasher24 { hasher: Hasher::new_with_keys(key0, key1) })
172 /// Creates a new `SipHasher13` with the two initial keys set to 0.
174 #[unstable(feature = "hashmap_internals", issue = "none")]
177 note = "use `std::collections::hash_map::DefaultHasher` instead"
179 pub fn new() -> SipHasher13 {
180 SipHasher13::new_with_keys(0, 0)
183 /// Creates a `SipHasher13` that is keyed off the provided keys.
185 #[unstable(feature = "hashmap_internals", issue = "none")]
188 note = "use `std::collections::hash_map::DefaultHasher` instead"
190 pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher13 {
191 SipHasher13 { hasher: Hasher::new_with_keys(key0, key1) }
195 impl<S: Sip> Hasher<S> {
197 fn new_with_keys(key0: u64, key1: u64) -> Hasher<S> {
198 let mut state = Hasher {
202 state: State { v0: 0, v1: 0, v2: 0, v3: 0 },
205 _marker: PhantomData,
212 fn reset(&mut self) {
214 self.state.v0 = self.k0 ^ 0x736f6d6570736575;
215 self.state.v1 = self.k1 ^ 0x646f72616e646f6d;
216 self.state.v2 = self.k0 ^ 0x6c7967656e657261;
217 self.state.v3 = self.k1 ^ 0x7465646279746573;
222 #[stable(feature = "rust1", since = "1.0.0")]
223 impl super::Hasher for SipHasher {
225 fn write(&mut self, msg: &[u8]) {
226 self.0.hasher.write(msg)
230 fn write_str(&mut self, s: &str) {
231 self.0.hasher.write_str(s);
235 fn finish(&self) -> u64 {
236 self.0.hasher.finish()
240 #[unstable(feature = "hashmap_internals", issue = "none")]
241 impl super::Hasher for SipHasher13 {
243 fn write(&mut self, msg: &[u8]) {
244 self.hasher.write(msg)
248 fn write_str(&mut self, s: &str) {
249 self.hasher.write_str(s);
253 fn finish(&self) -> u64 {
258 impl<S: Sip> super::Hasher for Hasher<S> {
259 // Note: no integer hashing methods (`write_u*`, `write_i*`) are defined
260 // for this type. We could add them, copy the `short_write` implementation
261 // in librustc_data_structures/sip128.rs, and add `write_u*`/`write_i*`
262 // methods to `SipHasher`, `SipHasher13`, and `DefaultHasher`. This would
263 // greatly speed up integer hashing by those hashers, at the cost of
264 // slightly slowing down compile speeds on some benchmarks. See #69152 for
267 fn write(&mut self, msg: &[u8]) {
268 let length = msg.len();
269 self.length += length;
274 needed = 8 - self.ntail;
275 // SAFETY: `cmp::min(length, needed)` is guaranteed to not be over `length`
276 self.tail |= unsafe { u8to64_le(msg, 0, cmp::min(length, needed)) } << (8 * self.ntail);
278 self.ntail += length;
281 self.state.v3 ^= self.tail;
282 S::c_rounds(&mut self.state);
283 self.state.v0 ^= self.tail;
288 // Buffered tail is now flushed, process new input.
289 let len = length - needed;
290 let left = len & 0x7; // len % 8
293 while i < len - left {
294 // SAFETY: because `len - left` is the biggest multiple of 8 under
295 // `len`, and because `i` starts at `needed` where `len` is `length - needed`,
296 // `i + 8` is guaranteed to be less than or equal to `length`.
297 let mi = unsafe { load_int_le!(msg, i, u64) };
300 S::c_rounds(&mut self.state);
306 // SAFETY: `i` is now `needed + len.div_euclid(8) * 8`,
307 // so `i + left` = `needed + len` = `length`, which is by
308 // definition equal to `msg.len()`.
309 self.tail = unsafe { u8to64_le(msg, i, left) };
314 fn write_str(&mut self, s: &str) {
315 // This hasher works byte-wise, and `0xFF` cannot show up in a `str`,
316 // so just hashing the one extra byte is enough to be prefix-free.
317 self.write(s.as_bytes());
322 fn finish(&self) -> u64 {
323 let mut state = self.state;
325 let b: u64 = ((self.length as u64 & 0xff) << 56) | self.tail;
328 S::c_rounds(&mut state);
332 S::d_rounds(&mut state);
334 state.v0 ^ state.v1 ^ state.v2 ^ state.v3
338 impl<S: Sip> Clone for Hasher<S> {
340 fn clone(&self) -> Hasher<S> {
348 _marker: self._marker,
353 impl<S: Sip> Default for Hasher<S> {
354 /// Creates a `Hasher<S>` with the two initial keys set to 0.
356 fn default() -> Hasher<S> {
357 Hasher::new_with_keys(0, 0)
363 fn c_rounds(_: &mut State);
364 fn d_rounds(_: &mut State);
367 #[derive(Debug, Clone, Default)]
370 impl Sip for Sip13Rounds {
372 fn c_rounds(state: &mut State) {
377 fn d_rounds(state: &mut State) {
384 #[derive(Debug, Clone, Default)]
387 impl Sip for Sip24Rounds {
389 fn c_rounds(state: &mut State) {
395 fn d_rounds(state: &mut State) {