Skip to main content

ahash/
aes_hash.rs

1use crate::convert::*;
2use crate::operations::*;
3use crate::random_state::PI_U128X2;
4use crate::RandomState;
5use core::hash::Hasher;
6
7/// A `Hasher` for hashing an arbitrary stream of bytes.
8///
9/// Instances of [`AHasher`] represent state that is updated while hashing data.
10///
11/// Each method updates the internal state based on the new data provided. Once
12/// all of the data has been provided, the resulting hash can be obtained by calling
13/// `finish()`
14///
15/// [Clone] is also provided in case you wish to calculate hashes for two different items that
16/// start with the same data.
17///
18#[derive(Debug, Clone)]
19pub struct AHasher {
20    /// A second copy of what `chain` last received, combined with `sum`.
21    echo: u128,
22    /// Collects what has passed through `echo`, so it never holds a value as supplied. Starts as the sum of the
23    /// keys: their xor would make `with_seeds(s, s, s, s)` independent of `s`.
24    sum: u128,
25    /// Takes each value as it arrives.
26    chain: u128,
27}
28
29impl AHasher {
30    /// Creates a new hasher keyed to the provided keys.
31    ///
32    /// Normally hashers are created via `AHasher::default()` for fixed keys or `RandomState::new()` for randomly
33    /// generated keys and `RandomState::with_seeds(a,b)` for seeds that are set and can be reused. All of these work at
34    /// map creation time (and hence don't have any overhead on a per-item basis).
35    ///
36    /// This method directly creates the hasher instance and performs no transformation on the provided seeds. This may
37    /// be useful where a HashBuilder is not desired, such as for testing purposes.
38    ///
39    /// # Example
40    ///
41    /// ```no_build
42    /// use std::hash::Hasher;
43    /// use ahash::AHasher;
44    ///
45    /// let mut hasher = AHasher::new_with_keys(1234, 5678);
46    ///
47    /// hasher.write_u32(1989);
48    /// hasher.write_u8(11);
49    /// hasher.write_u8(9);
50    /// hasher.write(b"Huh?");
51    ///
52    /// println!("Hash is {:x}!", hasher.finish());
53    /// ```
54    #[inline]
55    pub(crate) fn new_with_keys(key1: u128, key2: u128) -> Self {
56        let key1 = key1 ^ PI_U128X2[0];
57        let key2 = key2 ^ PI_U128X2[1];
58        Self {
59            echo: key1,
60            sum: add_by_64s(key1, key2),
61            chain: key2,
62        }
63    }
64
65    #[allow(unused)] // False positive
66    pub(crate) fn test_with_keys(key1: u128, key2: u128) -> Self {
67        Self {
68            echo: key1,
69            sum: add_by_64s(key1, key2),
70            chain: key2,
71        }
72    }
73
74    #[inline]
75    pub(crate) fn from_random_state(rand_state: &RandomState) -> Self {
76        let key1 = [rand_state.k0, rand_state.k1].convert();
77        let key2 = [rand_state.k2, rand_state.k3].convert();
78        Self {
79            echo: key1,
80            sum: add_by_64s(key1, key2),
81            chain: key2,
82        }
83    }
84
85    /// Adds one value. Every state gets a round: the value goes into `chain`, the new `chain` into `echo`, the old
86    /// `echo` into `sum`. A difference in a value is then in two states, one of which the input cannot reach, so
87    /// the next value alone cannot cancel it.
88    #[inline(always)]
89    fn hash_in(&mut self, new_value: u128) {
90        let (echo, sum, chain) = (self.echo, self.sum, self.chain);
91        // The value is usually ready last, so the rounds do not wait for it.
92        self.chain = aesenc_late(chain, new_value);
93        self.echo = aesenc_late(sum, self.chain);
94        self.sum = aesenc(echo, sum);
95    }
96
97    /// [Self::hash_in] for the first value of a `write`, with `sum_with_length` keying the round of the new `sum`.
98    #[inline(always)]
99    fn hash_in_first(&mut self, new_value: u128, sum_with_length: u128) {
100        let (echo, sum, chain) = (self.echo, self.sum, self.chain);
101        self.chain = aesenc_late(chain, new_value);
102        self.echo = aesenc_late(sum, self.chain);
103        self.sum = aesenc_late(echo, sum_with_length);
104    }
105
106    /// [Self::hash_in_first] followed by [Self::hash_in].
107    #[inline(always)]
108    fn hash_in_first_2(&mut self, v1: u128, v2: u128, sum_with_length: u128) {
109        let (echo, sum, chain) = (self.echo, self.sum, self.chain);
110        let chain1 = aesenc_late(chain, v1);
111        let echo1 = aesenc_late(sum, chain1);
112        let sum1 = aesenc_late(echo, sum_with_length);
113        self.chain = aesenc(chain1, v2);
114        self.echo = aesenc_late(sum1, self.chain);
115        self.sum = aesenc(echo1, sum1);
116    }
117
118    /// [Self::hash_in] twice, for values after the first of a `write`. Here the rounds wait on the state, not the
119    /// values, so the keys need not be applied late.
120    #[inline(always)]
121    fn hash_in_2(&mut self, v1: u128, v2: u128) {
122        let (echo, sum, chain) = (self.echo, self.sum, self.chain);
123        let chain1 = aesenc(chain, v1);
124        let echo1 = aesenc(sum, chain1);
125        let sum1 = aesenc(echo, sum);
126        self.chain = aesenc(chain1, v2);
127        self.echo = aesenc(sum1, self.chain);
128        self.sum = aesenc(echo1, sum1);
129    }
130
131    /// Adds more than 128 bytes.
132    ///
133    /// Eight lanes, held as four pairs. Each 32 bytes go into one pair, and the 32 starting one byte later into the
134    /// next, so every byte reaches two lanes at different positions and no part of the input can cancel the next.
135    /// (Inlined like the rest of `write`: a call would pass the state through memory.)
136    #[inline(always)]
137    fn hash_in_long(&mut self, data: &[u8], sum_with_length: u128) {
138        debug_assert!(data.len() > 128);
139        let (echo, sum, chain) = (self.echo, self.sum, self.chain);
140        // Each pair has its own secrets or operation, so no two lanes are related even on the same data.
141        // `first_pairs[1]` carries the length.
142        let first_pairs = [chain, aesenc_late(echo, sum_with_length)];
143        let last_pairs = [echo, sum];
144        // The last 128 bytes are read first, so the loop needs no special case for the end.
145        let tail = &data[data.len() - 128..];
146        let last = tail.read_last_u128x2();
147        // The second use of the last 32 bytes wraps around to the first byte, which would otherwise be used once.
148        let after_last = [
149            shift_in_byte(last[0], last[1]),
150            shift_in_byte(last[1], data.read_u128().0),
151        ];
152        let mut lanes: [[u128; 2]; 4] = [
153            aesenc_x2(first_pairs, tail.read_u128x2().0),
154            aesdec_x2(first_pairs, tail[1..].read_u128x2().0),
155            aesenc_x2(last_pairs, tail[33..].read_u128x2().0),
156            aesdec_x2(last_pairs, tail[65..].read_u128x2().0),
157        ];
158        lanes[1] = aesdec_x2(lanes[1], tail[32..].read_u128x2().0);
159        lanes[2] = aesdec_x2(lanes[2], tail[64..].read_u128x2().0);
160        lanes[3] = aesdec_x2(lanes[3], last);
161        lanes[0] = aesdec_x2(lanes[0], after_last);
162        // The rest, 128 bytes at a time. Each turn reads 129 bytes, always there while any are unread, so the last
163        // turn rereads part of the tail.
164        let mut data = data;
165        while data.len() > 128 {
166            hash_in_32_bytes(&mut lanes, 0, data);
167            hash_in_32_bytes(&mut lanes, 1, &data[32..]);
168            hash_in_32_bytes(&mut lanes, 2, &data[64..]);
169            hash_in_32_bytes(&mut lanes, 3, &data[96..]);
170            data = &data[128..];
171        }
172        // A lane's last input has had no round yet, so the last two pairs get one, then each lane is combined with one
173        // of the first two pairs, which never received the same bytes.
174        let zero = [0, 0];
175        let [t0, t1] = aesenc_x2(aesenc_x2(lanes[2], zero), lanes[0]);
176        let [t2, t3] = aesenc_x2(aesenc_x2(lanes[3], zero), lanes[1]);
177        // Four values become three, each keying the round of the one before, so no difference stays in one.
178        self.echo = aesenc(t1, t2);
179        self.sum = aesenc(t0, t1);
180        self.chain = aesenc(t2, t3);
181    }
182
183    /// For [AHasherFixed], which gets exactly one value: it goes into `sum`, which holds both keys, and its rounds
184    /// are in [Self::fixed_finish]. (Elsewhere values are added after a round, so a run of them costs one
185    /// operation each. With one value, the round can come after it, saving the rounds on the keys.)
186    #[inline(always)]
187    #[cfg(specialize)]
188    fn hash_in_fixed(&mut self, value: u128) {
189        self.sum = xor(self.sum, value);
190    }
191
192    #[inline]
193    #[cfg(specialize)]
194    fn fixed_finish(&self) -> u64 {
195        // Both keys are in the first round's input, so each key bit gets as many rounds as the value.
196        let c = aesenc(self.sum, self.echo);
197        let a = aesenc(aesenc(c, self.chain), PI_U128X2[0]);
198        cfg_if::cfg_if! {
199            if #[cfg(any(
200                all(any(target_arch = "x86", target_arch = "x86_64"), target_feature = "ssse3"),
201                target_arch = "aarch64"
202            ))] {
203                // Two bytes from each column, so each 32 bits of output depend on all 16 S-boxes of the last round,
204                // which cannot be undone.
205                spread_low64(a)
206            } else {
207                // Without a byte shuffle, a second stack does the same, as in `finish`.
208                let b = aesdec(aesdec(c, PI_U128X2[0]), PI_U128X2[1]);
209                let result: [u64; 2] = add_by_64s(a, b).convert();
210                result[0]
211            }
212        }
213    }
214}
215
216/// The first 32 bytes of `data` go into `lanes[pair]`, and the 32 bytes which start one byte later into the
217/// pair after it.
218#[inline(always)]
219fn hash_in_32_bytes(lanes: &mut [[u128; 2]; 4], pair: usize, data: &[u8]) {
220    lanes[pair] = aesdec_x2(lanes[pair], data.read_u128x2().0);
221    lanes[(pair + 1) % 4] = aesdec_x2(lanes[(pair + 1) % 4], data[1..].read_u128x2().0);
222}
223
224/// Provides [Hasher] methods to hash all of the primitive types.
225///
226/// [Hasher]: core::hash::Hasher
227impl Hasher for AHasher {
228    #[inline]
229    fn write_u8(&mut self, i: u8) {
230        self.write_u64(i as u64);
231    }
232
233    #[inline]
234    fn write_u16(&mut self, i: u16) {
235        self.write_u64(i as u64);
236    }
237
238    #[inline]
239    fn write_u32(&mut self, i: u32) {
240        self.write_u64(i as u64);
241    }
242
243    #[inline]
244    fn write_u128(&mut self, i: u128) {
245        self.hash_in(i);
246    }
247
248    #[inline]
249    #[cfg(any(
250        target_pointer_width = "64",
251        target_pointer_width = "32",
252        target_pointer_width = "16"
253    ))]
254    fn write_usize(&mut self, i: usize) {
255        self.write_u64(i as u64);
256    }
257
258    #[inline]
259    #[cfg(target_pointer_width = "128")]
260    fn write_usize(&mut self, i: usize) {
261        self.write_u128(i as u128);
262    }
263
264    #[inline]
265    fn write_u64(&mut self, i: u64) {
266        self.write_u128(i as u128);
267    }
268
269    // (Always inlined: a call would pass the state through memory, which costs more than the hashing.)
270    #[inline(always)]
271    #[allow(clippy::collapsible_if)]
272    fn write(&mut self, input: &[u8]) {
273        let data = input;
274        let length = data.len();
275        // The length goes only into the key of the next `sum`, the state never holding a value as supplied. (A slice
276        // hashes as its length, then its contents, so elsewhere the length could cancel a copy of itself.) The product
277        // makes two lengths differ in all eight bytes, so cancelling takes eight S-boxes, and no two lengths collide.
278        let mut sum_with_length = self.sum;
279        add_in_length(&mut sum_with_length, (length as u64).wrapping_mul(MULTIPLE));
280
281        // A binary search on the length keeps the comparisons few.
282        if data.len() <= 8 {
283            let value = read_small(data);
284            self.hash_in_first(value.convert(), sum_with_length);
285        } else {
286            if data.len() > 32 {
287                if data.len() > 64 {
288                    if data.len() > 128 {
289                        self.hash_in_long(data, sum_with_length);
290                    } else {
291                        //len 65-128
292                        let (head, _) = data.read_u128x4();
293                        let tail = data.read_last_u128x4();
294                        self.hash_in_first_2(head[0], head[1], sum_with_length);
295                        self.hash_in_2(head[2], head[3]);
296                        self.hash_in_2(tail[0], tail[1]);
297                        self.hash_in_2(tail[2], tail[3]);
298                    }
299                } else {
300                    //len 33-64
301                    let (head, _) = data.read_u128x2();
302                    let tail = data.read_last_u128x2();
303                    self.hash_in_first_2(head[0], head[1], sum_with_length);
304                    self.hash_in_2(tail[0], tail[1]);
305                }
306            } else {
307                if data.len() > 16 {
308                    //len 17-32
309                    self.hash_in_first_2(data.read_u128().0, data.read_last_u128(), sum_with_length);
310                } else {
311                    //len 9-16
312                    let value: [u64; 2] = [data.read_u64().0, data.read_last_u64()];
313                    self.hash_in_first(value.convert(), sum_with_length);
314                }
315            }
316        }
317    }
318    #[inline]
319    fn finish(&self) -> u64 {
320        // Two stacks of three rounds from `chain`, so each 32 bits of output depend on eight last-round S-boxes.
321        // (With one, the output difference for a fixed input difference is measurably non-uniform.) One decrypts, so
322        // they share no S-box and differ as functions; otherwise `v ^ k` would collide with `v`. `sum`, with the
323        // length, enters after `a`'s first round; `echo`'s older content, `chain ^ echo`, after `b`'s, two rounds
324        // before the output (one round before, a difference there could cancel through only ten S-boxes).
325        let a = aesenc(self.chain, self.sum);
326        let b = aesdec(self.chain, PI_U128X2[0]);
327        let a = aesenc(aesenc(a, PI_U128X2[1]), 0);
328        let b = aesdec(aesdec(b, xor(self.chain, self.echo)), 0);
329        let result: [u64; 2] = add_by_64s(a, b).convert();
330        result[0]
331    }
332}
333
334#[cfg(specialize)]
335pub(crate) struct AHasherU64 {
336    pub(crate) buffer: u64,
337    pub(crate) pad: u64,
338}
339
340/// A specialized hasher for only primitives under 64 bits.
341#[cfg(specialize)]
342impl Hasher for AHasherU64 {
343    #[inline]
344    fn finish(&self) -> u64 {
345        folded_multiply(self.buffer, self.pad)
346    }
347
348    #[inline]
349    fn write(&mut self, _bytes: &[u8]) {
350        unreachable!("Specialized hasher was called with a different type of object")
351    }
352
353    #[inline]
354    fn write_u8(&mut self, i: u8) {
355        self.write_u64(i as u64);
356    }
357
358    #[inline]
359    fn write_u16(&mut self, i: u16) {
360        self.write_u64(i as u64);
361    }
362
363    #[inline]
364    fn write_u32(&mut self, i: u32) {
365        self.write_u64(i as u64);
366    }
367
368    #[inline]
369    fn write_u64(&mut self, i: u64) {
370        self.buffer = folded_multiply(i ^ self.buffer, MULTIPLE);
371    }
372
373    #[inline]
374    fn write_u128(&mut self, _i: u128) {
375        unreachable!("Specialized hasher was called with a different type of object")
376    }
377
378    #[inline]
379    fn write_usize(&mut self, _i: usize) {
380        unreachable!("Specialized hasher was called with a different type of object")
381    }
382}
383
384#[cfg(specialize)]
385pub(crate) struct AHasherFixed(pub AHasher);
386
387/// A specialized hasher for primitives which are hashed as one value: `u128`, `i128`, `usize` and `isize`.
388#[cfg(specialize)]
389impl Hasher for AHasherFixed {
390    #[inline]
391    fn finish(&self) -> u64 {
392        self.0.fixed_finish()
393    }
394
395    #[inline]
396    fn write(&mut self, _bytes: &[u8]) {
397        unreachable!("Specialized hasher was called with a different type of object")
398    }
399
400    #[inline]
401    fn write_u8(&mut self, i: u8) {
402        self.write_u64(i as u64);
403    }
404
405    #[inline]
406    fn write_u16(&mut self, i: u16) {
407        self.write_u64(i as u64);
408    }
409
410    #[inline]
411    fn write_u32(&mut self, i: u32) {
412        self.write_u64(i as u64);
413    }
414
415    #[inline]
416    fn write_u64(&mut self, i: u64) {
417        self.0.hash_in_fixed(i as u128);
418    }
419
420    #[inline]
421    fn write_u128(&mut self, i: u128) {
422        self.0.hash_in_fixed(i);
423    }
424
425    #[inline]
426    fn write_usize(&mut self, i: usize) {
427        self.0.hash_in_fixed(i as u128);
428    }
429}
430
431#[cfg(specialize)]
432pub(crate) struct AHasherStr(pub AHasher);
433
434/// A specialized hasher for strings
435/// Note that the other types don't panic because the hash impl for String tacks on an unneeded call. (As does vec)
436#[cfg(specialize)]
437impl Hasher for AHasherStr {
438    #[inline]
439    fn finish(&self) -> u64 {
440        self.0.finish()
441    }
442
443    #[inline]
444    fn write(&mut self, bytes: &[u8]) {
445        self.0.write(bytes)
446    }
447
448    #[inline]
449    fn write_u8(&mut self, _i: u8) {}
450
451    #[inline]
452    fn write_u16(&mut self, _i: u16) {}
453
454    #[inline]
455    fn write_u32(&mut self, _i: u32) {}
456
457    #[inline]
458    fn write_u64(&mut self, _i: u64) {}
459
460    #[inline]
461    fn write_u128(&mut self, _i: u128) {}
462
463    #[inline]
464    fn write_usize(&mut self, _i: usize) {}
465}
466
467#[cfg(test)]
468mod tests {
469    use super::*;
470    use crate::convert::Convert;
471    use crate::operations::aesenc;
472    use crate::RandomState;
473    use std::hash::{BuildHasher, Hasher};
474    #[test]
475    fn test_sanity() {
476        let mut hasher = RandomState::with_seeds(1, 2, 3, 4).build_hasher();
477        hasher.write_u64(0);
478        let h1 = hasher.finish();
479        hasher.write(&[1, 0, 0, 0, 0, 0, 0, 0]);
480        let h2 = hasher.finish();
481        assert_ne!(h1, h2);
482    }
483
484    #[cfg(feature = "compile-time-rng")]
485    #[test]
486    fn test_builder() {
487        use std::collections::HashMap;
488        use std::hash::BuildHasherDefault;
489
490        let mut map = HashMap::<u32, u64, BuildHasherDefault<AHasher>>::default();
491        map.insert(1, 3);
492    }
493
494    #[cfg(feature = "compile-time-rng")]
495    #[test]
496    fn test_default() {
497        let hasher_a = AHasher::default();
498        let a_echo: [u64; 2] = hasher_a.echo.convert();
499        let a_sum: [u64; 2] = hasher_a.sum.convert();
500        assert_ne!(0, a_echo[0]);
501        assert_ne!(0, a_echo[1]);
502        assert_ne!(0, a_sum[0]);
503        assert_ne!(0, a_sum[1]);
504        assert_ne!(a_echo[0], a_echo[1]);
505        assert_ne!(a_sum[0], a_sum[1]);
506        assert_ne!(a_echo[0], a_sum[0]);
507        assert_ne!(a_echo[1], a_sum[1]);
508        let hasher_b = AHasher::default();
509        let b_echo: [u64; 2] = hasher_b.echo.convert();
510        let b_sum: [u64; 2] = hasher_b.sum.convert();
511        assert_eq!(a_echo[0], b_echo[0]);
512        assert_eq!(a_echo[1], b_echo[1]);
513        assert_eq!(a_sum[0], b_sum[0]);
514        assert_eq!(a_sum[1], b_sum[1]);
515    }
516
517    #[test]
518    fn test_hash() {
519        let mut result: [u64; 2] = [0x6c62272e07bb0142, 0x62b821756295c58d];
520        let value: [u64; 2] = [1 << 32, 0xFEDCBA9876543210];
521        result = aesenc(value.convert(), result.convert()).convert();
522        result = aesenc(result.convert(), result.convert()).convert();
523        let mut result2: [u64; 2] = [0x6c62272e07bb0142, 0x62b821756295c58d];
524        let value2: [u64; 2] = [1, 0xFEDCBA9876543210];
525        result2 = aesenc(value2.convert(), result2.convert()).convert();
526        result2 = aesenc(result2.convert(), result.convert()).convert();
527        let result: [u8; 16] = result.convert();
528        let result2: [u8; 16] = result2.convert();
529        assert_ne!(hex::encode(result), hex::encode(result2));
530    }
531}