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