Skip to main content

ahash/
fallback_hash.rs

1use crate::convert::*;
2use crate::operations::add_by_64s;
3use crate::operations::folded_multiply;
4use crate::operations::multiply_halves;
5use crate::operations::read_small;
6use crate::operations::xor;
7use crate::operations::MULTIPLE;
8use crate::random_state::PI_U128X2;
9use crate::RandomState;
10use core::hash::Hasher;
11
12/// How far `combine` rotates the word of the buffer which the high half was added to.
13///
14/// It is there so that a later block cannot undo what an earlier one did to a word with the same change to its
15/// input. (Without it, long inputs which are mostly zeros collide.) Were the keys the same for every block, 25
16/// would make blocks with a word in common least likely to collide: About one key in `2^42`. It is odd, so a word
17/// is back in the same position only after 128 blocks.
18const ROT: u32 = 25;
19
20/// A `Hasher` for hashing an arbitrary stream of bytes.
21///
22/// Instances of [`AHasher`] represent state that is updated while hashing data.
23///
24/// Each method updates the internal state based on the new data provided. Once
25/// all of the data has been provided, the resulting hash can be obtained by calling
26/// `finish()`
27///
28/// [Clone] is also provided in case you wish to calculate hashes for two different items that
29/// start with the same data.
30///
31#[derive(Debug, Clone)]
32pub struct AHasher {
33    /// The halves of each block's product go into one word each, and the words change places.
34    buffer: [u64; 2],
35    /// Xored with each block before it is multiplied. `increments` is added after every block.
36    keys: [u64; 2],
37    /// Always odd.
38    increments: [u64; 2],
39}
40
41/// What is added to the keys after each block: The sum of where the buffer and the keys start, so that it is secret
42/// too, and odd, so that each key differs from the one before.
43///
44/// It is one add, as a hasher is built for every value hashed. It is not an xor, because `new_with_keys` xors each
45/// key with a constant: Given the same key twice, an xor of the two would leave only the constants.
46#[inline(always)]
47fn increments(buffer: [u64; 2], keys: [u64; 2]) -> [u64; 2] {
48    let sum: [u64; 2] = add_by_64s(buffer.convert(), keys.convert()).convert();
49    [sum[0] | 1, sum[1] | 1]
50}
51
52impl AHasher {
53    /// Creates a new hasher keyed to the provided key.
54    #[inline]
55    #[allow(dead_code)] // Is not called if non-fallback hash is used.
56    pub(crate) fn new_with_keys(key1: u128, key2: u128) -> AHasher {
57        let key1: [u64; 2] = (key1 ^ PI_U128X2[0]).convert();
58        let key2: [u64; 2] = (key2 ^ PI_U128X2[1]).convert();
59        AHasher {
60            buffer: key1,
61            keys: key2,
62            increments: increments(key1, key2),
63        }
64    }
65
66    #[allow(unused)] // False positive
67    pub(crate) fn test_with_keys(key1: u128, key2: u128) -> Self {
68        let key1: [u64; 2] = key1.convert();
69        let key2: [u64; 2] = key2.convert();
70        Self {
71            buffer: key1,
72            keys: key2,
73            increments: increments(key1, key2),
74        }
75    }
76
77    #[inline]
78    #[allow(dead_code)] // Is not called if non-fallback hash is used.
79    pub(crate) fn from_random_state(rand_state: &RandomState) -> AHasher {
80        let buffer = [rand_state.k0, rand_state.k1];
81        let keys = [rand_state.k2, rand_state.k3];
82        AHasher {
83            buffer,
84            keys,
85            increments: increments(buffer, keys),
86        }
87    }
88
89    /// This update function has the goal of updating the buffer with a single multiply
90    /// FxHash does this but is vulnerable to attack. To avoid this input needs to be masked to with an
91    /// unpredictable value. Other hashes such as murmurhash have taken this approach but were found vulnerable
92    /// to attack. The attack was based on the idea of reversing the pre-mixing (Which is necessarily
93    /// reversible otherwise bits would be lost) then placing a difference in the highest bit before the
94    /// multiply used to mix the data. Because a multiply can never affect the bits to the right of it, a
95    /// subsequent update that also differed in this bit could result in a predictable collision.
96    ///
97    /// This version avoids this vulnerability while still only using a single multiply. It takes advantage
98    /// of the fact that when a 64 bit multiply is performed the upper 64 bits are usually computed and thrown
99    /// away. Instead it creates two 128 bit values where the upper 64 bits are zeros and multiplies them.
100    /// (The compiler is smart enough to turn this into a 64 bit multiplication in the assembly)
101    /// Then the upper bits are xored with the lower bits to produce a single 64 bit result.
102    ///
103    /// To understand why this is a good scrambling function it helps to understand multiply-with-carry PRNGs:
104    /// https://en.wikipedia.org/wiki/Multiply-with-carry_pseudorandom_number_generator
105    /// If the multiple is chosen well, this creates a long period, decent quality PRNG.
106    /// Notice that this function is equivalent to this except the `buffer`/`state` is being xored with each
107    /// new block of data. In the event that data is all zeros, it is exactly equivalent to an MWC PRNG.
108    ///
109    /// This is impervious to attack because every bit buffer at the end is dependent on every bit in
110    /// `new_data ^ buffer`. For example suppose two inputs differed in only the 5th bit. Then when the
111    /// multiplication is performed the `result` will differ in bits 5-69. More specifically it will differ by
112    /// 2^5 * MULTIPLE. However in the next step bits 65-128 are turned into a separate 64 bit value. So the
113    /// differing bits will be in the lower 6 bits of this value. The two intermediate values that differ in
114    /// bits 5-63 and in bits 0-5 respectively get added together. Producing an output that differs in every
115    /// bit. The addition carries in the multiplication and at the end additionally mean that even if an
116    /// attacker somehow knew part of (but not all) the contents of the buffer beforehand,
117    /// they would not be able to predict any of the bits in the buffer at the end.
118    #[inline(always)]
119    fn update(&mut self, new_data: u64) {
120        self.buffer[0] = folded_multiply(new_data ^ self.buffer[0], MULTIPLE);
121    }
122
123    /// Similar to the above this function performs an update using a multiply.
124    /// However it takes in 128 bits of data instead of 64, and xors each half with a key itself.
125    ///
126    /// Unlike in `update` both operands of the multiply are derived from the input, so the two halves of the product
127    /// go into the two words of the buffer. (See `combine`.)
128    ///
129    /// The keys change after every block so the same delta cannot be applied repeatedly.
130    #[inline(always)]
131    fn hash_in(&mut self, new_value: u128) {
132        // (A word at a time, so that nothing comes between the input and the multiply.)
133        let block: [u64; 2] = new_value.convert();
134        self.buffer = Self::combine(self.buffer, [block[0] ^ self.keys[0], block[1] ^ self.keys[1]]);
135        self.keys = [
136            self.keys[0].wrapping_add(self.increments[0]),
137            self.keys[1].wrapping_add(self.increments[1]),
138        ];
139    }
140
141    /// Performs a wide multiply and xors and adds the halves in to the buffer.
142    /// The added side is rotated to introduce asymmetry and the halves are swapped.
143    /// (Addition and xors don't commute.)
144    #[inline(always)]
145    fn combine([added, xored]: [u64; 2], [s, by]: [u64; 2]) -> [u64; 2] {
146        let [low, high] = multiply_halves(s, by);
147        [xored.wrapping_add(high), added.rotate_left(ROT) ^ low]
148    }
149
150    /// `hash_in` for two blocks. After it the words of the buffer are back where they started.
151    #[inline(always)]
152    fn hash_in_2(&mut self, first: u128, second: u128) {
153        self.hash_in(first);
154        self.hash_in(second);
155    }
156
157    /// Process data > 32 bytes.
158    #[inline(always)]
159    fn hash_in_long(&mut self, mut data: &[u8]) {
160        debug_assert!(data.len() > 32);
161        // (These products are needed first, so they take their keys the way `hash_in` does.)
162        let [first, second] = data.read_last_u128x2();
163        self.hash_in_2(first, second);
164        let mut buffer = self.buffer;
165        let mut keys: u128 = self.keys.convert();
166        let increments: u128 = self.increments.convert();
167        while data.len() > 32 {
168            let (blocks, rest) = data.read_u128x2();
169            for block in blocks {
170                // (The keys stay in a vector register: One load, one xor and one add for a block. The operands
171                // then have to be moved to be multiplied, but in a loop they are ready before the buffer is.)
172                let operands: [u64; 2] = xor(block, keys).convert();
173                keys = add_by_64s(keys, increments);
174                buffer = Self::combine(buffer, operands);
175            }
176            data = rest;
177        }
178        self.buffer = buffer;
179        self.keys = keys.convert();
180    }
181
182    /// Adds the length of a `write` to the buffer.
183    #[inline(always)]
184    fn add_length(&mut self, length: usize) {
185        //Needs to be an add rather than an xor because otherwise it could be canceled with carefully formed input.
186        self.buffer[0] = self.buffer[0].wrapping_add(length as u64).wrapping_mul(MULTIPLE);
187    }
188
189    #[inline]
190    #[cfg(specialize)]
191    fn short_finish(&self) -> u64 {
192        folded_multiply(self.buffer[0], self.buffer[1])
193    }
194}
195
196/// Provides [Hasher] methods to hash all of the primitive types.
197///
198/// [Hasher]: core::hash::Hasher
199impl Hasher for AHasher {
200    #[inline]
201    fn write_u8(&mut self, i: u8) {
202        self.update(i as u64);
203    }
204
205    #[inline]
206    fn write_u16(&mut self, i: u16) {
207        self.update(i as u64);
208    }
209
210    #[inline]
211    fn write_u32(&mut self, i: u32) {
212        self.update(i as u64);
213    }
214
215    #[inline]
216    fn write_u64(&mut self, i: u64) {
217        self.update(i);
218    }
219
220    #[inline]
221    fn write_u128(&mut self, i: u128) {
222        self.hash_in(i);
223    }
224
225    #[inline]
226    #[cfg(any(
227        target_pointer_width = "64",
228        target_pointer_width = "32",
229        target_pointer_width = "16"
230    ))]
231    fn write_usize(&mut self, i: usize) {
232        self.write_u64(i as u64);
233    }
234
235    #[inline]
236    #[cfg(target_pointer_width = "128")]
237    fn write_usize(&mut self, i: usize) {
238        self.write_u128(i as u128);
239    }
240
241    // (Up to 16 bytes inlined: a call would pass the state through memory. Longer input does make one, so that what
242    // is inlined stays small enough for LLVM to also inline the callers of `write`, such as `write_str`.)
243    #[inline(always)]
244    fn write(&mut self, input: &[u8]) {
245        if input.len() <= 16 {
246            self.add_length(input.len());
247            // (One block for both lengths, so that there is one copy of it to inline.)
248            let value = if input.len() > 8 {
249                [input.read_u64().0, input.read_last_u64()]
250            } else {
251                read_small(input)
252            };
253            self.hash_in(value.convert());
254        } else {
255            let (low, high) = write_over_16(self.buffer[0], self.buffer[1], &mut self.keys, &self.increments, input);
256            self.buffer = [low, high];
257        }
258    }
259
260    #[inline]
261    fn finish(&self) -> u64 {
262        let rot = (self.buffer[0] & 63) as u32;
263        folded_multiply(self.buffer[0], self.buffer[1]).rotate_left(rot)
264    }
265}
266
267/// [AHasher::write] for more than 16 bytes: Takes the buffer and returns it updated, and steps `keys`.
268///
269/// (The buffer goes both ways in registers: As a `[u64; 2]` it would go through memory. The keys and increments go
270/// by reference: By value there would be more arguments than registers to pass them in.)
271#[inline(never)]
272fn write_over_16(low: u64, high: u64, keys: &mut [u64; 2], increments: &[u64; 2], data: &[u8]) -> (u64, u64) {
273    debug_assert!(data.len() > 16);
274    let mut hasher = AHasher {
275        buffer: [low, high],
276        keys: *keys,
277        increments: *increments,
278    };
279    hasher.add_length(data.len());
280    //A 'binary search' on sizes reduces the number of comparisons.
281    if data.len() > 32 {
282        if data.len() > 64 {
283            hasher.hash_in_long(data);
284        } else {
285            //len 33-64, in the order `hash_in_long` would take it
286            let [first, second] = data.read_last_u128x2();
287            hasher.hash_in_2(first, second);
288            let ([first, second], _) = data.read_u128x2();
289            hasher.hash_in_2(first, second);
290        }
291    } else {
292        //len 17-32
293        hasher.hash_in_2(data.read_u128().0, data.read_last_u128());
294    }
295    *keys = hasher.keys;
296    (hasher.buffer[0], hasher.buffer[1])
297}
298
299#[cfg(specialize)]
300pub(crate) struct AHasherU64 {
301    pub(crate) buffer: u64,
302    pub(crate) pad: u64,
303}
304
305/// A specialized hasher for only primitives under 64 bits.
306#[cfg(specialize)]
307impl Hasher for AHasherU64 {
308    #[inline]
309    fn finish(&self) -> u64 {
310        folded_multiply(self.buffer, self.pad)
311        //self.buffer
312    }
313
314    #[inline]
315    fn write(&mut self, _bytes: &[u8]) {
316        unreachable!("Specialized hasher was called with a different type of object")
317    }
318
319    #[inline]
320    fn write_u8(&mut self, i: u8) {
321        self.write_u64(i as u64);
322    }
323
324    #[inline]
325    fn write_u16(&mut self, i: u16) {
326        self.write_u64(i as u64);
327    }
328
329    #[inline]
330    fn write_u32(&mut self, i: u32) {
331        self.write_u64(i as u64);
332    }
333
334    #[inline]
335    fn write_u64(&mut self, i: u64) {
336        self.buffer = folded_multiply(i ^ self.buffer, MULTIPLE);
337    }
338
339    #[inline]
340    fn write_u128(&mut self, _i: u128) {
341        unreachable!("Specialized hasher was called with a different type of object")
342    }
343
344    #[inline]
345    fn write_usize(&mut self, _i: usize) {
346        unreachable!("Specialized hasher was called with a different type of object")
347    }
348}
349
350#[cfg(specialize)]
351pub(crate) struct AHasherFixed(pub AHasher);
352
353/// A specialized hasher for fixed size primitives larger than 64 bits.
354#[cfg(specialize)]
355impl Hasher for AHasherFixed {
356    #[inline]
357    fn finish(&self) -> u64 {
358        self.0.short_finish()
359    }
360
361    #[inline]
362    fn write(&mut self, bytes: &[u8]) {
363        self.0.write(bytes)
364    }
365
366    #[inline]
367    fn write_u8(&mut self, i: u8) {
368        self.write_u64(i as u64);
369    }
370
371    #[inline]
372    fn write_u16(&mut self, i: u16) {
373        self.write_u64(i as u64);
374    }
375
376    #[inline]
377    fn write_u32(&mut self, i: u32) {
378        self.write_u64(i as u64);
379    }
380
381    #[inline]
382    fn write_u64(&mut self, i: u64) {
383        self.0.write_u64(i);
384    }
385
386    #[inline]
387    fn write_u128(&mut self, i: u128) {
388        self.0.write_u128(i);
389    }
390
391    #[inline]
392    fn write_usize(&mut self, i: usize) {
393        self.0.write_usize(i);
394    }
395}
396
397#[cfg(specialize)]
398pub(crate) struct AHasherStr(pub AHasher);
399
400/// A specialized hasher for a single string
401/// Note that the other types don't panic because the hash impl for String tacks on an unneeded call. (As does vec)
402#[cfg(specialize)]
403impl Hasher for AHasherStr {
404    #[inline]
405    fn finish(&self) -> u64 {
406        self.0.finish()
407    }
408
409    #[inline]
410    fn write(&mut self, bytes: &[u8]) {
411        if bytes.len() > 8 {
412            self.0.write(bytes)
413        } else {
414            let value = read_small(bytes);
415            // Both operands depend on the input here too, but only in their low 32 bits. Xoring the halves of
416            // the product is only a problem when all of the bits of an operand can be complemented.
417            // (See `test_short_string_differences_do_not_scale`.)
418            self.0.buffer[0] = folded_multiply(value[0] ^ self.0.buffer[0], value[1] ^ self.0.keys[1]);
419            self.0.buffer[1] = self.0.buffer[1].wrapping_add(bytes.len() as u64);
420        }
421    }
422
423    #[inline]
424    fn write_u8(&mut self, _i: u8) {}
425
426    #[inline]
427    fn write_u16(&mut self, _i: u16) {}
428
429    #[inline]
430    fn write_u32(&mut self, _i: u32) {}
431
432    #[inline]
433    fn write_u64(&mut self, _i: u64) {}
434
435    #[inline]
436    fn write_u128(&mut self, _i: u128) {}
437
438    #[inline]
439    fn write_usize(&mut self, _i: usize) {}
440}
441
442#[cfg(test)]
443mod tests {
444    use crate::fallback_hash::*;
445
446    #[test]
447    fn test_hash() {
448        let mut hasher = AHasher::new_with_keys(0, 0);
449        let value: u64 = 1 << 32;
450        hasher.update(value);
451        let result = hasher.buffer[0];
452        let mut hasher = AHasher::new_with_keys(0, 0);
453        let value2: u64 = 1;
454        hasher.update(value2);
455        let result2 = hasher.buffer[0];
456        let result: [u8; 8] = result.convert();
457        let result2: [u8; 8] = result2.convert();
458        assert_ne!(hex::encode(result), hex::encode(result2));
459    }
460
461    /// An even increment would leave the low bit of a key the same for every block, and zero the whole key.
462    #[test]
463    fn test_increments_are_odd() {
464        for (key1, key2) in [
465            (0_u128, 0_u128),
466            (1, 1),
467            (u128::MAX, 1),
468            (1 << 64, 1 << 64),
469            (3, 5 << 64),
470        ] {
471            let ([k0, k1], [k2, k3]): ([u64; 2], [u64; 2]) = (key1.convert(), key2.convert());
472            for hasher in [
473                AHasher::new_with_keys(key1, key2),
474                AHasher::test_with_keys(key1, key2),
475                AHasher::from_random_state(&RandomState { k0, k1, k2, k3 }),
476            ] {
477                assert_eq!([1, 1], [hasher.increments[0] & 1, hasher.increments[1] & 1]);
478            }
479        }
480    }
481
482    // The 64 bit function is too large to measure how often two different blocks collide. But the weaknesses
483    // of `hash_in` come from the arithmetic, and exist at every word size. So the tests below use a
484    // model of it with small words, where every key can be tried. (All of the rotations scale with the
485    // word size.) Rates are given as a multiple of `2^-width`, which is the chance that any two inputs collide in
486    // the one word `finish` returns.
487    //
488    // This is the bar even where the state compared is two words: A product of two words does not do better than
489    // one word. If an operand is zero (one key in `2^width`) any difference in the other has no effect, and if the
490    // operands are swapped the product is the same. So two words of state collide at about `2^-width` for some
491    // differences however the halves are combined, which adds at most as much as the output's own rate.
492
493    /// What two blocks are compared by: Equal results are a collision.
494    type Outcome = fn([u64; 2], u32) -> u64;
495
496    fn mask(width: u32) -> u64 {
497        u64::MAX >> (64 - width)
498    }
499
500    /// `ROT` scaled to the word size.
501    fn scaled_rot(width: u32) -> u32 {
502        (ROT * width + 32) / 64
503    }
504
505    fn rotate(value: u64, width: u32) -> u64 {
506        let rot = scaled_rot(width);
507        ((value << rot) | (value >> (width - rot))) & mask(width)
508    }
509
510    /// The model of `multiply_halves`.
511    fn product_halves(x: u64, y: u64, width: u32) -> [u64; 2] {
512        let product = (x as u128) * (y as u128);
513        [product as u64 & mask(width), (product >> width) as u64 & mask(width)]
514    }
515
516    /// The model of `AHasher::combine`.
517    fn combine([added, xored]: [u64; 2], [x, y]: [u64; 2], width: u32) -> [u64; 2] {
518        let [low, high] = product_halves(x, y, width);
519        [xored.wrapping_add(high) & mask(width), rotate(added, width) ^ low]
520    }
521
522    /// The model of `AHasherStr` for short strings, which xors the halves together.
523    fn fold([low, high]: [u64; 2], _width: u32) -> u64 {
524        low ^ high
525    }
526
527    #[test]
528    fn test_hash_in_matches_model() {
529        for (data, key1, key2) in [
530            (0_u128, 0_u128, 0_u128),
531            (1, 2, 3),
532            (u128::MAX, 1 << 80, 7),
533            (0x0123_4567_89ab_cdef_0011_2233_4455_6677, 99, 12345),
534            (0xfedc_ba98_7654_3210_8899_aabb_ccdd_eeff, u128::MAX / 3, u128::MAX / 5),
535        ] {
536            let mut hasher = AHasher::test_with_keys(key1, key2);
537            // Two blocks, so that the second one meets keys which have moved on.
538            for _ in 0..2 {
539                let block: [u64; 2] = data.convert();
540                let (keys, increments) = (hasher.keys, hasher.increments);
541                let expected = combine(hasher.buffer, [block[0] ^ keys[0], block[1] ^ keys[1]], 64);
542                hasher.hash_in(data);
543                assert_eq!(expected, hasher.buffer);
544                assert_eq!(
545                    [keys[0].wrapping_add(increments[0]), keys[1].wrapping_add(increments[1])],
546                    hasher.keys
547                );
548            }
549        }
550    }
551
552    /// `write` adds the length and then does `hash_in` for each block of the input: Up to 16 bytes are one
553    /// block, and up to 32 the first 16 and the last 16. Longer inputs are the last 32 bytes, and then each 32 from
554    /// the start while more than 32 remain. (Each number of blocks has code of its own.)
555    #[test]
556    fn test_write_is_hash_in_for_each_block() {
557        let data: Vec<u8> = (0..150_u32).map(|i| (i * 37 + 11) as u8).collect();
558        for length in 0..=data.len() {
559            let data = &data[..length];
560            let mut written = AHasher::test_with_keys(length as u128, 99);
561            let mut expected = written.clone();
562            written.write(data);
563            expected.buffer[0] = expected.buffer[0].wrapping_add(length as u64).wrapping_mul(MULTIPLE);
564            let mut blocks: Vec<u128> = Vec::new();
565            if length <= 8 {
566                blocks.push(read_small(data).convert());
567            } else if length <= 16 {
568                blocks.push([data.read_u64().0, data.read_last_u64()].convert());
569            } else if length <= 32 {
570                blocks.extend([data.read_u128().0, data.read_last_u128()]);
571            } else {
572                blocks.extend(data.read_last_u128x2());
573                let mut rest = data;
574                while rest.len() > 32 {
575                    let (pair, after) = rest.read_u128x2();
576                    blocks.extend(pair);
577                    rest = after;
578                }
579            }
580            for block in blocks {
581                expected.hash_in(block);
582            }
583            assert_eq!(
584                (expected.buffer, expected.keys),
585                (written.buffer, written.keys),
586                "{}",
587                length
588            );
589        }
590    }
591
592    /// Where there is no 128 bit multiply the product is put together from four smaller ones. It has to be the
593    /// same product, as the models assume it is.
594    #[test]
595    fn test_multiply_halves_by_32s_is_the_product() {
596        use crate::operations::multiply_halves_by_32s;
597        let mut seed = 1;
598        let mut operands = vec![
599            (0_u64, 0_u64),
600            (3, 5),
601            (u64::MAX, u64::MAX),
602            (u64::MAX, 1 << 32),
603            (0xffff_ffff, 0xffff_ffff),
604            (0xffff_ffff_0000_0001, 0x0000_0001_ffff_ffff),
605        ];
606        operands.extend((0..10_000).map(|_| (random(&mut seed), random(&mut seed))));
607        for (x, y) in operands {
608            assert_eq!(
609                multiply_halves_by_32s(x, y),
610                product_halves(x, y, 64),
611                "{:x} {:x}",
612                x,
613                y
614            );
615        }
616    }
617
618    /// For every possible difference between two blocks: How often they have the same `outcome`, which may have
619    /// up to twice the width (but is held to the same rate, see above). The difference `(da, db)` is at index
620    /// `da << width | db`.
621    /// (The keys are xored with the input before it is used. So trying every pair of operands is trying every key.)
622    fn difference_profile(outcome: Outcome, width: u32) -> Vec<f64> {
623        let size = 1_usize << width;
624        let mut counts = vec![0_u32; size * size];
625        let mut states: Vec<Vec<u32>> = vec![Vec::new(); size * size];
626        for x in 0..size as u64 {
627            for y in 0..size as u64 {
628                let state = outcome(product_halves(x, y, width), width);
629                states[state as usize].push((x << width | y) as u32);
630            }
631        }
632        // Any two operand pairs which lead to the same state are a collision for the difference between them.
633        for state in states.iter() {
634            for (i, a) in state.iter().enumerate() {
635                for b in &state[i + 1..] {
636                    counts[(a ^ b) as usize] += 1;
637                }
638            }
639        }
640        let ideal = size as f64 / 2.0;
641        counts.into_iter().map(|count| count as f64 / ideal).collect()
642    }
643
644    /// The same for a single difference, which is feasible for larger words.
645    fn collision_rate(outcome: Outcome, width: u32, da: u64, db: u64) -> f64 {
646        let size = 1_u64 << width;
647        let mut collisions = 0_u64;
648        for x in 0..size {
649            for y in 0..size {
650                let a = outcome(product_halves(x, y, width), width);
651                let b = outcome(product_halves(x ^ da, y ^ db, width), width);
652                collisions += (a == b) as u64;
653            }
654        }
655        collisions as f64 / size as f64
656    }
657
658    fn worst(profile: &[f64], width: u32, include: impl Fn(u64, u64) -> bool) -> (f64, u64, u64) {
659        let mut worst = (0.0, 0, 0);
660        for (index, &rate) in profile.iter().enumerate().skip(1) {
661            let (da, db) = (index as u64 >> width, index as u64 & mask(width));
662            if rate > worst.0 && include(da, db) {
663                worst = (rate, da, db);
664            }
665        }
666        worst
667    }
668
669    /// `combine` puts each half of the product in a word of its own, and what it does to each can be undone. So two
670    /// blocks leave the buffer in the same state exactly when both halves are the same.
671    fn both_halves([low, high]: [u64; 2], width: u32) -> u64 {
672        high << width | low
673    }
674
675    /// Checks every possible difference between two blocks, so that no pattern (like the complement in issue #292,
676    /// which collided 2^38 times more often than ideal at 64 bits) can stand out.
677    /// (The worst measured is 1.6 times ideal.)
678    #[test]
679    fn test_no_block_difference_collides_often() {
680        let width = 8;
681        let profile = difference_profile(both_halves, width);
682        let (rate, da, db) = worst(&profile, width, |_, _| true);
683        assert!(
684            rate < 3.0,
685            "A difference of {:x?} collides {} times more often than ideal",
686            (da, db),
687            rate
688        );
689    }
690
691    /// `AHasherStr` xors the halves of a product of two operands which both depend on the input, for strings of
692    /// up to 8 bytes. But there the input only reaches the low half of each operand. Check that no difference
693    /// which is confined to the low halves stands out, or grows with the word size the way the complement did.
694    #[test]
695    fn test_short_string_differences_do_not_scale() {
696        let width = 8;
697        let half = mask(width / 2);
698        let profile = difference_profile(fold, width);
699        let (rate, da, db) = worst(&profile, width, |da, db| da <= half && db <= half);
700        assert!(rate < 6.0, "{:x?} {}", (da, db), rate);
701        let width = 12;
702        let half = mask(width / 2);
703        for (da, db) in [(half, half), (half, 0), (0, half)] {
704            let rate = collision_rate(fold, width, da, db);
705            assert!(rate < 6.0, "{:x?} {}", (da, db), rate);
706        }
707    }
708
709    /// splitmix64.
710    fn random(state: &mut u64) -> u64 {
711        *state = state.wrapping_add(0x9e37_79b9_7f4a_7c15);
712        let z = (*state ^ (*state >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
713        let z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
714        z ^ (z >> 31)
715    }
716
717    /// How often two inputs of `between + 2` blocks leave the model of the buffer in the same state, when every
718    /// block has the same second word, and the first word of the first block differs in bit `first` and that of
719    /// the last block in bit `last`. With `stepped` the keys change after each block, as they do in `hash_in`.
720    fn shared_word_rate(width: u32, between: usize, first: u32, last: u32, stepped: bool) -> f64 {
721        let samples = 1_u64 << (width + 5);
722        let mut seed = (first as u64) << 32 | (last as u64) << 16 | between as u64;
723        let mut next = || random(&mut seed) & mask(width);
724        let mut collisions = 0;
725        for _ in 0..samples {
726            let start = [next(), next()];
727            let (mut keys, shared) = ([next(), next()], next());
728            let increments = if stepped { [next() | 1, next() | 1] } else { [0, 0] };
729            let mut buffers = [start, start];
730            for block in 0..between + 2 {
731                let word = next();
732                let flipped = match block {
733                    0 => word ^ 1 << first,
734                    b if b == between + 1 => word ^ 1 << last,
735                    _ => word,
736                };
737                for (buffer, word) in buffers.iter_mut().zip([word, flipped]) {
738                    *buffer = combine(*buffer, [word ^ keys[0], shared ^ keys[1]], width);
739                }
740                keys = [
741                    keys[0].wrapping_add(increments[0]) & mask(width),
742                    keys[1].wrapping_add(increments[1]) & mask(width),
743                ];
744            }
745            collisions += (buffers[0] == buffers[1]) as u64;
746        }
747        collisions as f64 / samples as f64 * (1_u64 << width) as f64
748    }
749
750    /// The worst of `shared_word_rate` over every pair of bits.
751    fn worst_shared_word_rate(width: u32, between: usize, stepped: bool) -> (f64, u32, u32) {
752        let mut worst = (0.0, 0, 0);
753        for first in 0..width {
754            for last in 0..width {
755                let rate = shared_word_rate(width, between, first, last, stepped);
756                if rate > worst.0 {
757                    worst = (rate, first, last);
758                }
759            }
760        }
761        worst
762    }
763
764    /// Blocks with a word in common would give a multiply the same operand, if the keys stayed the same. When
765    /// that operand ends in zeros, a later block can remove the difference an earlier one made, and with the
766    /// product this gets more likely as the words get longer. Check that it does not happen with keys which
767    /// change, and that this test would notice if it did.
768    /// (With keys which change the worst measured is 0.6 times ideal. With the same keys for every block it is
769    /// at 8 and 16 times ideal for 8 and 12 bit words.)
770    #[test]
771    fn test_blocks_which_share_a_word_do_not_cancel() {
772        for width in [8, 12] {
773            for between in [0, 1] {
774                let (rate, first, last) = worst_shared_word_rate(width, between, true);
775                assert!(
776                    rate < 2.0,
777                    "At {} bits a difference in bit {} and then, {} blocks later, bit {} collides {} times more often than ideal",
778                    width,
779                    first,
780                    between + 1,
781                    last,
782                    rate
783                );
784            }
785        }
786        let (rate, _, _) = worst_shared_word_rate(12, 1, false);
787        assert!(
788            rate > 8.0,
789            "With the same keys for every block the rate was only {}",
790            rate
791        );
792    }
793
794    /// The same on the real function, for the likeliest case which is known: Three blocks, of which the first
795    /// differs in bit 63 of its first word and the last in bit 24. This needs a key which makes the operand they
796    /// have in common end in around 32 zeros, so the keys here are chosen to. Of those, about one in 700 collides
797    /// if the keys stay the same (which comes to one key in `2^41.5` over all), and none should if they change.
798    #[test]
799    fn test_blocks_which_share_a_word_at_full_width() {
800        let samples = 1_u64 << 18;
801        for stepped in [false, true] {
802            let mut seed = 1;
803            let mut collisions = 0;
804            for _ in 0..samples {
805                let key1 = (random(&mut seed) as u128) << 64 | random(&mut seed) as u128;
806                let key2 = (random(&mut seed) as u128) << 64 | random(&mut seed) as u128;
807                let mut hasher = AHasher::test_with_keys(key1, key2);
808                if !stepped {
809                    hasher.increments = [0, 0];
810                }
811                let shared = hasher.keys[1] ^ random(&mut seed) << 32;
812                let mut hashers = [hasher.clone(), hasher];
813                for flip in [1 << 63, 0, 1 << 24] {
814                    let word = random(&mut seed);
815                    hashers[0].hash_in([word, shared].convert());
816                    hashers[1].hash_in([word ^ flip, shared].convert());
817                }
818                collisions += (hashers[0].buffer == hashers[1].buffer) as u64;
819            }
820            if stepped {
821                assert_eq!(0, collisions);
822            } else {
823                assert!(
824                    collisions > 100,
825                    "With the same keys for every block there were only {}",
826                    collisions
827                );
828            }
829        }
830    }
831}