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