WPILibC++  2019.3.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Modules Pages
Hashing.h
1 //===-- llvm/ADT/Hashing.h - Utilities for hashing --------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the newly proposed standard C++ interfaces for hashing
11 // arbitrary data and building hash functions for user-defined types. This
12 // interface was originally proposed in N3333[1] and is currently under review
13 // for inclusion in a future TR and/or standard.
14 //
15 // The primary interfaces provide are comprised of one type and three functions:
16 //
17 // -- 'hash_code' class is an opaque type representing the hash code for some
18 // data. It is the intended product of hashing, and can be used to implement
19 // hash tables, checksumming, and other common uses of hashes. It is not an
20 // integer type (although it can be converted to one) because it is risky
21 // to assume much about the internals of a hash_code. In particular, each
22 // execution of the program has a high probability of producing a different
23 // hash_code for a given input. Thus their values are not stable to save or
24 // persist, and should only be used during the execution for the
25 // construction of hashing datastructures.
26 //
27 // -- 'hash_value' is a function designed to be overloaded for each
28 // user-defined type which wishes to be used within a hashing context. It
29 // should be overloaded within the user-defined type's namespace and found
30 // via ADL. Overloads for primitive types are provided by this library.
31 //
32 // -- 'hash_combine' and 'hash_combine_range' are functions designed to aid
33 // programmers in easily and intuitively combining a set of data into
34 // a single hash_code for their object. They should only logically be used
35 // within the implementation of a 'hash_value' routine or similar context.
36 //
37 // Note that 'hash_combine_range' contains very special logic for hashing
38 // a contiguous array of integers or pointers. This logic is *extremely* fast,
39 // on a modern Intel "Gainestown" Xeon (Nehalem uarch) @2.2 GHz, these were
40 // benchmarked at over 6.5 GiB/s for large keys, and <20 cycles/hash for keys
41 // under 32-bytes.
42 //
43 //===----------------------------------------------------------------------===//
44 
45 #ifndef WPIUTIL_WPI_HASHING_H
46 #define WPIUTIL_WPI_HASHING_H
47 
48 #include "wpi/type_traits.h"
49 #include <algorithm>
50 #include <cassert>
51 #include <cstdint>
52 #include <cstring>
53 #include <string>
54 #include <utility>
55 
56 namespace wpi {
57 
70 class hash_code {
71  size_t value;
72 
73 public:
76  hash_code() = default;
77 
79  hash_code(size_t value) : value(value) {}
80 
82  /*explicit*/ operator size_t() const { return value; }
83 
84  friend bool operator==(const hash_code &lhs, const hash_code &rhs) {
85  return lhs.value == rhs.value;
86  }
87  friend bool operator!=(const hash_code &lhs, const hash_code &rhs) {
88  return lhs.value != rhs.value;
89  }
90 
92  friend size_t hash_value(const hash_code &code) { return code.value; }
93 };
94 
102 template <typename T>
103 typename std::enable_if<is_integral_or_enum<T>::value, hash_code>::type
104 hash_value(T value);
105 
109 template <typename T> hash_code hash_value(const T *ptr);
110 
112 template <typename T, typename U>
113 hash_code hash_value(const std::pair<T, U> &arg);
114 
116 template <typename T>
117 hash_code hash_value(const std::basic_string<T> &arg);
118 
119 
134 void set_fixed_execution_hash_seed(size_t fixed_value);
135 
136 
137 // All of the implementation details of actually computing the various hash
138 // code values are held within this namespace. These routines are included in
139 // the header file mainly to allow inlining and constant propagation.
140 namespace hashing {
141 namespace detail {
142 
143 inline uint64_t fetch64(const char *p) {
144  uint64_t result;
145  memcpy(&result, p, sizeof(result));
146  //if (sys::IsBigEndianHost)
147  // sys::swapByteOrder(result);
148  return result;
149 }
150 
151 inline uint32_t fetch32(const char *p) {
152  uint32_t result;
153  memcpy(&result, p, sizeof(result));
154  //if (sys::IsBigEndianHost)
155  // sys::swapByteOrder(result);
156  return result;
157 }
158 
160 static const uint64_t k0 = 0xc3a5c85c97cb3127ULL;
161 static const uint64_t k1 = 0xb492b66fbe98f273ULL;
162 static const uint64_t k2 = 0x9ae16a3b2f90404fULL;
163 static const uint64_t k3 = 0xc949d7c7509e6557ULL;
164 
168 inline uint64_t rotate(uint64_t val, size_t shift) {
169  // Avoid shifting by 64: doing so yields an undefined result.
170  return shift == 0 ? val : ((val >> shift) | (val << (64 - shift)));
171 }
172 
173 inline uint64_t shift_mix(uint64_t val) {
174  return val ^ (val >> 47);
175 }
176 
177 inline uint64_t hash_16_bytes(uint64_t low, uint64_t high) {
178  // Murmur-inspired hashing.
179  const uint64_t kMul = 0x9ddfea08eb382d69ULL;
180  uint64_t a = (low ^ high) * kMul;
181  a ^= (a >> 47);
182  uint64_t b = (high ^ a) * kMul;
183  b ^= (b >> 47);
184  b *= kMul;
185  return b;
186 }
187 
188 inline uint64_t hash_1to3_bytes(const char *s, size_t len, uint64_t seed) {
189  uint8_t a = s[0];
190  uint8_t b = s[len >> 1];
191  uint8_t c = s[len - 1];
192  uint32_t y = static_cast<uint32_t>(a) + (static_cast<uint32_t>(b) << 8);
193  uint32_t z = len + (static_cast<uint32_t>(c) << 2);
194  return shift_mix(y * k2 ^ z * k3 ^ seed) * k2;
195 }
196 
197 inline uint64_t hash_4to8_bytes(const char *s, size_t len, uint64_t seed) {
198  uint64_t a = fetch32(s);
199  return hash_16_bytes(len + (a << 3), seed ^ fetch32(s + len - 4));
200 }
201 
202 inline uint64_t hash_9to16_bytes(const char *s, size_t len, uint64_t seed) {
203  uint64_t a = fetch64(s);
204  uint64_t b = fetch64(s + len - 8);
205  return hash_16_bytes(seed ^ a, rotate(b + len, len)) ^ b;
206 }
207 
208 inline uint64_t hash_17to32_bytes(const char *s, size_t len, uint64_t seed) {
209  uint64_t a = fetch64(s) * k1;
210  uint64_t b = fetch64(s + 8);
211  uint64_t c = fetch64(s + len - 8) * k2;
212  uint64_t d = fetch64(s + len - 16) * k0;
213  return hash_16_bytes(rotate(a - b, 43) + rotate(c ^ seed, 30) + d,
214  a + rotate(b ^ k3, 20) - c + len + seed);
215 }
216 
217 inline uint64_t hash_33to64_bytes(const char *s, size_t len, uint64_t seed) {
218  uint64_t z = fetch64(s + 24);
219  uint64_t a = fetch64(s) + (len + fetch64(s + len - 16)) * k0;
220  uint64_t b = rotate(a + z, 52);
221  uint64_t c = rotate(a, 37);
222  a += fetch64(s + 8);
223  c += rotate(a, 7);
224  a += fetch64(s + 16);
225  uint64_t vf = a + z;
226  uint64_t vs = b + rotate(a, 31) + c;
227  a = fetch64(s + 16) + fetch64(s + len - 32);
228  z = fetch64(s + len - 8);
229  b = rotate(a + z, 52);
230  c = rotate(a, 37);
231  a += fetch64(s + len - 24);
232  c += rotate(a, 7);
233  a += fetch64(s + len - 16);
234  uint64_t wf = a + z;
235  uint64_t ws = b + rotate(a, 31) + c;
236  uint64_t r = shift_mix((vf + ws) * k2 + (wf + vs) * k0);
237  return shift_mix((seed ^ (r * k0)) + vs) * k2;
238 }
239 
240 inline uint64_t hash_short(const char *s, size_t length, uint64_t seed) {
241  if (length >= 4 && length <= 8)
242  return hash_4to8_bytes(s, length, seed);
243  if (length > 8 && length <= 16)
244  return hash_9to16_bytes(s, length, seed);
245  if (length > 16 && length <= 32)
246  return hash_17to32_bytes(s, length, seed);
247  if (length > 32)
248  return hash_33to64_bytes(s, length, seed);
249  if (length != 0)
250  return hash_1to3_bytes(s, length, seed);
251 
252  return k2 ^ seed;
253 }
254 
258 struct hash_state {
259  uint64_t h0, h1, h2, h3, h4, h5, h6;
260 
264  static hash_state create(const char *s, uint64_t seed) {
265  hash_state state = {
266  0, seed, hash_16_bytes(seed, k1), rotate(seed ^ k1, 49),
267  seed * k1, shift_mix(seed), 0 };
268  state.h6 = hash_16_bytes(state.h4, state.h5);
269  state.mix(s);
270  return state;
271  }
272 
275  static void mix_32_bytes(const char *s, uint64_t &a, uint64_t &b) {
276  a += fetch64(s);
277  uint64_t c = fetch64(s + 24);
278  b = rotate(b + a + c, 21);
279  uint64_t d = a;
280  a += fetch64(s + 8) + fetch64(s + 16);
281  b += rotate(a, 44) + d;
282  a += c;
283  }
284 
288  void mix(const char *s) {
289  h0 = rotate(h0 + h1 + h3 + fetch64(s + 8), 37) * k1;
290  h1 = rotate(h1 + h4 + fetch64(s + 48), 42) * k1;
291  h0 ^= h6;
292  h1 += h3 + fetch64(s + 40);
293  h2 = rotate(h2 + h5, 33) * k1;
294  h3 = h4 * k1;
295  h4 = h0 + h5;
296  mix_32_bytes(s, h3, h4);
297  h5 = h2 + h6;
298  h6 = h1 + fetch64(s + 16);
299  mix_32_bytes(s + 32, h5, h6);
300  std::swap(h2, h0);
301  }
302 
305  uint64_t finalize(size_t length) {
306  return hash_16_bytes(hash_16_bytes(h3, h5) + shift_mix(h1) * k1 + h2,
307  hash_16_bytes(h4, h6) + shift_mix(length) * k1 + h0);
308  }
309 };
310 
311 
317 extern size_t fixed_seed_override;
318 
319 inline size_t get_execution_seed() {
320  // FIXME: This needs to be a per-execution seed. This is just a placeholder
321  // implementation. Switching to a per-execution seed is likely to flush out
322  // instability bugs and so will happen as its own commit.
323  //
324  // However, if there is a fixed seed override set the first time this is
325  // called, return that instead of the per-execution seed.
326  const uint64_t seed_prime = 0xff51afd7ed558ccdULL;
327  static size_t seed = fixed_seed_override ? fixed_seed_override
328  : (size_t)seed_prime;
329  return seed;
330 }
331 
332 
338 //
339 // FIXME: We want to replace is_integral_or_enum and is_pointer here with
340 // a predicate which asserts that comparing the underlying storage of two
341 // values of the type for equality is equivalent to comparing the two values
342 // for equality. For all the platforms we care about, this holds for integers
343 // and pointers, but there are platforms where it doesn't and we would like to
344 // support user-defined types which happen to satisfy this property.
345 template <typename T> struct is_hashable_data
346  : std::integral_constant<bool, ((is_integral_or_enum<T>::value ||
347  std::is_pointer<T>::value) &&
348  64 % sizeof(T) == 0)> {};
349 
350 // Special case std::pair to detect when both types are viable and when there
351 // is no alignment-derived padding in the pair. This is a bit of a lie because
352 // std::pair isn't truly POD, but it's close enough in all reasonable
353 // implementations for our use case of hashing the underlying data.
354 template <typename T, typename U> struct is_hashable_data<std::pair<T, U> >
355  : std::integral_constant<bool, (is_hashable_data<T>::value &&
356  is_hashable_data<U>::value &&
357  (sizeof(T) + sizeof(U)) ==
358  sizeof(std::pair<T, U>))> {};
359 
362 template <typename T>
363 typename std::enable_if<is_hashable_data<T>::value, T>::type
364 get_hashable_data(const T &value) {
365  return value;
366 }
370 template <typename T>
371 typename std::enable_if<!is_hashable_data<T>::value, size_t>::type
372 get_hashable_data(const T &value) {
373  using ::wpi::hash_value;
374  return hash_value(value);
375 }
376 
384 template <typename T>
385 bool store_and_advance(char *&buffer_ptr, char *buffer_end, const T& value,
386  size_t offset = 0) {
387  size_t store_size = sizeof(value) - offset;
388  if (buffer_ptr + store_size > buffer_end)
389  return false;
390  const char *value_data = reinterpret_cast<const char *>(&value);
391  memcpy(buffer_ptr, value_data + offset, store_size);
392  buffer_ptr += store_size;
393  return true;
394 }
395 
401 template <typename InputIteratorT>
402 hash_code hash_combine_range_impl(InputIteratorT first, InputIteratorT last) {
403  const size_t seed = get_execution_seed();
404  char buffer[64], *buffer_ptr = buffer;
405  char *const buffer_end = std::end(buffer);
406  while (first != last && store_and_advance(buffer_ptr, buffer_end,
407  get_hashable_data(*first)))
408  ++first;
409  if (first == last)
410  return hash_short(buffer, buffer_ptr - buffer, seed);
411  assert(buffer_ptr == buffer_end);
412 
413  hash_state state = state.create(buffer, seed);
414  size_t length = 64;
415  while (first != last) {
416  // Fill up the buffer. We don't clear it, which re-mixes the last round
417  // when only a partial 64-byte chunk is left.
418  buffer_ptr = buffer;
419  while (first != last && store_and_advance(buffer_ptr, buffer_end,
420  get_hashable_data(*first)))
421  ++first;
422 
423  // Rotate the buffer if we did a partial fill in order to simulate doing
424  // a mix of the last 64-bytes. That is how the algorithm works when we
425  // have a contiguous byte sequence, and we want to emulate that here.
426  std::rotate(buffer, buffer_ptr, buffer_end);
427 
428  // Mix this chunk into the current state.
429  state.mix(buffer);
430  length += buffer_ptr - buffer;
431  };
432 
433  return state.finalize(length);
434 }
435 
444 template <typename ValueT>
445 typename std::enable_if<is_hashable_data<ValueT>::value, hash_code>::type
446 hash_combine_range_impl(ValueT *first, ValueT *last) {
447  const size_t seed = get_execution_seed();
448  const char *s_begin = reinterpret_cast<const char *>(first);
449  const char *s_end = reinterpret_cast<const char *>(last);
450  const size_t length = std::distance(s_begin, s_end);
451  if (length <= 64)
452  return hash_short(s_begin, length, seed);
453 
454  const char *s_aligned_end = s_begin + (length & ~63);
455  hash_state state = state.create(s_begin, seed);
456  s_begin += 64;
457  while (s_begin != s_aligned_end) {
458  state.mix(s_begin);
459  s_begin += 64;
460  }
461  if (length & 63)
462  state.mix(s_end - 64);
463 
464  return state.finalize(length);
465 }
466 
467 } // namespace detail
468 } // namespace hashing
469 
470 
477 template <typename InputIteratorT>
478 hash_code hash_combine_range(InputIteratorT first, InputIteratorT last) {
479  return ::wpi::hashing::detail::hash_combine_range_impl(first, last);
480 }
481 
482 
483 // Implementation details for hash_combine.
484 namespace hashing {
485 namespace detail {
486 
495  char buffer[64];
496  hash_state state;
497  const size_t seed;
498 
499 public:
505  : seed(get_execution_seed()) {}
506 
513  template <typename T>
514  char *combine_data(size_t &length, char *buffer_ptr, char *buffer_end, T data) {
515  if (!store_and_advance(buffer_ptr, buffer_end, data)) {
516  // Check for skew which prevents the buffer from being packed, and do
517  // a partial store into the buffer to fill it. This is only a concern
518  // with the variadic combine because that formation can have varying
519  // argument types.
520  size_t partial_store_size = buffer_end - buffer_ptr;
521  memcpy(buffer_ptr, &data, partial_store_size);
522 
523  // If the store fails, our buffer is full and ready to hash. We have to
524  // either initialize the hash state (on the first full buffer) or mix
525  // this buffer into the existing hash state. Length tracks the *hashed*
526  // length, not the buffered length.
527  if (length == 0) {
528  state = state.create(buffer, seed);
529  length = 64;
530  } else {
531  // Mix this chunk into the current state and bump length up by 64.
532  state.mix(buffer);
533  length += 64;
534  }
535  // Reset the buffer_ptr to the head of the buffer for the next chunk of
536  // data.
537  buffer_ptr = buffer;
538 
539  // Try again to store into the buffer -- this cannot fail as we only
540  // store types smaller than the buffer.
541  if (!store_and_advance(buffer_ptr, buffer_end, data,
542  partial_store_size))
543  abort();
544  }
545  return buffer_ptr;
546  }
547 
552  template <typename T, typename ...Ts>
553  hash_code combine(size_t length, char *buffer_ptr, char *buffer_end,
554  const T &arg, const Ts &...args) {
555  buffer_ptr = combine_data(length, buffer_ptr, buffer_end, get_hashable_data(arg));
556 
557  // Recurse to the next argument.
558  return combine(length, buffer_ptr, buffer_end, args...);
559  }
560 
566  hash_code combine(size_t length, char *buffer_ptr, char *buffer_end) {
567  // Check whether the entire set of values fit in the buffer. If so, we'll
568  // use the optimized short hashing routine and skip state entirely.
569  if (length == 0)
570  return hash_short(buffer, buffer_ptr - buffer, seed);
571 
572  // Mix the final buffer, rotating it if we did a partial fill in order to
573  // simulate doing a mix of the last 64-bytes. That is how the algorithm
574  // works when we have a contiguous byte sequence, and we want to emulate
575  // that here.
576  std::rotate(buffer, buffer_ptr, buffer_end);
577 
578  // Mix this chunk into the current state.
579  state.mix(buffer);
580  length += buffer_ptr - buffer;
581 
582  return state.finalize(length);
583  }
584 };
585 
586 } // namespace detail
587 } // namespace hashing
588 
600 template <typename ...Ts> hash_code hash_combine(const Ts &...args) {
601  // Recursively hash each argument using a helper class.
603  return helper.combine(0, helper.buffer, helper.buffer + 64, args...);
604 }
605 
606 // Implementation details for implementations of hash_value overloads provided
607 // here.
608 namespace hashing {
609 namespace detail {
610 
616 inline hash_code hash_integer_value(uint64_t value) {
617  // Similar to hash_4to8_bytes but using a seed instead of length.
618  const uint64_t seed = get_execution_seed();
619  const char *s = reinterpret_cast<const char *>(&value);
620  const uint64_t a = fetch32(s);
621  return hash_16_bytes(seed + (a << 3), fetch32(s + 4));
622 }
623 
624 } // namespace detail
625 } // namespace hashing
626 
627 // Declared and documented above, but defined here so that any of the hashing
628 // infrastructure is available.
629 template <typename T>
630 typename std::enable_if<is_integral_or_enum<T>::value, hash_code>::type
631 hash_value(T value) {
632  return ::wpi::hashing::detail::hash_integer_value(
633  static_cast<uint64_t>(value));
634 }
635 
636 // Declared and documented above, but defined here so that any of the hashing
637 // infrastructure is available.
638 template <typename T> hash_code hash_value(const T *ptr) {
639  return ::wpi::hashing::detail::hash_integer_value(
640  reinterpret_cast<uintptr_t>(ptr));
641 }
642 
643 // Declared and documented above, but defined here so that any of the hashing
644 // infrastructure is available.
645 template <typename T, typename U>
646 hash_code hash_value(const std::pair<T, U> &arg) {
647  return hash_combine(arg.first, arg.second);
648 }
649 
650 // Declared and documented above, but defined here so that any of the hashing
651 // infrastructure is available.
652 template <typename T>
653 hash_code hash_value(const std::basic_string<T> &arg) {
654  return hash_combine_range(arg.begin(), arg.end());
655 }
656 
657 } // namespace wpi
658 
659 #endif
hash_combine_recursive_helper()
Construct a recursive hash combining helper.
Definition: Hashing.h:504
The intermediate state used during hashing.
Definition: Hashing.h:258
Trait to indicate whether a type's bits can be hashed directly.
Definition: Hashing.h:345
hash_code combine(size_t length, char *buffer_ptr, char *buffer_end)
Base case for recursive, variadic combining.
Definition: Hashing.h:566
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition: Hashing.h:600
hash_code()=default
Default construct a hash_code.
hash_code combine(size_t length, char *buffer_ptr, char *buffer_end, const T &arg, const Ts &...args)
Recursive, variadic combining method.
Definition: Hashing.h:553
Definition: optional.h:885
static void mix_32_bytes(const char *s, uint64_t &a, uint64_t &b)
Mix 32-bytes from the input sequence into the 16-bytes of 'a' and 'b', including whatever is already ...
Definition: Hashing.h:275
static hash_state create(const char *s, uint64_t seed)
Create a new hash_state structure and initialize it based on the seed and the first 64-byte chunk...
Definition: Hashing.h:264
void set_fixed_execution_hash_seed(size_t fixed_value)
Override the execution seed with a fixed value.
WPILib C++ utilities (wpiutil) namespace.
Definition: SmallString.h:21
friend size_t hash_value(const hash_code &code)
Allow a hash_code to be directly run through hash_value.
Definition: Hashing.h:92
uint64_t finalize(size_t length)
Compute the final 64-bit hash code value based on the current state and the length of bytes hashed...
Definition: Hashing.h:305
void mix(const char *s)
Mix in a 64-byte buffer of data.
Definition: Hashing.h:288
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition: Hashing.h:478
Helper class to manage the recursive combining of hash_combine arguments.
Definition: Hashing.h:494
char * combine_data(size_t &length, char *buffer_ptr, char *buffer_end, T data)
Combine one chunk of data into the current in-flight hash.
Definition: Hashing.h:514
hash_code(size_t value)
Form a hash code directly from a numerical value.
Definition: Hashing.h:79
An opaque object representing a hash code.
Definition: Hashing.h:70