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