WPILibC++  2020.3.2
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/Endian.h"
49 #include "wpi/SwapByteOrder.h"
50 #include "wpi/type_traits.h"
51 #include <stdint.h>
52 #include <algorithm>
53 #include <cassert>
54 #include <cstring>
55 #include <string>
56 #include <utility>
57 
58 #ifdef _WIN32
59 #pragma warning(push)
60 #pragma warning(disable : 26495)
61 #endif
62 
63 namespace wpi {
64 
77 class hash_code {
78  size_t value;
79 
80 public:
83  hash_code() = default;
84 
86  hash_code(size_t value) : value(value) {}
87 
89  /*explicit*/ operator size_t() const { return value; }
90 
91  friend bool operator==(const hash_code &lhs, const hash_code &rhs) {
92  return lhs.value == rhs.value;
93  }
94  friend bool operator!=(const hash_code &lhs, const hash_code &rhs) {
95  return lhs.value != rhs.value;
96  }
97 
99  friend size_t hash_value(const hash_code &code) { return code.value; }
100 };
101 
109 template <typename T>
110 typename std::enable_if<is_integral_or_enum<T>::value, hash_code>::type
111 hash_value(T value);
112 
116 template <typename T> hash_code hash_value(const T *ptr);
117 
119 template <typename T, typename U>
120 hash_code hash_value(const std::pair<T, U> &arg);
121 
123 template <typename T>
124 hash_code hash_value(const std::basic_string<T> &arg);
125 
126 
141 void set_fixed_execution_hash_seed(uint64_t fixed_value);
142 
143 
144 // All of the implementation details of actually computing the various hash
145 // code values are held within this namespace. These routines are included in
146 // the header file mainly to allow inlining and constant propagation.
147 namespace hashing {
148 namespace detail {
149 
150 inline uint64_t fetch64(const char *p) {
151  uint64_t result;
152  memcpy(&result, p, sizeof(result));
153  if (support::endian::system_endianness() == support::big)
154  sys::swapByteOrder(result);
155  return result;
156 }
157 
158 inline uint32_t fetch32(const char *p) {
159  uint32_t result;
160  memcpy(&result, p, sizeof(result));
161  if (support::endian::system_endianness() == support::big)
162  sys::swapByteOrder(result);
163  return result;
164 }
165 
167 static const uint64_t k0 = 0xc3a5c85c97cb3127ULL;
168 static const uint64_t k1 = 0xb492b66fbe98f273ULL;
169 static const uint64_t k2 = 0x9ae16a3b2f90404fULL;
170 static const uint64_t k3 = 0xc949d7c7509e6557ULL;
171 
175 inline uint64_t rotate(uint64_t val, size_t shift) {
176  // Avoid shifting by 64: doing so yields an undefined result.
177  return shift == 0 ? val : ((val >> shift) | (val << (64 - shift)));
178 }
179 
180 inline uint64_t shift_mix(uint64_t val) {
181  return val ^ (val >> 47);
182 }
183 
184 inline uint64_t hash_16_bytes(uint64_t low, uint64_t high) {
185  // Murmur-inspired hashing.
186  const uint64_t kMul = 0x9ddfea08eb382d69ULL;
187  uint64_t a = (low ^ high) * kMul;
188  a ^= (a >> 47);
189  uint64_t b = (high ^ a) * kMul;
190  b ^= (b >> 47);
191  b *= kMul;
192  return b;
193 }
194 
195 inline uint64_t hash_1to3_bytes(const char *s, size_t len, uint64_t seed) {
196  uint8_t a = s[0];
197  uint8_t b = s[len >> 1];
198  uint8_t c = s[len - 1];
199  uint32_t y = static_cast<uint32_t>(a) + (static_cast<uint32_t>(b) << 8);
200  uint32_t z = static_cast<uint32_t>(len + (static_cast<uint64_t>(c) << 2));
201  return shift_mix(y * k2 ^ z * k3 ^ seed) * k2;
202 }
203 
204 inline uint64_t hash_4to8_bytes(const char *s, size_t len, uint64_t seed) {
205  uint64_t a = fetch32(s);
206  return hash_16_bytes(len + (a << 3), seed ^ fetch32(s + len - 4));
207 }
208 
209 inline uint64_t hash_9to16_bytes(const char *s, size_t len, uint64_t seed) {
210  uint64_t a = fetch64(s);
211  uint64_t b = fetch64(s + len - 8);
212  return hash_16_bytes(seed ^ a, rotate(b + len, len)) ^ b;
213 }
214 
215 inline uint64_t hash_17to32_bytes(const char *s, size_t len, uint64_t seed) {
216  uint64_t a = fetch64(s) * k1;
217  uint64_t b = fetch64(s + 8);
218  uint64_t c = fetch64(s + len - 8) * k2;
219  uint64_t d = fetch64(s + len - 16) * k0;
220  return hash_16_bytes(rotate(a - b, 43) + rotate(c ^ seed, 30) + d,
221  a + rotate(b ^ k3, 20) - c + len + seed);
222 }
223 
224 inline uint64_t hash_33to64_bytes(const char *s, size_t len, uint64_t seed) {
225  uint64_t z = fetch64(s + 24);
226  uint64_t a = fetch64(s) + (len + fetch64(s + len - 16)) * k0;
227  uint64_t b = rotate(a + z, 52);
228  uint64_t c = rotate(a, 37);
229  a += fetch64(s + 8);
230  c += rotate(a, 7);
231  a += fetch64(s + 16);
232  uint64_t vf = a + z;
233  uint64_t vs = b + rotate(a, 31) + c;
234  a = fetch64(s + 16) + fetch64(s + len - 32);
235  z = fetch64(s + len - 8);
236  b = rotate(a + z, 52);
237  c = rotate(a, 37);
238  a += fetch64(s + len - 24);
239  c += rotate(a, 7);
240  a += fetch64(s + len - 16);
241  uint64_t wf = a + z;
242  uint64_t ws = b + rotate(a, 31) + c;
243  uint64_t r = shift_mix((vf + ws) * k2 + (wf + vs) * k0);
244  return shift_mix((seed ^ (r * k0)) + vs) * k2;
245 }
246 
247 inline uint64_t hash_short(const char *s, size_t length, uint64_t seed) {
248  if (length >= 4 && length <= 8)
249  return hash_4to8_bytes(s, length, seed);
250  if (length > 8 && length <= 16)
251  return hash_9to16_bytes(s, length, seed);
252  if (length > 16 && length <= 32)
253  return hash_17to32_bytes(s, length, seed);
254  if (length > 32)
255  return hash_33to64_bytes(s, length, seed);
256  if (length != 0)
257  return hash_1to3_bytes(s, length, seed);
258 
259  return k2 ^ seed;
260 }
261 
265 struct hash_state {
266  uint64_t h0, h1, h2, h3, h4, h5, h6;
267 
271  static hash_state create(const char *s, uint64_t seed) {
272  hash_state state = {
273  0, seed, hash_16_bytes(seed, k1), rotate(seed ^ k1, 49),
274  seed * k1, shift_mix(seed), 0 };
275  state.h6 = hash_16_bytes(state.h4, state.h5);
276  state.mix(s);
277  return state;
278  }
279 
282  static void mix_32_bytes(const char *s, uint64_t &a, uint64_t &b) {
283  a += fetch64(s);
284  uint64_t c = fetch64(s + 24);
285  b = rotate(b + a + c, 21);
286  uint64_t d = a;
287  a += fetch64(s + 8) + fetch64(s + 16);
288  b += rotate(a, 44) + d;
289  a += c;
290  }
291 
295  void mix(const char *s) {
296  h0 = rotate(h0 + h1 + h3 + fetch64(s + 8), 37) * k1;
297  h1 = rotate(h1 + h4 + fetch64(s + 48), 42) * k1;
298  h0 ^= h6;
299  h1 += h3 + fetch64(s + 40);
300  h2 = rotate(h2 + h5, 33) * k1;
301  h3 = h4 * k1;
302  h4 = h0 + h5;
303  mix_32_bytes(s, h3, h4);
304  h5 = h2 + h6;
305  h6 = h1 + fetch64(s + 16);
306  mix_32_bytes(s + 32, h5, h6);
307  std::swap(h2, h0);
308  }
309 
312  uint64_t finalize(size_t length) {
313  return hash_16_bytes(hash_16_bytes(h3, h5) + shift_mix(h1) * k1 + h2,
314  hash_16_bytes(h4, h6) + shift_mix(length) * k1 + h0);
315  }
316 };
317 
318 
324 extern uint64_t fixed_seed_override;
325 
326 inline uint64_t get_execution_seed() {
327  // FIXME: This needs to be a per-execution seed. This is just a placeholder
328  // implementation. Switching to a per-execution seed is likely to flush out
329  // instability bugs and so will happen as its own commit.
330  //
331  // However, if there is a fixed seed override set the first time this is
332  // called, return that instead of the per-execution seed.
333  const uint64_t seed_prime = 0xff51afd7ed558ccdULL;
334  static uint64_t seed = fixed_seed_override ? fixed_seed_override : seed_prime;
335  return seed;
336 }
337 
338 
344 //
345 // FIXME: We want to replace is_integral_or_enum and is_pointer here with
346 // a predicate which asserts that comparing the underlying storage of two
347 // values of the type for equality is equivalent to comparing the two values
348 // for equality. For all the platforms we care about, this holds for integers
349 // and pointers, but there are platforms where it doesn't and we would like to
350 // support user-defined types which happen to satisfy this property.
351 template <typename T> struct is_hashable_data
352  : std::integral_constant<bool, ((is_integral_or_enum<T>::value ||
353  std::is_pointer<T>::value) &&
354  64 % sizeof(T) == 0)> {};
355 
356 // Special case std::pair to detect when both types are viable and when there
357 // is no alignment-derived padding in the pair. This is a bit of a lie because
358 // std::pair isn't truly POD, but it's close enough in all reasonable
359 // implementations for our use case of hashing the underlying data.
360 template <typename T, typename U> struct is_hashable_data<std::pair<T, U> >
361  : std::integral_constant<bool, (is_hashable_data<T>::value &&
362  is_hashable_data<U>::value &&
363  (sizeof(T) + sizeof(U)) ==
364  sizeof(std::pair<T, U>))> {};
365 
368 template <typename T>
369 typename std::enable_if<is_hashable_data<T>::value, T>::type
370 get_hashable_data(const T &value) {
371  return value;
372 }
376 template <typename T>
377 typename std::enable_if<!is_hashable_data<T>::value, size_t>::type
378 get_hashable_data(const T &value) {
379  using ::wpi::hash_value;
380  return hash_value(value);
381 }
382 
390 template <typename T>
391 bool store_and_advance(char *&buffer_ptr, char *buffer_end, const T& value,
392  size_t offset = 0) {
393  size_t store_size = sizeof(value) - offset;
394  if (buffer_ptr + store_size > buffer_end)
395  return false;
396  const char *value_data = reinterpret_cast<const char *>(&value);
397  memcpy(buffer_ptr, value_data + offset, store_size);
398  buffer_ptr += store_size;
399  return true;
400 }
401 
407 template <typename InputIteratorT>
408 hash_code hash_combine_range_impl(InputIteratorT first, InputIteratorT last) {
409  const uint64_t seed = get_execution_seed();
410  char buffer[64], *buffer_ptr = buffer;
411  char *const buffer_end = std::end(buffer);
412  while (first != last && store_and_advance(buffer_ptr, buffer_end,
413  get_hashable_data(*first)))
414  ++first;
415  if (first == last)
416  return hash_short(buffer, buffer_ptr - buffer, seed);
417  assert(buffer_ptr == buffer_end);
418 
419  hash_state state = state.create(buffer, seed);
420  size_t length = 64;
421  while (first != last) {
422  // Fill up the buffer. We don't clear it, which re-mixes the last round
423  // when only a partial 64-byte chunk is left.
424  buffer_ptr = buffer;
425  while (first != last && store_and_advance(buffer_ptr, buffer_end,
426  get_hashable_data(*first)))
427  ++first;
428 
429  // Rotate the buffer if we did a partial fill in order to simulate doing
430  // a mix of the last 64-bytes. That is how the algorithm works when we
431  // have a contiguous byte sequence, and we want to emulate that here.
432  std::rotate(buffer, buffer_ptr, buffer_end);
433 
434  // Mix this chunk into the current state.
435  state.mix(buffer);
436  length += buffer_ptr - buffer;
437  };
438 
439  return state.finalize(length);
440 }
441 
450 template <typename ValueT>
451 typename std::enable_if<is_hashable_data<ValueT>::value, hash_code>::type
452 hash_combine_range_impl(ValueT *first, ValueT *last) {
453  const uint64_t seed = get_execution_seed();
454  const char *s_begin = reinterpret_cast<const char *>(first);
455  const char *s_end = reinterpret_cast<const char *>(last);
456  const size_t length = std::distance(s_begin, s_end);
457  if (length <= 64)
458  return hash_short(s_begin, length, seed);
459 
460  const char *s_aligned_end = s_begin + (length & ~63);
461  hash_state state = state.create(s_begin, seed);
462  s_begin += 64;
463  while (s_begin != s_aligned_end) {
464  state.mix(s_begin);
465  s_begin += 64;
466  }
467  if (length & 63)
468  state.mix(s_end - 64);
469 
470  return state.finalize(length);
471 }
472 
473 } // namespace detail
474 } // namespace hashing
475 
476 
483 template <typename InputIteratorT>
484 hash_code hash_combine_range(InputIteratorT first, InputIteratorT last) {
485  return ::wpi::hashing::detail::hash_combine_range_impl(first, last);
486 }
487 
488 
489 // Implementation details for hash_combine.
490 namespace hashing {
491 namespace detail {
492 
501  char buffer[64];
502  hash_state state;
503  const uint64_t seed;
504 
505 public:
511  : seed(get_execution_seed()) {}
512 
519  template <typename T>
520  char *combine_data(size_t &length, char *buffer_ptr, char *buffer_end, T data) {
521  if (!store_and_advance(buffer_ptr, buffer_end, data)) {
522  // Check for skew which prevents the buffer from being packed, and do
523  // a partial store into the buffer to fill it. This is only a concern
524  // with the variadic combine because that formation can have varying
525  // argument types.
526  size_t partial_store_size = buffer_end - buffer_ptr;
527  memcpy(buffer_ptr, &data, partial_store_size);
528 
529  // If the store fails, our buffer is full and ready to hash. We have to
530  // either initialize the hash state (on the first full buffer) or mix
531  // this buffer into the existing hash state. Length tracks the *hashed*
532  // length, not the buffered length.
533  if (length == 0) {
534  state = state.create(buffer, seed);
535  length = 64;
536  } else {
537  // Mix this chunk into the current state and bump length up by 64.
538  state.mix(buffer);
539  length += 64;
540  }
541  // Reset the buffer_ptr to the head of the buffer for the next chunk of
542  // data.
543  buffer_ptr = buffer;
544 
545  // Try again to store into the buffer -- this cannot fail as we only
546  // store types smaller than the buffer.
547  if (!store_and_advance(buffer_ptr, buffer_end, data,
548  partial_store_size))
549  abort();
550  }
551  return buffer_ptr;
552  }
553 
558  template <typename T, typename ...Ts>
559  hash_code combine(size_t length, char *buffer_ptr, char *buffer_end,
560  const T &arg, const Ts &...args) {
561  buffer_ptr = combine_data(length, buffer_ptr, buffer_end, get_hashable_data(arg));
562 
563  // Recurse to the next argument.
564  return combine(length, buffer_ptr, buffer_end, args...);
565  }
566 
572  hash_code combine(size_t length, char *buffer_ptr, char *buffer_end) {
573  // Check whether the entire set of values fit in the buffer. If so, we'll
574  // use the optimized short hashing routine and skip state entirely.
575  if (length == 0)
576  return static_cast<size_t>(hash_short(buffer, buffer_ptr - buffer, seed));
577 
578  // Mix the final buffer, rotating it if we did a partial fill in order to
579  // simulate doing a mix of the last 64-bytes. That is how the algorithm
580  // works when we have a contiguous byte sequence, and we want to emulate
581  // that here.
582  std::rotate(buffer, buffer_ptr, buffer_end);
583 
584  // Mix this chunk into the current state.
585  state.mix(buffer);
586  length += buffer_ptr - buffer;
587 
588  return static_cast<size_t>(state.finalize(length));
589  }
590 };
591 
592 } // namespace detail
593 } // namespace hashing
594 
606 template <typename ...Ts> hash_code hash_combine(const Ts &...args) {
607  // Recursively hash each argument using a helper class.
609  return helper.combine(0, helper.buffer, helper.buffer + 64, args...);
610 }
611 
612 // Implementation details for implementations of hash_value overloads provided
613 // here.
614 namespace hashing {
615 namespace detail {
616 
622 inline hash_code hash_integer_value(uint64_t value) {
623  // Similar to hash_4to8_bytes but using a seed instead of length.
624  const uint64_t seed = get_execution_seed();
625  const char *s = reinterpret_cast<const char *>(&value);
626  const uint64_t a = fetch32(s);
627  return static_cast<size_t>(hash_16_bytes(seed + (a << 3), fetch32(s + 4)));
628 }
629 
630 } // namespace detail
631 } // namespace hashing
632 
633 // Declared and documented above, but defined here so that any of the hashing
634 // infrastructure is available.
635 template <typename T>
636 typename std::enable_if<is_integral_or_enum<T>::value, hash_code>::type
637 hash_value(T value) {
638  return ::wpi::hashing::detail::hash_integer_value(
639  static_cast<uint64_t>(value));
640 }
641 
642 // Declared and documented above, but defined here so that any of the hashing
643 // infrastructure is available.
644 template <typename T> hash_code hash_value(const T *ptr) {
645  return ::wpi::hashing::detail::hash_integer_value(
646  reinterpret_cast<uintptr_t>(ptr));
647 }
648 
649 // Declared and documented above, but defined here so that any of the hashing
650 // infrastructure is available.
651 template <typename T, typename U>
652 hash_code hash_value(const std::pair<T, U> &arg) {
653  return hash_combine(arg.first, arg.second);
654 }
655 
656 // Declared and documented above, but defined here so that any of the hashing
657 // infrastructure is available.
658 template <typename T>
659 hash_code hash_value(const std::basic_string<T> &arg) {
660  return hash_combine_range(arg.begin(), arg.end());
661 }
662 
663 } // namespace wpi
664 
665 #ifdef _WIN32
666 #pragma warning(pop)
667 #endif
668 
669 #endif
wpi::hashing::detail::hash_state::create
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:271
wpi::set_fixed_execution_hash_seed
void set_fixed_execution_hash_seed(uint64_t fixed_value)
Override the execution seed with a fixed value.
wpi::hashing::detail::hash_state::mix
void mix(const char *s)
Mix in a 64-byte buffer of data.
Definition: Hashing.h:295
wpi::hash_code::hash_code
hash_code()=default
Default construct a hash_code.
wpi::hashing::detail::hash_state::mix_32_bytes
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:282
wpi::hash_code::hash_value
friend size_t hash_value(const hash_code &code)
Allow a hash_code to be directly run through hash_value.
Definition: Hashing.h:99
wpi
WPILib C++ utilities (wpiutil) namespace.
Definition: EventLoopRunner.h:17
wpi::hashing::detail::hash_combine_recursive_helper
Helper class to manage the recursive combining of hash_combine arguments.
Definition: Hashing.h:500
wpi::hashing::detail::is_hashable_data
Trait to indicate whether a type's bits can be hashed directly.
Definition: Hashing.h:351
wpi::hashing::detail::hash_combine_recursive_helper::combine_data
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:520
wpi::hashing::detail::hash_state::finalize
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:312
wpi::hashing::detail::hash_combine_recursive_helper::combine
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:559
wpi::hashing::detail::hash_combine_recursive_helper::hash_combine_recursive_helper
hash_combine_recursive_helper()
Construct a recursive hash combining helper.
Definition: Hashing.h:510
wpi::hashing::detail::hash_combine_recursive_helper::combine
hash_code combine(size_t length, char *buffer_ptr, char *buffer_end)
Base case for recursive, variadic combining.
Definition: Hashing.h:572
wpi::hash_combine_range
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition: Hashing.h:484
wpi::hash_code
An opaque object representing a hash code.
Definition: Hashing.h:77
wpi::hashing::detail::hash_state
The intermediate state used during hashing.
Definition: Hashing.h:265
wpi::hash_combine
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition: Hashing.h:606
wpi::hash_code::hash_code
hash_code(size_t value)
Form a hash code directly from a numerical value.
Definition: Hashing.h:86