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