1 /// Implementation of CityHash digester.
2 module tern.digest.cityhash;
3
4 import tern.digest;
5 import tern.serialization;
6
7 /**
8 * Implementation of CityHash digester.
9 *
10 * CityHash is a family of hash functions developed by Google.
11 * It provides fast and strong hash functions for hash tables and checksums.
12 *
13 * Example:
14 * ```d
15 * import tern.digest.cityhash;
16 *
17 * ubyte[] data = [1, 2, 3, 4, 5];
18 * auto hashValue = CityHash.hash(data);
19 * ```
20 */
21 public static @digester class CityHash
22 {
23 public:
24 static:
25 pure:
26 /**
27 * Computes the CityHash digest of the given data.
28 *
29 * Params:
30 * data = The input byte array for which the CityHash digest is to be computed.
31 *
32 * Returns:
33 * A byte array representing the computed CityHash digest.
34 */
35 ubyte[] hash(ubyte[] data)
36 {
37 ulong seed = 0x9ae16a3b2f90404f;
38 ulong m = 0xc6a4a7935bd1e995;
39 ulong r = 47;
40 ulong h = seed + (data.length * m);
41
42 size_t i = 0;
43 foreach_reverse (j; 0..(data.length / 8))
44 {
45 ulong k = data[i..i+8].deserialize!ulong();
46 i += 8;
47 k *= m;
48 k ^= k >> r;
49 k *= m;
50 h ^= k;
51 h *= m;
52 }
53
54 if (data.length % 8 != 0)
55 {
56 ulong k = 0;
57 foreach (j; 0..(data.length % 8))
58 k |= (data[i + j] << (8 * j));
59
60 k *= m;
61 k ^= k >> r;
62 k *= m;
63 h ^= k;
64 }
65
66 h ^= h >> r;
67 h *= m;
68 h ^= h >> r;
69
70 return h.serialize!true();
71 }
72 }