]> git.lizzy.rs Git - rust.git/blob - library/core/src/hash/sip.rs
Rollup merge of #95040 - frank-king:fix/94981, r=Mark-Simulacrum
[rust.git] / library / core / src / hash / sip.rs
1 //! An implementation of SipHash.
2
3 #![allow(deprecated)] // the types in this module are deprecated
4
5 use crate::cmp;
6 use crate::marker::PhantomData;
7 use crate::mem;
8 use crate::ptr;
9
10 /// An implementation of SipHash 1-3.
11 ///
12 /// This is currently the default hashing function used by standard library
13 /// (e.g., `collections::HashMap` uses it by default).
14 ///
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)]
19 #[doc(hidden)]
20 pub struct SipHasher13 {
21     hasher: Hasher<Sip13Rounds>,
22 }
23
24 /// An implementation of SipHash 2-4.
25 ///
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)]
30 struct SipHasher24 {
31     hasher: Hasher<Sip24Rounds>,
32 }
33
34 /// An implementation of SipHash 2-4.
35 ///
36 /// See: <https://131002.net/siphash/>
37 ///
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).
42 ///
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);
50
51 #[derive(Debug)]
52 struct Hasher<S: Sip> {
53     k0: u64,
54     k1: u64,
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>,
60 }
61
62 #[derive(Debug, Clone, Copy)]
63 #[repr(C)]
64 struct State {
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.
69     v0: u64,
70     v2: u64,
71     v1: u64,
72     v3: u64,
73 }
74
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);
80         $v1 ^= $v0;
81         $v0 = $v0.rotate_left(32);
82         $v2 = $v2.wrapping_add($v3);
83         $v3 = $v3.rotate_left(16);
84         $v3 ^= $v2;
85         $v0 = $v0.wrapping_add($v3);
86         $v3 = $v3.rotate_left(21);
87         $v3 ^= $v0;
88         $v2 = $v2.wrapping_add($v1);
89         $v1 = $v1.rotate_left(17);
90         $v1 ^= $v2;
91         $v2 = $v2.rotate_left(32);
92     }};
93 }
94
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.
98 ///
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>(),
109         );
110         data.to_le()
111     }};
112 }
113
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.
117 ///
118 /// Safety: this performs unchecked indexing of `buf` at `start..start+len`, so
119 /// that must be in-bounds.
120 #[inline]
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
124     let mut out = 0;
125     if i + 3 < len {
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;
129         i += 4;
130     }
131     if i + 1 < len {
132         // SAFETY: same as above.
133         out |= (unsafe { load_int_le!(buf, start + i, u16) } as u64) << (i * 8);
134         i += 2
135     }
136     if i < len {
137         // SAFETY: same as above.
138         out |= (unsafe { *buf.get_unchecked(start + i) } as u64) << (i * 8);
139         i += 1;
140     }
141     debug_assert_eq!(i, len);
142     out
143 }
144
145 impl SipHasher {
146     /// Creates a new `SipHasher` with the two initial keys set to 0.
147     #[inline]
148     #[stable(feature = "rust1", since = "1.0.0")]
149     #[deprecated(
150         since = "1.13.0",
151         note = "use `std::collections::hash_map::DefaultHasher` instead"
152     )]
153     #[must_use]
154     pub fn new() -> SipHasher {
155         SipHasher::new_with_keys(0, 0)
156     }
157
158     /// Creates a `SipHasher` that is keyed off the provided keys.
159     #[inline]
160     #[stable(feature = "rust1", since = "1.0.0")]
161     #[deprecated(
162         since = "1.13.0",
163         note = "use `std::collections::hash_map::DefaultHasher` instead"
164     )]
165     #[must_use]
166     pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher {
167         SipHasher(SipHasher24 { hasher: Hasher::new_with_keys(key0, key1) })
168     }
169 }
170
171 impl SipHasher13 {
172     /// Creates a new `SipHasher13` with the two initial keys set to 0.
173     #[inline]
174     #[unstable(feature = "hashmap_internals", issue = "none")]
175     #[deprecated(
176         since = "1.13.0",
177         note = "use `std::collections::hash_map::DefaultHasher` instead"
178     )]
179     pub fn new() -> SipHasher13 {
180         SipHasher13::new_with_keys(0, 0)
181     }
182
183     /// Creates a `SipHasher13` that is keyed off the provided keys.
184     #[inline]
185     #[unstable(feature = "hashmap_internals", issue = "none")]
186     #[deprecated(
187         since = "1.13.0",
188         note = "use `std::collections::hash_map::DefaultHasher` instead"
189     )]
190     pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher13 {
191         SipHasher13 { hasher: Hasher::new_with_keys(key0, key1) }
192     }
193 }
194
195 impl<S: Sip> Hasher<S> {
196     #[inline]
197     fn new_with_keys(key0: u64, key1: u64) -> Hasher<S> {
198         let mut state = Hasher {
199             k0: key0,
200             k1: key1,
201             length: 0,
202             state: State { v0: 0, v1: 0, v2: 0, v3: 0 },
203             tail: 0,
204             ntail: 0,
205             _marker: PhantomData,
206         };
207         state.reset();
208         state
209     }
210
211     #[inline]
212     fn reset(&mut self) {
213         self.length = 0;
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;
218         self.ntail = 0;
219     }
220 }
221
222 #[stable(feature = "rust1", since = "1.0.0")]
223 impl super::Hasher for SipHasher {
224     #[inline]
225     fn write(&mut self, msg: &[u8]) {
226         self.0.hasher.write(msg)
227     }
228
229     #[inline]
230     fn write_str(&mut self, s: &str) {
231         self.0.hasher.write_str(s);
232     }
233
234     #[inline]
235     fn finish(&self) -> u64 {
236         self.0.hasher.finish()
237     }
238 }
239
240 #[unstable(feature = "hashmap_internals", issue = "none")]
241 impl super::Hasher for SipHasher13 {
242     #[inline]
243     fn write(&mut self, msg: &[u8]) {
244         self.hasher.write(msg)
245     }
246
247     #[inline]
248     fn write_str(&mut self, s: &str) {
249         self.hasher.write_str(s);
250     }
251
252     #[inline]
253     fn finish(&self) -> u64 {
254         self.hasher.finish()
255     }
256 }
257
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
265     // details.
266     #[inline]
267     fn write(&mut self, msg: &[u8]) {
268         let length = msg.len();
269         self.length += length;
270
271         let mut needed = 0;
272
273         if self.ntail != 0 {
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);
277             if length < needed {
278                 self.ntail += length;
279                 return;
280             } else {
281                 self.state.v3 ^= self.tail;
282                 S::c_rounds(&mut self.state);
283                 self.state.v0 ^= self.tail;
284                 self.ntail = 0;
285             }
286         }
287
288         // Buffered tail is now flushed, process new input.
289         let len = length - needed;
290         let left = len & 0x7; // len % 8
291
292         let mut i = needed;
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) };
298
299             self.state.v3 ^= mi;
300             S::c_rounds(&mut self.state);
301             self.state.v0 ^= mi;
302
303             i += 8;
304         }
305
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) };
310         self.ntail = left;
311     }
312
313     #[inline]
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());
318         self.write_u8(0xFF);
319     }
320
321     #[inline]
322     fn finish(&self) -> u64 {
323         let mut state = self.state;
324
325         let b: u64 = ((self.length as u64 & 0xff) << 56) | self.tail;
326
327         state.v3 ^= b;
328         S::c_rounds(&mut state);
329         state.v0 ^= b;
330
331         state.v2 ^= 0xff;
332         S::d_rounds(&mut state);
333
334         state.v0 ^ state.v1 ^ state.v2 ^ state.v3
335     }
336 }
337
338 impl<S: Sip> Clone for Hasher<S> {
339     #[inline]
340     fn clone(&self) -> Hasher<S> {
341         Hasher {
342             k0: self.k0,
343             k1: self.k1,
344             length: self.length,
345             state: self.state,
346             tail: self.tail,
347             ntail: self.ntail,
348             _marker: self._marker,
349         }
350     }
351 }
352
353 impl<S: Sip> Default for Hasher<S> {
354     /// Creates a `Hasher<S>` with the two initial keys set to 0.
355     #[inline]
356     fn default() -> Hasher<S> {
357         Hasher::new_with_keys(0, 0)
358     }
359 }
360
361 #[doc(hidden)]
362 trait Sip {
363     fn c_rounds(_: &mut State);
364     fn d_rounds(_: &mut State);
365 }
366
367 #[derive(Debug, Clone, Default)]
368 struct Sip13Rounds;
369
370 impl Sip for Sip13Rounds {
371     #[inline]
372     fn c_rounds(state: &mut State) {
373         compress!(state);
374     }
375
376     #[inline]
377     fn d_rounds(state: &mut State) {
378         compress!(state);
379         compress!(state);
380         compress!(state);
381     }
382 }
383
384 #[derive(Debug, Clone, Default)]
385 struct Sip24Rounds;
386
387 impl Sip for Sip24Rounds {
388     #[inline]
389     fn c_rounds(state: &mut State) {
390         compress!(state);
391         compress!(state);
392     }
393
394     #[inline]
395     fn d_rounds(state: &mut State) {
396         compress!(state);
397         compress!(state);
398         compress!(state);
399         compress!(state);
400     }
401 }