]> git.lizzy.rs Git - rust.git/blob - library/core/src/hash/sip.rs
Auto merge of #105397 - matthiaskrgr:rollup-xv5imz8, r=matthiaskrgr
[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 const 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     //FIXME(fee1-dead): use debug_assert_eq
142     debug_assert!(i == len);
143     out
144 }
145
146 impl SipHasher {
147     /// Creates a new `SipHasher` with the two initial keys set to 0.
148     #[inline]
149     #[stable(feature = "rust1", since = "1.0.0")]
150     #[deprecated(
151         since = "1.13.0",
152         note = "use `std::collections::hash_map::DefaultHasher` instead"
153     )]
154     #[rustc_const_unstable(feature = "const_hash", issue = "104061")]
155     #[must_use]
156     pub const fn new() -> SipHasher {
157         SipHasher::new_with_keys(0, 0)
158     }
159
160     /// Creates a `SipHasher` that is keyed off the provided keys.
161     #[inline]
162     #[stable(feature = "rust1", since = "1.0.0")]
163     #[deprecated(
164         since = "1.13.0",
165         note = "use `std::collections::hash_map::DefaultHasher` instead"
166     )]
167     #[rustc_const_unstable(feature = "const_hash", issue = "104061")]
168     #[must_use]
169     pub const fn new_with_keys(key0: u64, key1: u64) -> SipHasher {
170         SipHasher(SipHasher24 { hasher: Hasher::new_with_keys(key0, key1) })
171     }
172 }
173
174 impl SipHasher13 {
175     /// Creates a new `SipHasher13` with the two initial keys set to 0.
176     #[inline]
177     #[unstable(feature = "hashmap_internals", issue = "none")]
178     #[deprecated(
179         since = "1.13.0",
180         note = "use `std::collections::hash_map::DefaultHasher` instead"
181     )]
182     #[rustc_const_unstable(feature = "const_hash", issue = "104061")]
183     pub const fn new() -> SipHasher13 {
184         SipHasher13::new_with_keys(0, 0)
185     }
186
187     /// Creates a `SipHasher13` that is keyed off the provided keys.
188     #[inline]
189     #[unstable(feature = "hashmap_internals", issue = "none")]
190     #[deprecated(
191         since = "1.13.0",
192         note = "use `std::collections::hash_map::DefaultHasher` instead"
193     )]
194     #[rustc_const_unstable(feature = "const_hash", issue = "104061")]
195     pub const fn new_with_keys(key0: u64, key1: u64) -> SipHasher13 {
196         SipHasher13 { hasher: Hasher::new_with_keys(key0, key1) }
197     }
198 }
199
200 impl<S: Sip> Hasher<S> {
201     #[inline]
202     const fn new_with_keys(key0: u64, key1: u64) -> Hasher<S> {
203         let mut state = Hasher {
204             k0: key0,
205             k1: key1,
206             length: 0,
207             state: State { v0: 0, v1: 0, v2: 0, v3: 0 },
208             tail: 0,
209             ntail: 0,
210             _marker: PhantomData,
211         };
212         state.reset();
213         state
214     }
215
216     #[inline]
217     const fn reset(&mut self) {
218         self.length = 0;
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;
223         self.ntail = 0;
224     }
225 }
226
227 #[stable(feature = "rust1", since = "1.0.0")]
228 #[rustc_const_unstable(feature = "const_hash", issue = "104061")]
229 impl const super::Hasher for SipHasher {
230     #[inline]
231     fn write(&mut self, msg: &[u8]) {
232         self.0.hasher.write(msg)
233     }
234
235     #[inline]
236     fn write_str(&mut self, s: &str) {
237         self.0.hasher.write_str(s);
238     }
239
240     #[inline]
241     fn finish(&self) -> u64 {
242         self.0.hasher.finish()
243     }
244 }
245
246 #[unstable(feature = "hashmap_internals", issue = "none")]
247 #[rustc_const_unstable(feature = "const_hash", issue = "104061")]
248 impl const super::Hasher for SipHasher13 {
249     #[inline]
250     fn write(&mut self, msg: &[u8]) {
251         self.hasher.write(msg)
252     }
253
254     #[inline]
255     fn write_str(&mut self, s: &str) {
256         self.hasher.write_str(s);
257     }
258
259     #[inline]
260     fn finish(&self) -> u64 {
261         self.hasher.finish()
262     }
263 }
264
265 impl<S: ~const Sip> const 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
272     // details.
273     #[inline]
274     fn write(&mut self, msg: &[u8]) {
275         let length = msg.len();
276         self.length += length;
277
278         let mut needed = 0;
279
280         if self.ntail != 0 {
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);
284             if length < needed {
285                 self.ntail += length;
286                 return;
287             } else {
288                 self.state.v3 ^= self.tail;
289                 S::c_rounds(&mut self.state);
290                 self.state.v0 ^= self.tail;
291                 self.ntail = 0;
292             }
293         }
294
295         // Buffered tail is now flushed, process new input.
296         let len = length - needed;
297         let left = len & 0x7; // len % 8
298
299         let mut i = needed;
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) };
305
306             self.state.v3 ^= mi;
307             S::c_rounds(&mut self.state);
308             self.state.v0 ^= mi;
309
310             i += 8;
311         }
312
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) };
317         self.ntail = left;
318     }
319
320     #[inline]
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());
325         self.write_u8(0xFF);
326     }
327
328     #[inline]
329     fn finish(&self) -> u64 {
330         let mut state = self.state;
331
332         let b: u64 = ((self.length as u64 & 0xff) << 56) | self.tail;
333
334         state.v3 ^= b;
335         S::c_rounds(&mut state);
336         state.v0 ^= b;
337
338         state.v2 ^= 0xff;
339         S::d_rounds(&mut state);
340
341         state.v0 ^ state.v1 ^ state.v2 ^ state.v3
342     }
343 }
344
345 impl<S: Sip> const Clone for Hasher<S> {
346     #[inline]
347     fn clone(&self) -> Hasher<S> {
348         Hasher {
349             k0: self.k0,
350             k1: self.k1,
351             length: self.length,
352             state: self.state,
353             tail: self.tail,
354             ntail: self.ntail,
355             _marker: self._marker,
356         }
357     }
358 }
359
360 impl<S: Sip> Default for Hasher<S> {
361     /// Creates a `Hasher<S>` with the two initial keys set to 0.
362     #[inline]
363     fn default() -> Hasher<S> {
364         Hasher::new_with_keys(0, 0)
365     }
366 }
367
368 #[doc(hidden)]
369 #[const_trait]
370 trait Sip {
371     fn c_rounds(_: &mut State);
372     fn d_rounds(_: &mut State);
373 }
374
375 #[derive(Debug, Clone, Default)]
376 struct Sip13Rounds;
377
378 impl const Sip for Sip13Rounds {
379     #[inline]
380     fn c_rounds(state: &mut State) {
381         compress!(state);
382     }
383
384     #[inline]
385     fn d_rounds(state: &mut State) {
386         compress!(state);
387         compress!(state);
388         compress!(state);
389     }
390 }
391
392 #[derive(Debug, Clone, Default)]
393 struct Sip24Rounds;
394
395 impl const Sip for Sip24Rounds {
396     #[inline]
397     fn c_rounds(state: &mut State) {
398         compress!(state);
399         compress!(state);
400     }
401
402     #[inline]
403     fn d_rounds(state: &mut State) {
404         compress!(state);
405         compress!(state);
406         compress!(state);
407         compress!(state);
408     }
409 }