Make hash_combine accept a configurable hash function
[folly.git] / folly / Hash.h
1 /*
2  * Copyright 2013 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #ifndef FOLLY_BASE_HASH_H_
18 #define FOLLY_BASE_HASH_H_
19
20 #include <cstring>
21 #include <stdint.h>
22 #include <string>
23 #include <utility>
24
25 #include "folly/SpookyHashV1.h"
26 #include "folly/SpookyHashV2.h"
27
28 /*
29  * Various hashing functions.
30  */
31
32 namespace folly { namespace hash {
33
34 // This is a general-purpose way to create a single hash from multiple
35 // hashable objects. hash_combine_generic takes a class Hasher implementing
36 // hash<T>; hash_combine uses a default hasher StdHasher that uses std::hash.
37 // hash_combine_generic hashes each argument and combines those hashes in
38 // an order-dependent way to yield a new hash.
39
40
41 // This is the Hash128to64 function from Google's cityhash (available
42 // under the MIT License).  We use it to reduce multiple 64 bit hashes
43 // into a single hash.
44 inline size_t hash_128_to_64(const size_t upper, const size_t lower) {
45   // Murmur-inspired hashing.
46   const size_t kMul = 0x9ddfea08eb382d69ULL;
47   size_t a = (lower ^ upper) * kMul;
48   a ^= (a >> 47);
49   size_t b = (upper ^ a) * kMul;
50   b ^= (b >> 47);
51   b *= kMul;
52   return b;
53 }
54
55 // Never used, but gcc demands it.
56 template <class Hasher>
57 inline size_t hash_combine_generic() {
58   return 0;
59 }
60
61 template <class Hasher, typename T, typename... Ts>
62 size_t hash_combine_generic(const T& t, const Ts&... ts) {
63   size_t seed = Hasher::hash(t);
64   if (sizeof...(ts) == 0) {
65     return seed;
66   }
67   size_t remainder = hash_combine_generic<Hasher>(ts...);
68   return hash_128_to_64(seed, remainder);
69 }
70
71 // Simply uses std::hash to hash.  Note that std::hash is not guaranteed
72 // to be a very good hash function; provided std::hash doesn't collide on
73 // the individual inputs, you are fine, but that won't be true for, say,
74 // strings or pairs
75 class StdHasher {
76  public:
77   template <typename T>
78   static size_t hash(const T& t) {
79     return std::hash<T>()(t);
80   }
81 };
82
83 template <typename T, typename... Ts>
84 size_t hash_combine(const T& t, const Ts&... ts) {
85   return hash_combine_generic<StdHasher>(t, ts...);
86 }
87
88 //////////////////////////////////////////////////////////////////////
89
90 /*
91  * Thomas Wang 64 bit mix hash function
92  */
93
94 inline uint64_t twang_mix64(uint64_t key) {
95   key = (~key) + (key << 21);  // key *= (1 << 21) - 1; key -= 1;
96   key = key ^ (key >> 24);
97   key = key + (key << 3) + (key << 8);  // key *= 1 + (1 << 3) + (1 << 8)
98   key = key ^ (key >> 14);
99   key = key + (key << 2) + (key << 4);  // key *= 1 + (1 << 2) + (1 << 4)
100   key = key ^ (key >> 28);
101   key = key + (key << 31);  // key *= 1 + (1 << 31)
102   return key;
103 }
104
105 /*
106  * Inverse of twang_mix64
107  *
108  * Note that twang_unmix64 is significantly slower than twang_mix64.
109  */
110
111 inline uint64_t twang_unmix64(uint64_t key) {
112   // See the comments in jenkins_rev_unmix32 for an explanation as to how this
113   // was generated
114   key *= 4611686016279904257U;
115   key ^= (key >> 28) ^ (key >> 56);
116   key *= 14933078535860113213U;
117   key ^= (key >> 14) ^ (key >> 28) ^ (key >> 42) ^ (key >> 56);
118   key *= 15244667743933553977U;
119   key ^= (key >> 24) ^ (key >> 48);
120   key = (key + 1) * 9223367638806167551U;
121   return key;
122 }
123
124 /*
125  * Thomas Wang downscaling hash function
126  */
127
128 inline uint32_t twang_32from64(uint64_t key) {
129   key = (~key) + (key << 18);
130   key = key ^ (key >> 31);
131   key = key * 21;
132   key = key ^ (key >> 11);
133   key = key + (key << 6);
134   key = key ^ (key >> 22);
135   return (uint32_t) key;
136 }
137
138 /*
139  * Robert Jenkins' reversible 32 bit mix hash function
140  */
141
142 inline uint32_t jenkins_rev_mix32(uint32_t key) {
143   key += (key << 12);  // key *= (1 + (1 << 12))
144   key ^= (key >> 22);
145   key += (key << 4);   // key *= (1 + (1 << 4))
146   key ^= (key >> 9);
147   key += (key << 10);  // key *= (1 + (1 << 10))
148   key ^= (key >> 2);
149   // key *= (1 + (1 << 7)) * (1 + (1 << 12))
150   key += (key << 7);
151   key += (key << 12);
152   return key;
153 }
154
155 /*
156  * Inverse of jenkins_rev_mix32
157  *
158  * Note that jenkinks_rev_unmix32 is significantly slower than
159  * jenkins_rev_mix32.
160  */
161
162 inline uint32_t jenkins_rev_unmix32(uint32_t key) {
163   // These are the modular multiplicative inverses (in Z_2^32) of the
164   // multiplication factors in jenkins_rev_mix32, in reverse order.  They were
165   // computed using the Extended Euclidean algorithm, see
166   // http://en.wikipedia.org/wiki/Modular_multiplicative_inverse
167   key *= 2364026753U;
168
169   // The inverse of a ^= (a >> n) is
170   // b = a
171   // for (int i = n; i < 32; i += n) {
172   //   b ^= (a >> i);
173   // }
174   key ^=
175     (key >> 2) ^ (key >> 4) ^ (key >> 6) ^ (key >> 8) ^
176     (key >> 10) ^ (key >> 12) ^ (key >> 14) ^ (key >> 16) ^
177     (key >> 18) ^ (key >> 20) ^ (key >> 22) ^ (key >> 24) ^
178     (key >> 26) ^ (key >> 28) ^ (key >> 30);
179   key *= 3222273025U;
180   key ^= (key >> 9) ^ (key >> 18) ^ (key >> 27);
181   key *= 4042322161U;
182   key ^= (key >> 22);
183   key *= 16773121U;
184   return key;
185 }
186
187 /*
188  * Fowler / Noll / Vo (FNV) Hash
189  *     http://www.isthe.com/chongo/tech/comp/fnv/
190  */
191
192 const uint32_t FNV_32_HASH_START = 216613626UL;
193 const uint64_t FNV_64_HASH_START = 14695981039346656037ULL;
194
195 inline uint32_t fnv32(const char* s,
196                       uint32_t hash = FNV_32_HASH_START) {
197   for (; *s; ++s) {
198     hash += (hash << 1) + (hash << 4) + (hash << 7) +
199             (hash << 8) + (hash << 24);
200     hash ^= *s;
201   }
202   return hash;
203 }
204
205 inline uint32_t fnv32_buf(const void* buf,
206                           int n,
207                           uint32_t hash = FNV_32_HASH_START) {
208   const char* char_buf = reinterpret_cast<const char*>(buf);
209
210   for (int i = 0; i < n; ++i) {
211     hash += (hash << 1) + (hash << 4) + (hash << 7) +
212             (hash << 8) + (hash << 24);
213     hash ^= char_buf[i];
214   }
215
216   return hash;
217 }
218
219 inline uint32_t fnv32(const std::string& str,
220                       uint64_t hash = FNV_32_HASH_START) {
221   return fnv32_buf(str.data(), str.size(), hash);
222 }
223
224 inline uint64_t fnv64(const char* s,
225                       uint64_t hash = FNV_64_HASH_START) {
226   for (; *s; ++s) {
227     hash += (hash << 1) + (hash << 4) + (hash << 5) + (hash << 7) +
228       (hash << 8) + (hash << 40);
229     hash ^= *s;
230   }
231   return hash;
232 }
233
234 inline uint64_t fnv64_buf(const void* buf,
235                           int n,
236                           uint64_t hash = FNV_64_HASH_START) {
237   const char* char_buf = reinterpret_cast<const char*>(buf);
238
239   for (int i = 0; i < n; ++i) {
240     hash += (hash << 1) + (hash << 4) + (hash << 5) + (hash << 7) +
241       (hash << 8) + (hash << 40);
242     hash ^= char_buf[i];
243   }
244   return hash;
245 }
246
247 inline uint64_t fnv64(const std::string& str,
248                       uint64_t hash = FNV_64_HASH_START) {
249   return fnv64_buf(str.data(), str.size(), hash);
250 }
251
252 /*
253  * Paul Hsieh: http://www.azillionmonkeys.com/qed/hash.html
254  */
255
256 #define get16bits(d) (*((const uint16_t*) (d)))
257
258 inline uint32_t hsieh_hash32_buf(const void* buf, int len) {
259   const char* s = reinterpret_cast<const char*>(buf);
260   uint32_t hash = len;
261   uint32_t tmp;
262   int rem;
263
264   if (len <= 0 || buf == 0) {
265     return 0;
266   }
267
268   rem = len & 3;
269   len >>= 2;
270
271   /* Main loop */
272   for (;len > 0; len--) {
273     hash  += get16bits (s);
274     tmp    = (get16bits (s+2) << 11) ^ hash;
275     hash   = (hash << 16) ^ tmp;
276     s  += 2*sizeof (uint16_t);
277     hash  += hash >> 11;
278   }
279
280   /* Handle end cases */
281   switch (rem) {
282   case 3:
283     hash += get16bits(s);
284     hash ^= hash << 16;
285     hash ^= s[sizeof (uint16_t)] << 18;
286     hash += hash >> 11;
287     break;
288   case 2:
289     hash += get16bits(s);
290     hash ^= hash << 11;
291     hash += hash >> 17;
292     break;
293   case 1:
294     hash += *s;
295     hash ^= hash << 10;
296     hash += hash >> 1;
297   }
298
299   /* Force "avalanching" of final 127 bits */
300   hash ^= hash << 3;
301   hash += hash >> 5;
302   hash ^= hash << 4;
303   hash += hash >> 17;
304   hash ^= hash << 25;
305   hash += hash >> 6;
306
307   return hash;
308 };
309
310 #undef get16bits
311
312 inline uint32_t hsieh_hash32(const char* s) {
313   return hsieh_hash32_buf(s, std::strlen(s));
314 }
315
316 inline uint32_t hsieh_hash32_str(const std::string& str) {
317   return hsieh_hash32_buf(str.data(), str.size());
318 }
319
320 //////////////////////////////////////////////////////////////////////
321
322 } // namespace hash
323
324 template<class Key>
325 struct hasher;
326
327 template<> struct hasher<int32_t> {
328   size_t operator()(int32_t key) const {
329     return hash::jenkins_rev_mix32(uint32_t(key));
330   }
331 };
332
333 template<> struct hasher<uint32_t> {
334   size_t operator()(uint32_t key) const {
335     return hash::jenkins_rev_mix32(key);
336   }
337 };
338
339 template<> struct hasher<int64_t> {
340   size_t operator()(int64_t key) const {
341     return hash::twang_mix64(uint64_t(key));
342   }
343 };
344
345 template<> struct hasher<uint64_t> {
346   size_t operator()(uint64_t key) const {
347     return hash::twang_mix64(key);
348   }
349 };
350
351 } // namespace folly
352
353 // Custom hash functions.
354 namespace std {
355   // Hash function for pairs. Requires default hash functions for both
356   // items in the pair.
357   template <typename T1, typename T2>
358   class hash<std::pair<T1, T2> > {
359   public:
360     size_t operator()(const std::pair<T1, T2>& x) const {
361       return folly::hash::hash_combine(x.first, x.second);
362     }
363   };
364 } // namespace std
365
366 #endif