]> git.lizzy.rs Git - rust.git/blob - src/libcore/hash/sip.rs
Update const_forget.rs
[rust.git] / src / libcore / hash / sip.rs
1 //! An implementation of SipHash.
2
3 // ignore-tidy-undocumented-unsafe
4
5 #![allow(deprecated)] // the types in this module are deprecated
6
7 use crate::cmp;
8 use crate::marker::PhantomData;
9 use crate::mem;
10 use crate::ptr;
11
12 /// An implementation of SipHash 1-3.
13 ///
14 /// This is currently the default hashing function used by standard library
15 /// (e.g., `collections::HashMap` uses it by default).
16 ///
17 /// See: <https://131002.net/siphash>
18 #[unstable(feature = "hashmap_internals", issue = "none")]
19 #[rustc_deprecated(
20     since = "1.13.0",
21     reason = "use `std::collections::hash_map::DefaultHasher` instead"
22 )]
23 #[derive(Debug, Clone, Default)]
24 #[doc(hidden)]
25 pub struct SipHasher13 {
26     hasher: Hasher<Sip13Rounds>,
27 }
28
29 /// An implementation of SipHash 2-4.
30 ///
31 /// See: <https://131002.net/siphash/>
32 #[unstable(feature = "hashmap_internals", issue = "none")]
33 #[rustc_deprecated(
34     since = "1.13.0",
35     reason = "use `std::collections::hash_map::DefaultHasher` instead"
36 )]
37 #[derive(Debug, Clone, Default)]
38 struct SipHasher24 {
39     hasher: Hasher<Sip24Rounds>,
40 }
41
42 /// An implementation of SipHash 2-4.
43 ///
44 /// See: <https://131002.net/siphash/>
45 ///
46 /// SipHash is a general-purpose hashing function: it runs at a good
47 /// speed (competitive with Spooky and City) and permits strong _keyed_
48 /// hashing. This lets you key your hashtables from a strong RNG, such as
49 /// [`rand::os::OsRng`](https://doc.rust-lang.org/rand/rand/os/struct.OsRng.html).
50 ///
51 /// Although the SipHash algorithm is considered to be generally strong,
52 /// it is not intended for cryptographic purposes. As such, all
53 /// cryptographic uses of this implementation are _strongly discouraged_.
54 #[stable(feature = "rust1", since = "1.0.0")]
55 #[rustc_deprecated(
56     since = "1.13.0",
57     reason = "use `std::collections::hash_map::DefaultHasher` instead"
58 )]
59 #[derive(Debug, Clone, Default)]
60 pub struct SipHasher(SipHasher24);
61
62 #[derive(Debug)]
63 struct Hasher<S: Sip> {
64     k0: u64,
65     k1: u64,
66     length: usize, // how many bytes we've processed
67     state: State,  // hash State
68     tail: u64,     // unprocessed bytes le
69     ntail: usize,  // how many bytes in tail are valid
70     _marker: PhantomData<S>,
71 }
72
73 #[derive(Debug, Clone, Copy)]
74 #[repr(C)]
75 struct State {
76     // v0, v2 and v1, v3 show up in pairs in the algorithm,
77     // and simd implementations of SipHash will use vectors
78     // of v02 and v13. By placing them in this order in the struct,
79     // the compiler can pick up on just a few simd optimizations by itself.
80     v0: u64,
81     v2: u64,
82     v1: u64,
83     v3: u64,
84 }
85
86 macro_rules! compress {
87     ($state:expr) => {{ compress!($state.v0, $state.v1, $state.v2, $state.v3) }};
88     ($v0:expr, $v1:expr, $v2:expr, $v3:expr) => {{
89         $v0 = $v0.wrapping_add($v1);
90         $v1 = $v1.rotate_left(13);
91         $v1 ^= $v0;
92         $v0 = $v0.rotate_left(32);
93         $v2 = $v2.wrapping_add($v3);
94         $v3 = $v3.rotate_left(16);
95         $v3 ^= $v2;
96         $v0 = $v0.wrapping_add($v3);
97         $v3 = $v3.rotate_left(21);
98         $v3 ^= $v0;
99         $v2 = $v2.wrapping_add($v1);
100         $v1 = $v1.rotate_left(17);
101         $v1 ^= $v2;
102         $v2 = $v2.rotate_left(32);
103     }};
104 }
105
106 /// Loads an integer of the desired type from a byte stream, in LE order. Uses
107 /// `copy_nonoverlapping` to let the compiler generate the most efficient way
108 /// to load it from a possibly unaligned address.
109 ///
110 /// Unsafe because: unchecked indexing at i..i+size_of(int_ty)
111 macro_rules! load_int_le {
112     ($buf:expr, $i:expr, $int_ty:ident) => {{
113         debug_assert!($i + mem::size_of::<$int_ty>() <= $buf.len());
114         let mut data = 0 as $int_ty;
115         ptr::copy_nonoverlapping(
116             $buf.get_unchecked($i),
117             &mut data as *mut _ as *mut u8,
118             mem::size_of::<$int_ty>(),
119         );
120         data.to_le()
121     }};
122 }
123
124 /// Loads a u64 using up to 7 bytes of a byte slice. It looks clumsy but the
125 /// `copy_nonoverlapping` calls that occur (via `load_int_le!`) all have fixed
126 /// sizes and avoid calling `memcpy`, which is good for speed.
127 ///
128 /// Unsafe because: unchecked indexing at start..start+len
129 #[inline]
130 unsafe fn u8to64_le(buf: &[u8], start: usize, len: usize) -> u64 {
131     debug_assert!(len < 8);
132     let mut i = 0; // current byte index (from LSB) in the output u64
133     let mut out = 0;
134     if i + 3 < len {
135         out = load_int_le!(buf, start + i, u32) as u64;
136         i += 4;
137     }
138     if i + 1 < len {
139         out |= (load_int_le!(buf, start + i, u16) as u64) << (i * 8);
140         i += 2
141     }
142     if i < len {
143         out |= (*buf.get_unchecked(start + i) as u64) << (i * 8);
144         i += 1;
145     }
146     debug_assert_eq!(i, len);
147     out
148 }
149
150 impl SipHasher {
151     /// Creates a new `SipHasher` with the two initial keys set to 0.
152     #[inline]
153     #[stable(feature = "rust1", since = "1.0.0")]
154     #[rustc_deprecated(
155         since = "1.13.0",
156         reason = "use `std::collections::hash_map::DefaultHasher` instead"
157     )]
158     pub fn new() -> SipHasher {
159         SipHasher::new_with_keys(0, 0)
160     }
161
162     /// Creates a `SipHasher` that is keyed off the provided keys.
163     #[inline]
164     #[stable(feature = "rust1", since = "1.0.0")]
165     #[rustc_deprecated(
166         since = "1.13.0",
167         reason = "use `std::collections::hash_map::DefaultHasher` instead"
168     )]
169     pub 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     #[rustc_deprecated(
179         since = "1.13.0",
180         reason = "use `std::collections::hash_map::DefaultHasher` instead"
181     )]
182     pub fn new() -> SipHasher13 {
183         SipHasher13::new_with_keys(0, 0)
184     }
185
186     /// Creates a `SipHasher13` that is keyed off the provided keys.
187     #[inline]
188     #[unstable(feature = "hashmap_internals", issue = "none")]
189     #[rustc_deprecated(
190         since = "1.13.0",
191         reason = "use `std::collections::hash_map::DefaultHasher` instead"
192     )]
193     pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher13 {
194         SipHasher13 { hasher: Hasher::new_with_keys(key0, key1) }
195     }
196 }
197
198 impl<S: Sip> Hasher<S> {
199     #[inline]
200     fn new_with_keys(key0: u64, key1: u64) -> Hasher<S> {
201         let mut state = Hasher {
202             k0: key0,
203             k1: key1,
204             length: 0,
205             state: State { v0: 0, v1: 0, v2: 0, v3: 0 },
206             tail: 0,
207             ntail: 0,
208             _marker: PhantomData,
209         };
210         state.reset();
211         state
212     }
213
214     #[inline]
215     fn reset(&mut self) {
216         self.length = 0;
217         self.state.v0 = self.k0 ^ 0x736f6d6570736575;
218         self.state.v1 = self.k1 ^ 0x646f72616e646f6d;
219         self.state.v2 = self.k0 ^ 0x6c7967656e657261;
220         self.state.v3 = self.k1 ^ 0x7465646279746573;
221         self.ntail = 0;
222     }
223
224     // Specialized write function that is only valid for buffers with len <= 8.
225     // It's used to force inlining of write_u8 and write_usize, those would normally be inlined
226     // except for composite types (that includes slices and str hashing because of delimiter).
227     // Without this extra push the compiler is very reluctant to inline delimiter writes,
228     // degrading performance substantially for the most common use cases.
229     #[inline]
230     fn short_write(&mut self, msg: &[u8]) {
231         debug_assert!(msg.len() <= 8);
232         let length = msg.len();
233         self.length += length;
234
235         let needed = 8 - self.ntail;
236         let fill = cmp::min(length, needed);
237         if fill == 8 {
238             self.tail = unsafe { load_int_le!(msg, 0, u64) };
239         } else {
240             self.tail |= unsafe { u8to64_le(msg, 0, fill) } << (8 * self.ntail);
241             if length < needed {
242                 self.ntail += length;
243                 return;
244             }
245         }
246         self.state.v3 ^= self.tail;
247         S::c_rounds(&mut self.state);
248         self.state.v0 ^= self.tail;
249
250         // Buffered tail is now flushed, process new input.
251         self.ntail = length - needed;
252         self.tail = unsafe { u8to64_le(msg, needed, self.ntail) };
253     }
254 }
255
256 #[stable(feature = "rust1", since = "1.0.0")]
257 impl super::Hasher for SipHasher {
258     #[inline]
259     fn write(&mut self, msg: &[u8]) {
260         self.0.hasher.write(msg)
261     }
262
263     #[inline]
264     fn finish(&self) -> u64 {
265         self.0.hasher.finish()
266     }
267 }
268
269 #[unstable(feature = "hashmap_internals", issue = "none")]
270 impl super::Hasher for SipHasher13 {
271     #[inline]
272     fn write(&mut self, msg: &[u8]) {
273         self.hasher.write(msg)
274     }
275
276     #[inline]
277     fn finish(&self) -> u64 {
278         self.hasher.finish()
279     }
280 }
281
282 impl<S: Sip> super::Hasher for Hasher<S> {
283     // see short_write comment for explanation
284     #[inline]
285     fn write_usize(&mut self, i: usize) {
286         let bytes = unsafe {
287             crate::slice::from_raw_parts(&i as *const usize as *const u8, mem::size_of::<usize>())
288         };
289         self.short_write(bytes);
290     }
291
292     // see short_write comment for explanation
293     #[inline]
294     fn write_u8(&mut self, i: u8) {
295         self.short_write(&[i]);
296     }
297
298     #[inline]
299     fn write(&mut self, msg: &[u8]) {
300         let length = msg.len();
301         self.length += length;
302
303         let mut needed = 0;
304
305         if self.ntail != 0 {
306             needed = 8 - self.ntail;
307             self.tail |= unsafe { u8to64_le(msg, 0, cmp::min(length, needed)) } << (8 * self.ntail);
308             if length < needed {
309                 self.ntail += length;
310                 return;
311             } else {
312                 self.state.v3 ^= self.tail;
313                 S::c_rounds(&mut self.state);
314                 self.state.v0 ^= self.tail;
315                 self.ntail = 0;
316             }
317         }
318
319         // Buffered tail is now flushed, process new input.
320         let len = length - needed;
321         let left = len & 0x7;
322
323         let mut i = needed;
324         while i < len - left {
325             let mi = unsafe { load_int_le!(msg, i, u64) };
326
327             self.state.v3 ^= mi;
328             S::c_rounds(&mut self.state);
329             self.state.v0 ^= mi;
330
331             i += 8;
332         }
333
334         self.tail = unsafe { u8to64_le(msg, i, left) };
335         self.ntail = left;
336     }
337
338     #[inline]
339     fn finish(&self) -> u64 {
340         let mut state = self.state;
341
342         let b: u64 = ((self.length as u64 & 0xff) << 56) | self.tail;
343
344         state.v3 ^= b;
345         S::c_rounds(&mut state);
346         state.v0 ^= b;
347
348         state.v2 ^= 0xff;
349         S::d_rounds(&mut state);
350
351         state.v0 ^ state.v1 ^ state.v2 ^ state.v3
352     }
353 }
354
355 impl<S: Sip> Clone for Hasher<S> {
356     #[inline]
357     fn clone(&self) -> Hasher<S> {
358         Hasher {
359             k0: self.k0,
360             k1: self.k1,
361             length: self.length,
362             state: self.state,
363             tail: self.tail,
364             ntail: self.ntail,
365             _marker: self._marker,
366         }
367     }
368 }
369
370 impl<S: Sip> Default for Hasher<S> {
371     /// Creates a `Hasher<S>` with the two initial keys set to 0.
372     #[inline]
373     fn default() -> Hasher<S> {
374         Hasher::new_with_keys(0, 0)
375     }
376 }
377
378 #[doc(hidden)]
379 trait Sip {
380     fn c_rounds(_: &mut State);
381     fn d_rounds(_: &mut State);
382 }
383
384 #[derive(Debug, Clone, Default)]
385 struct Sip13Rounds;
386
387 impl Sip for Sip13Rounds {
388     #[inline]
389     fn c_rounds(state: &mut State) {
390         compress!(state);
391     }
392
393     #[inline]
394     fn d_rounds(state: &mut State) {
395         compress!(state);
396         compress!(state);
397         compress!(state);
398     }
399 }
400
401 #[derive(Debug, Clone, Default)]
402 struct Sip24Rounds;
403
404 impl Sip for Sip24Rounds {
405     #[inline]
406     fn c_rounds(state: &mut State) {
407         compress!(state);
408         compress!(state);
409     }
410
411     #[inline]
412     fn d_rounds(state: &mut State) {
413         compress!(state);
414         compress!(state);
415         compress!(state);
416         compress!(state);
417     }
418 }