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 hashtables 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.get_unchecked($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"
160 pub fn new() -> SipHasher {
161 SipHasher::new_with_keys(0, 0)
164 /// Creates a `SipHasher` that is keyed off the provided keys.
166 #[stable(feature = "rust1", since = "1.0.0")]
169 reason = "use `std::collections::hash_map::DefaultHasher` instead"
171 pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher {
172 SipHasher(SipHasher24 { hasher: Hasher::new_with_keys(key0, key1) })
177 /// Creates a new `SipHasher13` with the two initial keys set to 0.
179 #[unstable(feature = "hashmap_internals", issue = "none")]
182 reason = "use `std::collections::hash_map::DefaultHasher` instead"
184 pub fn new() -> SipHasher13 {
185 SipHasher13::new_with_keys(0, 0)
188 /// Creates a `SipHasher13` that is keyed off the provided keys.
190 #[unstable(feature = "hashmap_internals", issue = "none")]
193 reason = "use `std::collections::hash_map::DefaultHasher` instead"
195 pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher13 {
196 SipHasher13 { hasher: Hasher::new_with_keys(key0, key1) }
200 impl<S: Sip> Hasher<S> {
202 fn new_with_keys(key0: u64, key1: u64) -> Hasher<S> {
203 let mut state = Hasher {
207 state: State { v0: 0, v1: 0, v2: 0, v3: 0 },
210 _marker: PhantomData,
217 fn reset(&mut self) {
219 self.state.v0 = self.k0 ^ 0x736f6d6570736575;
220 self.state.v1 = self.k1 ^ 0x646f72616e646f6d;
221 self.state.v2 = self.k0 ^ 0x6c7967656e657261;
222 self.state.v3 = self.k1 ^ 0x7465646279746573;
227 #[stable(feature = "rust1", since = "1.0.0")]
228 impl super::Hasher for SipHasher {
230 fn write(&mut self, msg: &[u8]) {
231 self.0.hasher.write(msg)
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 finish(&self) -> u64 {
253 impl<S: Sip> super::Hasher for Hasher<S> {
254 // Note: no integer hashing methods (`write_u*`, `write_i*`) are defined
255 // for this type. We could add them, copy the `short_write` implementation
256 // in librustc_data_structures/sip128.rs, and add `write_u*`/`write_i*`
257 // methods to `SipHasher`, `SipHasher13`, and `DefaultHasher`. This would
258 // greatly speed up integer hashing by those hashers, at the cost of
259 // slightly slowing down compile speeds on some benchmarks. See #69152 for
262 fn write(&mut self, msg: &[u8]) {
263 let length = msg.len();
264 self.length += length;
269 needed = 8 - self.ntail;
270 // SAFETY: `cmp::min(length, needed)` is guaranteed to not be over `length`
271 self.tail |= unsafe { u8to64_le(msg, 0, cmp::min(length, needed)) } << (8 * self.ntail);
273 self.ntail += length;
276 self.state.v3 ^= self.tail;
277 S::c_rounds(&mut self.state);
278 self.state.v0 ^= self.tail;
283 // Buffered tail is now flushed, process new input.
284 let len = length - needed;
285 let left = len & 0x7; // len % 8
288 while i < len - left {
289 // SAFETY: because `len - left` is the biggest multiple of 8 under
290 // `len`, and because `i` starts at `needed` where `len` is `length - needed`,
291 // `i + 8` is guaranteed to be less than or equal to `length`.
292 let mi = unsafe { load_int_le!(msg, i, u64) };
295 S::c_rounds(&mut self.state);
301 // SAFETY: `i` is now `needed + len.div_euclid(8) * 8`,
302 // so `i + left` = `needed + len` = `length`, which is by
303 // definition equal to `msg.len()`.
304 self.tail = unsafe { u8to64_le(msg, i, left) };
309 fn finish(&self) -> u64 {
310 let mut state = self.state;
312 let b: u64 = ((self.length as u64 & 0xff) << 56) | self.tail;
315 S::c_rounds(&mut state);
319 S::d_rounds(&mut state);
321 state.v0 ^ state.v1 ^ state.v2 ^ state.v3
325 impl<S: Sip> Clone for Hasher<S> {
327 fn clone(&self) -> Hasher<S> {
335 _marker: self._marker,
340 impl<S: Sip> Default for Hasher<S> {
341 /// Creates a `Hasher<S>` with the two initial keys set to 0.
343 fn default() -> Hasher<S> {
344 Hasher::new_with_keys(0, 0)
350 fn c_rounds(_: &mut State);
351 fn d_rounds(_: &mut State);
354 #[derive(Debug, Clone, Default)]
357 impl Sip for Sip13Rounds {
359 fn c_rounds(state: &mut State) {
364 fn d_rounds(state: &mut State) {
371 #[derive(Debug, Clone, Default)]
374 impl Sip for Sip24Rounds {
376 fn c_rounds(state: &mut State) {
382 fn d_rounds(state: &mut State) {