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")]
19 reason = "use `std::collections::hash_map::DefaultHasher` instead"
21 #[derive(Debug, Clone, Default)]
23 pub struct SipHasher13 {
24 hasher: Hasher<Sip13Rounds>,
27 /// An implementation of SipHash 2-4.
29 /// See: <https://131002.net/siphash/>
30 #[unstable(feature = "hashmap_internals", issue = "none")]
33 reason = "use `std::collections::hash_map::DefaultHasher` instead"
35 #[derive(Debug, Clone, Default)]
37 hasher: Hasher<Sip24Rounds>,
40 /// An implementation of SipHash 2-4.
42 /// See: <https://131002.net/siphash/>
44 /// SipHash is a general-purpose hashing function: it runs at a good
45 /// speed (competitive with Spooky and City) and permits strong _keyed_
46 /// hashing. This lets you key your hash tables from a strong RNG, such as
47 /// [`rand::os::OsRng`](https://doc.rust-lang.org/rand/rand/os/struct.OsRng.html).
49 /// Although the SipHash algorithm is considered to be generally strong,
50 /// it is not intended for cryptographic purposes. As such, all
51 /// cryptographic uses of this implementation are _strongly discouraged_.
52 #[stable(feature = "rust1", since = "1.0.0")]
55 reason = "use `std::collections::hash_map::DefaultHasher` instead"
57 #[derive(Debug, Clone, Default)]
58 pub struct SipHasher(SipHasher24);
61 struct Hasher<S: Sip> {
64 length: usize, // how many bytes we've processed
65 state: State, // hash State
66 tail: u64, // unprocessed bytes le
67 ntail: usize, // how many bytes in tail are valid
68 _marker: PhantomData<S>,
71 #[derive(Debug, Clone, Copy)]
74 // v0, v2 and v1, v3 show up in pairs in the algorithm,
75 // and simd implementations of SipHash will use vectors
76 // of v02 and v13. By placing them in this order in the struct,
77 // the compiler can pick up on just a few simd optimizations by itself.
84 macro_rules! compress {
85 ($state:expr) => {{ compress!($state.v0, $state.v1, $state.v2, $state.v3) }};
86 ($v0:expr, $v1:expr, $v2:expr, $v3:expr) => {{
87 $v0 = $v0.wrapping_add($v1);
88 $v1 = $v1.rotate_left(13);
90 $v0 = $v0.rotate_left(32);
91 $v2 = $v2.wrapping_add($v3);
92 $v3 = $v3.rotate_left(16);
94 $v0 = $v0.wrapping_add($v3);
95 $v3 = $v3.rotate_left(21);
97 $v2 = $v2.wrapping_add($v1);
98 $v1 = $v1.rotate_left(17);
100 $v2 = $v2.rotate_left(32);
104 /// Loads an integer of the desired type from a byte stream, in LE order. Uses
105 /// `copy_nonoverlapping` to let the compiler generate the most efficient way
106 /// to load it from a possibly unaligned address.
108 /// Unsafe because: unchecked indexing at i..i+size_of(int_ty)
109 macro_rules! load_int_le {
110 ($buf:expr, $i:expr, $int_ty:ident) => {{
111 debug_assert!($i + mem::size_of::<$int_ty>() <= $buf.len());
112 let mut data = 0 as $int_ty;
113 ptr::copy_nonoverlapping(
114 $buf.as_ptr().add($i),
115 &mut data as *mut _ as *mut u8,
116 mem::size_of::<$int_ty>(),
122 /// Loads a u64 using up to 7 bytes of a byte slice. It looks clumsy but the
123 /// `copy_nonoverlapping` calls that occur (via `load_int_le!`) all have fixed
124 /// sizes and avoid calling `memcpy`, which is good for speed.
126 /// Unsafe because: unchecked indexing at start..start+len
128 unsafe fn u8to64_le(buf: &[u8], start: usize, len: usize) -> u64 {
129 debug_assert!(len < 8);
130 let mut i = 0; // current byte index (from LSB) in the output u64
133 // SAFETY: `i` cannot be greater than `len`, and the caller must guarantee
134 // that the index start..start+len is in bounds.
135 out = unsafe { load_int_le!(buf, start + i, u32) } as u64;
139 // SAFETY: same as above.
140 out |= (unsafe { load_int_le!(buf, start + i, u16) } as u64) << (i * 8);
144 // SAFETY: same as above.
145 out |= (unsafe { *buf.get_unchecked(start + i) } as u64) << (i * 8);
148 debug_assert_eq!(i, len);
153 /// Creates a new `SipHasher` with the two initial keys set to 0.
155 #[stable(feature = "rust1", since = "1.0.0")]
158 reason = "use `std::collections::hash_map::DefaultHasher` instead"
161 pub fn new() -> SipHasher {
162 SipHasher::new_with_keys(0, 0)
165 /// Creates a `SipHasher` that is keyed off the provided keys.
167 #[stable(feature = "rust1", since = "1.0.0")]
170 reason = "use `std::collections::hash_map::DefaultHasher` instead"
173 pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher {
174 SipHasher(SipHasher24 { hasher: Hasher::new_with_keys(key0, key1) })
179 /// Creates a new `SipHasher13` with the two initial keys set to 0.
181 #[unstable(feature = "hashmap_internals", issue = "none")]
184 reason = "use `std::collections::hash_map::DefaultHasher` instead"
186 pub fn new() -> SipHasher13 {
187 SipHasher13::new_with_keys(0, 0)
190 /// Creates a `SipHasher13` that is keyed off the provided keys.
192 #[unstable(feature = "hashmap_internals", issue = "none")]
195 reason = "use `std::collections::hash_map::DefaultHasher` instead"
197 pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher13 {
198 SipHasher13 { hasher: Hasher::new_with_keys(key0, key1) }
202 impl<S: Sip> Hasher<S> {
204 fn new_with_keys(key0: u64, key1: u64) -> Hasher<S> {
205 let mut state = Hasher {
209 state: State { v0: 0, v1: 0, v2: 0, v3: 0 },
212 _marker: PhantomData,
219 fn reset(&mut self) {
221 self.state.v0 = self.k0 ^ 0x736f6d6570736575;
222 self.state.v1 = self.k1 ^ 0x646f72616e646f6d;
223 self.state.v2 = self.k0 ^ 0x6c7967656e657261;
224 self.state.v3 = self.k1 ^ 0x7465646279746573;
229 #[stable(feature = "rust1", since = "1.0.0")]
230 impl super::Hasher for SipHasher {
232 fn write(&mut self, msg: &[u8]) {
233 self.0.hasher.write(msg)
237 fn write_str(&mut self, s: &str) {
238 self.0.hasher.write_str(s);
242 fn finish(&self) -> u64 {
243 self.0.hasher.finish()
247 #[unstable(feature = "hashmap_internals", issue = "none")]
248 impl super::Hasher for SipHasher13 {
250 fn write(&mut self, msg: &[u8]) {
251 self.hasher.write(msg)
255 fn write_str(&mut self, s: &str) {
256 self.hasher.write_str(s);
260 fn finish(&self) -> u64 {
265 impl<S: Sip> super::Hasher for Hasher<S> {
266 // Note: no integer hashing methods (`write_u*`, `write_i*`) are defined
267 // for this type. We could add them, copy the `short_write` implementation
268 // in librustc_data_structures/sip128.rs, and add `write_u*`/`write_i*`
269 // methods to `SipHasher`, `SipHasher13`, and `DefaultHasher`. This would
270 // greatly speed up integer hashing by those hashers, at the cost of
271 // slightly slowing down compile speeds on some benchmarks. See #69152 for
274 fn write(&mut self, msg: &[u8]) {
275 let length = msg.len();
276 self.length += length;
281 needed = 8 - self.ntail;
282 // SAFETY: `cmp::min(length, needed)` is guaranteed to not be over `length`
283 self.tail |= unsafe { u8to64_le(msg, 0, cmp::min(length, needed)) } << (8 * self.ntail);
285 self.ntail += length;
288 self.state.v3 ^= self.tail;
289 S::c_rounds(&mut self.state);
290 self.state.v0 ^= self.tail;
295 // Buffered tail is now flushed, process new input.
296 let len = length - needed;
297 let left = len & 0x7; // len % 8
300 while i < len - left {
301 // SAFETY: because `len - left` is the biggest multiple of 8 under
302 // `len`, and because `i` starts at `needed` where `len` is `length - needed`,
303 // `i + 8` is guaranteed to be less than or equal to `length`.
304 let mi = unsafe { load_int_le!(msg, i, u64) };
307 S::c_rounds(&mut self.state);
313 // SAFETY: `i` is now `needed + len.div_euclid(8) * 8`,
314 // so `i + left` = `needed + len` = `length`, which is by
315 // definition equal to `msg.len()`.
316 self.tail = unsafe { u8to64_le(msg, i, left) };
321 fn write_str(&mut self, s: &str) {
322 // This hasher works byte-wise, and `0xFF` cannot show up in a `str`,
323 // so just hashing the one extra byte is enough to be prefix-free.
324 self.write(s.as_bytes());
329 fn finish(&self) -> u64 {
330 let mut state = self.state;
332 let b: u64 = ((self.length as u64 & 0xff) << 56) | self.tail;
335 S::c_rounds(&mut state);
339 S::d_rounds(&mut state);
341 state.v0 ^ state.v1 ^ state.v2 ^ state.v3
345 impl<S: Sip> Clone for Hasher<S> {
347 fn clone(&self) -> Hasher<S> {
355 _marker: self._marker,
360 impl<S: Sip> Default for Hasher<S> {
361 /// Creates a `Hasher<S>` with the two initial keys set to 0.
363 fn default() -> Hasher<S> {
364 Hasher::new_with_keys(0, 0)
370 fn c_rounds(_: &mut State);
371 fn d_rounds(_: &mut State);
374 #[derive(Debug, Clone, Default)]
377 impl Sip for Sip13Rounds {
379 fn c_rounds(state: &mut State) {
384 fn d_rounds(state: &mut State) {
391 #[derive(Debug, Clone, Default)]
394 impl Sip for Sip24Rounds {
396 fn c_rounds(state: &mut State) {
402 fn d_rounds(state: &mut State) {