You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

pmh.h 8.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. /*
  2. * Frozen
  3. * Copyright 2016 QuarksLab
  4. *
  5. * Licensed to the Apache Software Foundation (ASF) under one
  6. * or more contributor license agreements. See the NOTICE file
  7. * distributed with this work for additional information
  8. * regarding copyright ownership. The ASF licenses this file
  9. * to you under the Apache License, Version 2.0 (the
  10. * "License"); you may not use this file except in compliance
  11. * with the License. You may obtain a copy of the License at
  12. *
  13. * http://www.apache.org/licenses/LICENSE-2.0
  14. *
  15. * Unless required by applicable law or agreed to in writing,
  16. * software distributed under the License is distributed on an
  17. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18. * KIND, either express or implied. See the License for the
  19. * specific language governing permissions and limitations
  20. * under the License.
  21. */
  22. // inspired from http://stevehanov.ca/blog/index.php?id=119
  23. #ifndef FROZEN_LETITGO_PMH_H
  24. #define FROZEN_LETITGO_PMH_H
  25. #include "frozen/bits/algorithms.h"
  26. #include "frozen/bits/basic_types.h"
  27. #include <array>
  28. #include <limits>
  29. namespace frozen {
  30. namespace bits {
  31. // Function object for sorting buckets in decreasing order of size
  32. struct bucket_size_compare {
  33. template <typename B>
  34. bool constexpr operator()(B const &b0,
  35. B const &b1) const {
  36. return b0.size() > b1.size();
  37. }
  38. };
  39. // Step One in pmh routine is to take all items and hash them into buckets,
  40. // with some collisions. Then process those buckets further to build a perfect
  41. // hash function.
  42. // pmh_buckets represents the initial placement into buckets.
  43. template <size_t M>
  44. struct pmh_buckets {
  45. // Step 0: Bucket max is 2 * sqrt M
  46. // TODO: Come up with justification for this, should it not be O(log M)?
  47. static constexpr auto bucket_max = 2 * (1u << (log(M) / 2));
  48. using bucket_t = cvector<std::size_t, bucket_max>;
  49. carray<bucket_t, M> buckets;
  50. uint64_t seed;
  51. // Represents a reference to a bucket. This is used because the buckets
  52. // have to be sorted, but buckets are big, making it slower than sorting refs
  53. struct bucket_ref {
  54. unsigned hash;
  55. const bucket_t * ptr;
  56. // Forward some interface of bucket
  57. using value_type = typename bucket_t::value_type;
  58. using const_iterator = typename bucket_t::const_iterator;
  59. constexpr auto size() const { return ptr->size(); }
  60. constexpr const auto & operator[](std::size_t idx) const { return (*ptr)[idx]; }
  61. constexpr auto begin() const { return ptr->begin(); }
  62. constexpr auto end() const { return ptr->end(); }
  63. };
  64. // Make a bucket_ref for each bucket
  65. template <std::size_t... Is>
  66. carray<bucket_ref, M> constexpr make_bucket_refs(std::index_sequence<Is...>) const {
  67. return {{ bucket_ref{Is, &buckets[Is]}... }};
  68. }
  69. // Makes a bucket_ref for each bucket and sorts them by size
  70. carray<bucket_ref, M> constexpr get_sorted_buckets() const {
  71. carray<bucket_ref, M> result{this->make_bucket_refs(std::make_index_sequence<M>())};
  72. bits::quicksort(result.begin(), result.end() - 1, bucket_size_compare{});
  73. return result;
  74. }
  75. };
  76. template <size_t M, class Item, size_t N, class Hash, class Key, class PRG>
  77. pmh_buckets<M> constexpr make_pmh_buckets(const carray<Item, N> & items,
  78. Hash const & hash,
  79. Key const & key,
  80. PRG & prg) {
  81. using result_t = pmh_buckets<M>;
  82. result_t result{};
  83. bool rejected = false;
  84. // Continue until all items are placed without exceeding bucket_max
  85. while (1) {
  86. for (auto & b : result.buckets) {
  87. b.clear();
  88. }
  89. result.seed = prg();
  90. rejected = false;
  91. for (std::size_t i = 0; i < N; ++i) {
  92. auto & bucket = result.buckets[hash(key(items[i]), static_cast<size_t>(result.seed)) % M];
  93. if (bucket.size() >= result_t::bucket_max) {
  94. rejected = true;
  95. break;
  96. }
  97. bucket.push_back(i);
  98. }
  99. if (!rejected) { return result; }
  100. }
  101. }
  102. // Check if an item appears in a cvector
  103. template<class T, size_t N>
  104. constexpr bool all_different_from(cvector<T, N> & data, T & a) {
  105. for (std::size_t i = 0; i < data.size(); ++i)
  106. if (data[i] == a)
  107. return false;
  108. return true;
  109. }
  110. // Represents either an index to a data item array, or a seed to be used with
  111. // a hasher. Seed must have high bit of 1, value has high bit of zero.
  112. struct seed_or_index {
  113. using value_type = uint64_t;
  114. private:
  115. static constexpr value_type MINUS_ONE = std::numeric_limits<value_type>::max();
  116. static constexpr value_type HIGH_BIT = ~(MINUS_ONE >> 1);
  117. value_type value_ = 0;
  118. public:
  119. constexpr value_type value() const { return value_; }
  120. constexpr bool is_seed() const { return value_ & HIGH_BIT; }
  121. constexpr seed_or_index(bool is_seed, value_type value)
  122. : value_(is_seed ? (value | HIGH_BIT) : (value & ~HIGH_BIT)) {}
  123. constexpr seed_or_index() = default;
  124. constexpr seed_or_index(const seed_or_index &) = default;
  125. constexpr seed_or_index & operator =(const seed_or_index &) = default;
  126. };
  127. // Represents the perfect hash function created by pmh algorithm
  128. template <std::size_t M, class Hasher>
  129. struct pmh_tables {
  130. uint64_t first_seed_;
  131. carray<seed_or_index, M> first_table_;
  132. carray<std::size_t, M> second_table_;
  133. Hasher hash_;
  134. // Looks up a given key, to find its expected index in carray<Item, N>
  135. // Always returns a valid index, must use KeyEqual test after to confirm.
  136. template <typename KeyType>
  137. constexpr std::size_t lookup(const KeyType & key) const {
  138. auto const d = first_table_[hash_(key, static_cast<size_t>(first_seed_)) % M];
  139. if (!d.is_seed()) { return static_cast<std::size_t>(d.value()); } // this is narrowing uint64 -> size_t but should be fine
  140. else { return second_table_[hash_(key, static_cast<std::size_t>(d.value())) % M]; }
  141. }
  142. };
  143. // Make pmh tables for given items, hash function, prg, etc.
  144. template <std::size_t M, class Item, std::size_t N, class Hash, class Key, class PRG>
  145. pmh_tables<M, Hash> constexpr make_pmh_tables(const carray<Item, N> &
  146. items,
  147. Hash const &hash,
  148. Key const &key,
  149. PRG prg) {
  150. // Step 1: Place all of the keys into buckets
  151. auto step_one = make_pmh_buckets<M>(items, hash, key, prg);
  152. // Step 2: Sort the buckets to process the ones with the most items first.
  153. auto buckets = step_one.get_sorted_buckets();
  154. // G becomes the first hash table in the resulting pmh function
  155. carray<seed_or_index, M> G; // Default constructed to "index 0"
  156. // H becomes the second hash table in the resulting pmh function
  157. constexpr std::size_t UNUSED = std::numeric_limits<std::size_t>::max();
  158. carray<std::size_t, M> H;
  159. H.fill(UNUSED);
  160. // Step 3: Map the items in buckets into hash tables.
  161. for (const auto & bucket : buckets) {
  162. auto const bsize = bucket.size();
  163. if (bsize == 1) {
  164. // Store index to the (single) item in G
  165. // assert(bucket.hash == hash(key(items[bucket[0]]), step_one.seed) % M);
  166. G[bucket.hash] = {false, static_cast<uint64_t>(bucket[0])};
  167. } else if (bsize > 1) {
  168. // Repeatedly try different H of d until we find a hash function
  169. // that places all items in the bucket into free slots
  170. seed_or_index d{true, prg()};
  171. cvector<std::size_t, decltype(step_one)::bucket_max> bucket_slots;
  172. while (bucket_slots.size() < bsize) {
  173. auto slot = hash(key(items[bucket[bucket_slots.size()]]), static_cast<size_t>(d.value())) % M;
  174. if (H[slot] != UNUSED || !all_different_from(bucket_slots, slot)) {
  175. bucket_slots.clear();
  176. d = {true, prg()};
  177. continue;
  178. }
  179. bucket_slots.push_back(slot);
  180. }
  181. // Put successful seed in G, and put indices to items in their slots
  182. // assert(bucket.hash == hash(key(items[bucket[0]]), step_one.seed) % M);
  183. G[bucket.hash] = d;
  184. for (std::size_t i = 0; i < bsize; ++i)
  185. H[bucket_slots[i]] = bucket[i];
  186. }
  187. }
  188. // Any unused entries in the H table have to get changed to zero.
  189. // This is because hashing should not fail or return an out-of-bounds entry.
  190. // A lookup fails after we apply user-supplied KeyEqual to the query and the
  191. // key found by hashing. Sending such queries to zero cannot hurt.
  192. for (std::size_t i = 0; i < M; ++i)
  193. if (H[i] == UNUSED)
  194. H[i] = 0;
  195. return {step_one.seed, G, H, hash};
  196. }
  197. } // namespace bits
  198. } // namespace frozen
  199. #endif