1 /// Implementation of XXHash digester.
2 module tern.digest.xxhash;
3 
4 import tern.serialization;
5 import tern.digest;
6 
7 /**
8  * Implementation of XXHash digester.
9  *
10  * XXHash is an extremely fast non-cryptographic hash algorithm, which offers
11  * excellent distribution, especially for small keys and values. It is designed
12  * for speed and efficiency on both little-endian and big-endian machines.
13  *
14  * Example:
15  * ```d
16  * import tern.digest.xxhash;
17  * 
18  * ubyte[] data = [1, 2, 3, 4, 5];
19  * auto hashValue = XXHash.hash(data);
20  * ```
21  */
22 public static @digester class XXHash
23 {
24 public:
25 static:
26 pure:
27     /**
28      * Computes the XXHash digest of the given data.
29      *
30      * Params:
31      *  data = The input byte array for which the XXHash is to be computed.
32      *
33      * Returns:
34      *  A byte array representing the computed XXHash digest.
35      */
36     ubyte[] hash(ubyte[] data)
37     {
38         const ulong prime1 = 11_400_714_785_074_694_791;
39         const ulong prime2 = 14_029_467_366_897_019_727;
40         const ulong prime3 = 1_609_587_929_392_839_161;
41         const ulong prime4 = 9_650_029_242_287_828_579;
42         const ulong prime5 = 2_870_177_450_012_600_261;
43 
44         ulong hash = data.length * prime5;
45         foreach (b; data) 
46         {
47             hash += b * prime3;
48             hash = (hash << 31) | (hash >> 33);
49             hash *= prime2;
50         }
51         
52         hash = (~hash) + (data.length * prime1);
53         hash = (hash ^ (hash >> 27)) * prime1 + prime4;
54         hash = (hash ^ (hash >> 31)) * prime1;
55         return (hash ^ (hash >> 33)).serialize!true();
56     }
57 }