/src/abseil-cpp/absl/container/internal/raw_hash_set.h
Line | Count | Source (jump to first uncovered line) |
1 | | // Copyright 2018 The Abseil Authors. |
2 | | // |
3 | | // Licensed under the Apache License, Version 2.0 (the "License"); |
4 | | // you may not use this file except in compliance with the License. |
5 | | // You may obtain a copy of the License at |
6 | | // |
7 | | // https://www.apache.org/licenses/LICENSE-2.0 |
8 | | // |
9 | | // Unless required by applicable law or agreed to in writing, software |
10 | | // distributed under the License is distributed on an "AS IS" BASIS, |
11 | | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
12 | | // See the License for the specific language governing permissions and |
13 | | // limitations under the License. |
14 | | // |
15 | | // An open-addressing |
16 | | // hashtable with quadratic probing. |
17 | | // |
18 | | // This is a low level hashtable on top of which different interfaces can be |
19 | | // implemented, like flat_hash_set, node_hash_set, string_hash_set, etc. |
20 | | // |
21 | | // The table interface is similar to that of std::unordered_set. Notable |
22 | | // differences are that most member functions support heterogeneous keys when |
23 | | // BOTH the hash and eq functions are marked as transparent. They do so by |
24 | | // providing a typedef called `is_transparent`. |
25 | | // |
26 | | // When heterogeneous lookup is enabled, functions that take key_type act as if |
27 | | // they have an overload set like: |
28 | | // |
29 | | // iterator find(const key_type& key); |
30 | | // template <class K> |
31 | | // iterator find(const K& key); |
32 | | // |
33 | | // size_type erase(const key_type& key); |
34 | | // template <class K> |
35 | | // size_type erase(const K& key); |
36 | | // |
37 | | // std::pair<iterator, iterator> equal_range(const key_type& key); |
38 | | // template <class K> |
39 | | // std::pair<iterator, iterator> equal_range(const K& key); |
40 | | // |
41 | | // When heterogeneous lookup is disabled, only the explicit `key_type` overloads |
42 | | // exist. |
43 | | // |
44 | | // In addition the pointer to element and iterator stability guarantees are |
45 | | // weaker: all iterators and pointers are invalidated after a new element is |
46 | | // inserted. |
47 | | // |
48 | | // IMPLEMENTATION DETAILS |
49 | | // |
50 | | // # Table Layout |
51 | | // |
52 | | // A raw_hash_set's backing array consists of control bytes followed by slots |
53 | | // that may or may not contain objects. |
54 | | // |
55 | | // The layout of the backing array, for `capacity` slots, is thus, as a |
56 | | // pseudo-struct: |
57 | | // |
58 | | // struct BackingArray { |
59 | | // // Sampling handler. This field isn't present when the sampling is |
60 | | // // disabled or this allocation hasn't been selected for sampling. |
61 | | // HashtablezInfoHandle infoz_; |
62 | | // // The number of elements we can insert before growing the capacity. |
63 | | // size_t growth_left; |
64 | | // // Control bytes for the "real" slots. |
65 | | // ctrl_t ctrl[capacity]; |
66 | | // // Always `ctrl_t::kSentinel`. This is used by iterators to find when to |
67 | | // // stop and serves no other purpose. |
68 | | // ctrl_t sentinel; |
69 | | // // A copy of the first `kWidth - 1` elements of `ctrl`. This is used so |
70 | | // // that if a probe sequence picks a value near the end of `ctrl`, |
71 | | // // `Group` will have valid control bytes to look at. |
72 | | // ctrl_t clones[kWidth - 1]; |
73 | | // // The actual slot data. |
74 | | // slot_type slots[capacity]; |
75 | | // }; |
76 | | // |
77 | | // The length of this array is computed by `RawHashSetLayout::alloc_size` below. |
78 | | // |
79 | | // Control bytes (`ctrl_t`) are bytes (collected into groups of a |
80 | | // platform-specific size) that define the state of the corresponding slot in |
81 | | // the slot array. Group manipulation is tightly optimized to be as efficient |
82 | | // as possible: SSE and friends on x86, clever bit operations on other arches. |
83 | | // |
84 | | // Group 1 Group 2 Group 3 |
85 | | // +---------------+---------------+---------------+ |
86 | | // | | | | | | | | | | | | | | | | | | | | | | | | | |
87 | | // +---------------+---------------+---------------+ |
88 | | // |
89 | | // Each control byte is either a special value for empty slots, deleted slots |
90 | | // (sometimes called *tombstones*), and a special end-of-table marker used by |
91 | | // iterators, or, if occupied, seven bits (H2) from the hash of the value in the |
92 | | // corresponding slot. |
93 | | // |
94 | | // Storing control bytes in a separate array also has beneficial cache effects, |
95 | | // since more logical slots will fit into a cache line. |
96 | | // |
97 | | // # Small Object Optimization (SOO) |
98 | | // |
99 | | // When the size/alignment of the value_type and the capacity of the table are |
100 | | // small, we enable small object optimization and store the values inline in |
101 | | // the raw_hash_set object. This optimization allows us to avoid |
102 | | // allocation/deallocation as well as cache/dTLB misses. |
103 | | // |
104 | | // # Hashing |
105 | | // |
106 | | // We compute two separate hashes, `H1` and `H2`, from the hash of an object. |
107 | | // `H1(hash(x))` is an index into `slots`, and essentially the starting point |
108 | | // for the probe sequence. `H2(hash(x))` is a 7-bit value used to filter out |
109 | | // objects that cannot possibly be the one we are looking for. |
110 | | // |
111 | | // # Table operations. |
112 | | // |
113 | | // The key operations are `insert`, `find`, and `erase`. |
114 | | // |
115 | | // Since `insert` and `erase` are implemented in terms of `find`, we describe |
116 | | // `find` first. To `find` a value `x`, we compute `hash(x)`. From |
117 | | // `H1(hash(x))` and the capacity, we construct a `probe_seq` that visits every |
118 | | // group of slots in some interesting order. |
119 | | // |
120 | | // We now walk through these indices. At each index, we select the entire group |
121 | | // starting with that index and extract potential candidates: occupied slots |
122 | | // with a control byte equal to `H2(hash(x))`. If we find an empty slot in the |
123 | | // group, we stop and return an error. Each candidate slot `y` is compared with |
124 | | // `x`; if `x == y`, we are done and return `&y`; otherwise we continue to the |
125 | | // next probe index. Tombstones effectively behave like full slots that never |
126 | | // match the value we're looking for. |
127 | | // |
128 | | // The `H2` bits ensure when we compare a slot to an object with `==`, we are |
129 | | // likely to have actually found the object. That is, the chance is low that |
130 | | // `==` is called and returns `false`. Thus, when we search for an object, we |
131 | | // are unlikely to call `==` many times. This likelyhood can be analyzed as |
132 | | // follows (assuming that H2 is a random enough hash function). |
133 | | // |
134 | | // Let's assume that there are `k` "wrong" objects that must be examined in a |
135 | | // probe sequence. For example, when doing a `find` on an object that is in the |
136 | | // table, `k` is the number of objects between the start of the probe sequence |
137 | | // and the final found object (not including the final found object). The |
138 | | // expected number of objects with an H2 match is then `k/128`. Measurements |
139 | | // and analysis indicate that even at high load factors, `k` is less than 32, |
140 | | // meaning that the number of "false positive" comparisons we must perform is |
141 | | // less than 1/8 per `find`. |
142 | | |
143 | | // `insert` is implemented in terms of `unchecked_insert`, which inserts a |
144 | | // value presumed to not be in the table (violating this requirement will cause |
145 | | // the table to behave erratically). Given `x` and its hash `hash(x)`, to insert |
146 | | // it, we construct a `probe_seq` once again, and use it to find the first |
147 | | // group with an unoccupied (empty *or* deleted) slot. We place `x` into the |
148 | | // first such slot in the group and mark it as full with `x`'s H2. |
149 | | // |
150 | | // To `insert`, we compose `unchecked_insert` with `find`. We compute `h(x)` and |
151 | | // perform a `find` to see if it's already present; if it is, we're done. If |
152 | | // it's not, we may decide the table is getting overcrowded (i.e. the load |
153 | | // factor is greater than 7/8 for big tables; tables smaller than one probing |
154 | | // group use a max load factor of 1); in this case, we allocate a bigger array, |
155 | | // `unchecked_insert` each element of the table into the new array (we know that |
156 | | // no insertion here will insert an already-present value), and discard the old |
157 | | // backing array. At this point, we may `unchecked_insert` the value `x`. |
158 | | // |
159 | | // Below, `unchecked_insert` is partly implemented by `prepare_insert`, which |
160 | | // presents a viable, initialized slot pointee to the caller. |
161 | | // |
162 | | // `erase` is implemented in terms of `erase_at`, which takes an index to a |
163 | | // slot. Given an offset, we simply create a tombstone and destroy its contents. |
164 | | // If we can prove that the slot would not appear in a probe sequence, we can |
165 | | // make the slot as empty, instead. We can prove this by observing that if a |
166 | | // group has any empty slots, it has never been full (assuming we never create |
167 | | // an empty slot in a group with no empties, which this heuristic guarantees we |
168 | | // never do) and find would stop at this group anyways (since it does not probe |
169 | | // beyond groups with empties). |
170 | | // |
171 | | // `erase` is `erase_at` composed with `find`: if we |
172 | | // have a value `x`, we can perform a `find`, and then `erase_at` the resulting |
173 | | // slot. |
174 | | // |
175 | | // To iterate, we simply traverse the array, skipping empty and deleted slots |
176 | | // and stopping when we hit a `kSentinel`. |
177 | | |
178 | | #ifndef ABSL_CONTAINER_INTERNAL_RAW_HASH_SET_H_ |
179 | | #define ABSL_CONTAINER_INTERNAL_RAW_HASH_SET_H_ |
180 | | |
181 | | #include <algorithm> |
182 | | #include <cassert> |
183 | | #include <cmath> |
184 | | #include <cstddef> |
185 | | #include <cstdint> |
186 | | #include <cstring> |
187 | | #include <functional> |
188 | | #include <initializer_list> |
189 | | #include <iterator> |
190 | | #include <limits> |
191 | | #include <memory> |
192 | | #include <tuple> |
193 | | #include <type_traits> |
194 | | #include <utility> |
195 | | |
196 | | #include "absl/base/attributes.h" |
197 | | #include "absl/base/casts.h" |
198 | | #include "absl/base/config.h" |
199 | | #include "absl/base/internal/endian.h" |
200 | | #include "absl/base/internal/iterator_traits.h" |
201 | | #include "absl/base/internal/raw_logging.h" |
202 | | #include "absl/base/macros.h" |
203 | | #include "absl/base/optimization.h" |
204 | | #include "absl/base/options.h" |
205 | | #include "absl/base/port.h" |
206 | | #include "absl/base/prefetch.h" |
207 | | #include "absl/container/internal/common.h" // IWYU pragma: export // for node_handle |
208 | | #include "absl/container/internal/common_policy_traits.h" |
209 | | #include "absl/container/internal/compressed_tuple.h" |
210 | | #include "absl/container/internal/container_memory.h" |
211 | | #include "absl/container/internal/hash_function_defaults.h" |
212 | | #include "absl/container/internal/hash_policy_traits.h" |
213 | | #include "absl/container/internal/hashtable_control_bytes.h" |
214 | | #include "absl/container/internal/hashtable_debug_hooks.h" |
215 | | #include "absl/container/internal/hashtablez_sampler.h" |
216 | | #include "absl/functional/function_ref.h" |
217 | | #include "absl/hash/hash.h" |
218 | | #include "absl/hash/internal/weakly_mixed_integer.h" |
219 | | #include "absl/memory/memory.h" |
220 | | #include "absl/meta/type_traits.h" |
221 | | #include "absl/numeric/bits.h" |
222 | | #include "absl/utility/utility.h" |
223 | | |
224 | | namespace absl { |
225 | | ABSL_NAMESPACE_BEGIN |
226 | | namespace container_internal { |
227 | | |
228 | | #ifdef ABSL_SWISSTABLE_ENABLE_GENERATIONS |
229 | | #error ABSL_SWISSTABLE_ENABLE_GENERATIONS cannot be directly set |
230 | | #elif (defined(ABSL_HAVE_ADDRESS_SANITIZER) || \ |
231 | | defined(ABSL_HAVE_HWADDRESS_SANITIZER) || \ |
232 | | defined(ABSL_HAVE_MEMORY_SANITIZER)) && \ |
233 | | !defined(NDEBUG_SANITIZER) // If defined, performance is important. |
234 | | // When compiled in sanitizer mode, we add generation integers to the backing |
235 | | // array and iterators. In the backing array, we store the generation between |
236 | | // the control bytes and the slots. When iterators are dereferenced, we assert |
237 | | // that the container has not been mutated in a way that could cause iterator |
238 | | // invalidation since the iterator was initialized. |
239 | | #define ABSL_SWISSTABLE_ENABLE_GENERATIONS |
240 | | #endif |
241 | | |
242 | | #ifdef ABSL_SWISSTABLE_ASSERT |
243 | | #error ABSL_SWISSTABLE_ASSERT cannot be directly set |
244 | | #else |
245 | | // We use this macro for assertions that users may see when the table is in an |
246 | | // invalid state that sanitizers may help diagnose. |
247 | | #define ABSL_SWISSTABLE_ASSERT(CONDITION) \ |
248 | 71.1M | assert((CONDITION) && "Try enabling sanitizers.") |
249 | | #endif |
250 | | |
251 | | // We use uint8_t so we don't need to worry about padding. |
252 | | using GenerationType = uint8_t; |
253 | | |
254 | | // A sentinel value for empty generations. Using 0 makes it easy to constexpr |
255 | | // initialize an array of this value. |
256 | 203k | constexpr GenerationType SentinelEmptyGeneration() { return 0; } |
257 | | |
258 | 203k | constexpr GenerationType NextGeneration(GenerationType generation) { |
259 | 203k | return ++generation == SentinelEmptyGeneration() ? ++generation : generation; |
260 | 203k | } |
261 | | |
262 | | #ifdef ABSL_SWISSTABLE_ENABLE_GENERATIONS |
263 | | constexpr bool SwisstableGenerationsEnabled() { return true; } |
264 | | constexpr size_t NumGenerationBytes() { return sizeof(GenerationType); } |
265 | | #else |
266 | 0 | constexpr bool SwisstableGenerationsEnabled() { return false; } |
267 | 611k | constexpr size_t NumGenerationBytes() { return 0; } |
268 | | #endif |
269 | | |
270 | | // Returns true if we should assert that the table is not accessed after it has |
271 | | // been destroyed or during the destruction of the table. |
272 | 0 | constexpr bool SwisstableAssertAccessToDestroyedTable() { |
273 | 0 | #ifndef NDEBUG |
274 | 0 | return true; |
275 | 0 | #endif |
276 | 0 | return SwisstableGenerationsEnabled(); |
277 | 0 | } |
278 | | |
279 | | template <typename AllocType> |
280 | | void SwapAlloc(AllocType& lhs, AllocType& rhs, |
281 | | std::true_type /* propagate_on_container_swap */) { |
282 | | using std::swap; |
283 | | swap(lhs, rhs); |
284 | | } |
285 | | template <typename AllocType> |
286 | | void SwapAlloc([[maybe_unused]] AllocType& lhs, [[maybe_unused]] AllocType& rhs, |
287 | | std::false_type /* propagate_on_container_swap */) { |
288 | | assert(lhs == rhs && |
289 | | "It's UB to call swap with unequal non-propagating allocators."); |
290 | | } |
291 | | |
292 | | template <typename AllocType> |
293 | | void CopyAlloc(AllocType& lhs, AllocType& rhs, |
294 | | std::true_type /* propagate_alloc */) { |
295 | | lhs = rhs; |
296 | | } |
297 | | template <typename AllocType> |
298 | | void CopyAlloc(AllocType&, AllocType&, std::false_type /* propagate_alloc */) {} |
299 | | |
300 | | // The state for a probe sequence. |
301 | | // |
302 | | // Currently, the sequence is a triangular progression of the form |
303 | | // |
304 | | // p(i) := Width * (i^2 + i)/2 + hash (mod mask + 1) |
305 | | // |
306 | | // The use of `Width` ensures that each probe step does not overlap groups; |
307 | | // the sequence effectively outputs the addresses of *groups* (although not |
308 | | // necessarily aligned to any boundary). The `Group` machinery allows us |
309 | | // to check an entire group with minimal branching. |
310 | | // |
311 | | // Wrapping around at `mask + 1` is important, but not for the obvious reason. |
312 | | // As described above, the first few entries of the control byte array |
313 | | // are mirrored at the end of the array, which `Group` will find and use |
314 | | // for selecting candidates. However, when those candidates' slots are |
315 | | // actually inspected, there are no corresponding slots for the cloned bytes, |
316 | | // so we need to make sure we've treated those offsets as "wrapping around". |
317 | | // |
318 | | // It turns out that this probe sequence visits every group exactly once if the |
319 | | // number of groups is a power of two, since (i^2+i)/2 is a bijection in |
320 | | // Z/(2^m). See https://en.wikipedia.org/wiki/Quadratic_probing |
321 | | template <size_t Width> |
322 | | class probe_seq { |
323 | | public: |
324 | | // Creates a new probe sequence using `hash` as the initial value of the |
325 | | // sequence and `mask` (usually the capacity of the table) as the mask to |
326 | | // apply to each value in the progression. |
327 | | probe_seq(size_t hash, size_t mask) { |
328 | | ABSL_SWISSTABLE_ASSERT(((mask + 1) & mask) == 0 && "not a mask"); |
329 | | mask_ = mask; |
330 | | offset_ = hash & mask_; |
331 | | } |
332 | | |
333 | | // The offset within the table, i.e., the value `p(i)` above. |
334 | 145M | size_t offset() const { return offset_; } |
335 | 37.1M | size_t offset(size_t i) const { return (offset_ + i) & mask_; } |
336 | | |
337 | 4.26M | void next() { |
338 | 4.26M | index_ += Width; |
339 | 4.26M | offset_ += index_; |
340 | 4.26M | offset_ &= mask_; |
341 | 4.26M | } |
342 | | // 0-based probe index, a multiple of `Width`. |
343 | 8.74M | size_t index() const { return index_; } |
344 | | |
345 | | private: |
346 | | size_t mask_; |
347 | | size_t offset_; |
348 | | size_t index_ = 0; |
349 | | }; |
350 | | |
351 | | template <class ContainerKey, class Hash, class Eq> |
352 | | struct RequireUsableKey { |
353 | | template <class PassedKey, class... Args> |
354 | | std::pair< |
355 | | decltype(std::declval<const Hash&>()(std::declval<const PassedKey&>())), |
356 | | decltype(std::declval<const Eq&>()(std::declval<const ContainerKey&>(), |
357 | | std::declval<const PassedKey&>()))>* |
358 | | operator()(const PassedKey&, const Args&...) const; |
359 | | }; |
360 | | |
361 | | template <class E, class Policy, class Hash, class Eq, class... Ts> |
362 | | struct IsDecomposable : std::false_type {}; |
363 | | |
364 | | template <class Policy, class Hash, class Eq, class... Ts> |
365 | | struct IsDecomposable< |
366 | | absl::void_t<decltype(Policy::apply( |
367 | | RequireUsableKey<typename Policy::key_type, Hash, Eq>(), |
368 | | std::declval<Ts>()...))>, |
369 | | Policy, Hash, Eq, Ts...> : std::true_type {}; |
370 | | |
371 | | // TODO(alkis): Switch to std::is_nothrow_swappable when gcc/clang supports it. |
372 | | template <class T> |
373 | | constexpr bool IsNoThrowSwappable(std::true_type = {} /* is_swappable */) { |
374 | | using std::swap; |
375 | | return noexcept(swap(std::declval<T&>(), std::declval<T&>())); |
376 | | } |
377 | | template <class T> |
378 | | constexpr bool IsNoThrowSwappable(std::false_type /* is_swappable */) { |
379 | | return false; |
380 | | } |
381 | | |
382 | | ABSL_DLL extern ctrl_t kDefaultIterControl; |
383 | | |
384 | | // We use these sentinel capacity values in debug mode to indicate different |
385 | | // classes of bugs. |
386 | | enum InvalidCapacity : size_t { |
387 | | kAboveMaxValidCapacity = ~size_t{} - 100, |
388 | | kReentrance, |
389 | | kDestroyed, |
390 | | |
391 | | // These two must be last because we use `>= kMovedFrom` to mean moved-from. |
392 | | kMovedFrom, |
393 | | kSelfMovedFrom, |
394 | | }; |
395 | | |
396 | | // Returns a pointer to a control byte that can be used by default-constructed |
397 | | // iterators. We don't expect this pointer to be dereferenced. |
398 | 0 | inline ctrl_t* DefaultIterControl() { return &kDefaultIterControl; } |
399 | | |
400 | | // For use in SOO iterators. |
401 | | // TODO(b/289225379): we could potentially get rid of this by adding an is_soo |
402 | | // bit in iterators. This would add branches but reduce cache misses. |
403 | | ABSL_DLL extern const ctrl_t kSooControl[17]; |
404 | | |
405 | | // Returns a pointer to a full byte followed by a sentinel byte. |
406 | 259k | inline ctrl_t* SooControl() { |
407 | | // Const must be cast away here; no uses of this function will actually write |
408 | | // to it because it is only used for SOO iterators. |
409 | 259k | return const_cast<ctrl_t*>(kSooControl); |
410 | 259k | } |
411 | | // Whether ctrl is from the SooControl array. |
412 | 0 | inline bool IsSooControl(const ctrl_t* ctrl) { return ctrl == SooControl(); } |
413 | | |
414 | | // Returns a pointer to a generation to use for an empty hashtable. |
415 | | GenerationType* EmptyGeneration(); |
416 | | |
417 | | // Returns whether `generation` is a generation for an empty hashtable that |
418 | | // could be returned by EmptyGeneration(). |
419 | 0 | inline bool IsEmptyGeneration(const GenerationType* generation) { |
420 | 0 | return *generation == SentinelEmptyGeneration(); |
421 | 0 | } |
422 | | |
423 | | // We only allow a maximum of 1 SOO element, which makes the implementation |
424 | | // much simpler. Complications with multiple SOO elements include: |
425 | | // - Satisfying the guarantee that erasing one element doesn't invalidate |
426 | | // iterators to other elements means we would probably need actual SOO |
427 | | // control bytes. |
428 | | // - In order to prevent user code from depending on iteration order for small |
429 | | // tables, we would need to randomize the iteration order somehow. |
430 | 761k | constexpr size_t SooCapacity() { return 1; } |
431 | | // Sentinel type to indicate SOO CommonFields construction. |
432 | | struct soo_tag_t {}; |
433 | | // Sentinel type to indicate SOO CommonFields construction with full size. |
434 | | struct full_soo_tag_t {}; |
435 | | // Sentinel type to indicate non-SOO CommonFields construction. |
436 | | struct non_soo_tag_t {}; |
437 | | // Sentinel value to indicate an uninitialized value explicitly. |
438 | | struct uninitialized_tag_t {}; |
439 | | // Sentinel value to indicate creation of an empty table without a seed. |
440 | | struct no_seed_empty_tag_t {}; |
441 | | |
442 | | // Per table hash salt. This gets mixed into H1 to randomize iteration order |
443 | | // per-table. |
444 | | // The seed is needed to ensure non-determinism of iteration order. |
445 | | class PerTableSeed { |
446 | | public: |
447 | | // The number of bits in the seed. |
448 | | // It is big enough to ensure non-determinism of iteration order. |
449 | | // We store the seed inside a uint64_t together with size and other metadata. |
450 | | // Using 16 bits allows us to save one `and` instruction in H1 (we use |
451 | | // sign-extended move instead of mov+and). |
452 | | static constexpr size_t kBitCount = 16; |
453 | | static constexpr size_t kSignBit = uint64_t{1} << (kBitCount - 1); |
454 | | |
455 | | // Returns the seed for the table. |
456 | 76.0M | size_t seed() const { |
457 | | // We use a sign-extended load to ensure high bits are non-zero. |
458 | 76.0M | int16_t seed_signed = absl::bit_cast<int16_t>(seed_); |
459 | 76.0M | auto seed_sign_extended = |
460 | 76.0M | static_cast<std::make_signed_t<size_t>>(seed_signed); |
461 | 76.0M | return absl::bit_cast<size_t>(seed_sign_extended); |
462 | 76.0M | } |
463 | | |
464 | | private: |
465 | | friend class HashtableSize; |
466 | | explicit PerTableSeed(uint16_t seed) : seed_(seed) { |
467 | | ABSL_SWISSTABLE_ASSERT((seed & kSignBit) != 0 || seed == 0); |
468 | | } |
469 | | |
470 | | // The most significant bit of the seed is always 1 when there is a non-zero |
471 | | // seed. This way, when sign-extended the seed has non-zero high bits. |
472 | | const uint16_t seed_; |
473 | | }; |
474 | | |
475 | | // Returns next per-table seed. |
476 | 50.7k | inline uint16_t NextSeed() { |
477 | 50.7k | static_assert(PerTableSeed::kBitCount == 16); |
478 | 50.7k | thread_local uint16_t seed = |
479 | 50.7k | static_cast<uint16_t>(reinterpret_cast<uintptr_t>(&seed)); |
480 | 50.7k | seed += uint16_t{0xad53}; |
481 | 50.7k | return seed; |
482 | 50.7k | } |
483 | | |
484 | | // The size and also has additionally |
485 | | // 1) one bit that stores whether we have infoz. |
486 | | // 2) PerTableSeed::kBitCount bits for the seed. |
487 | | class HashtableSize { |
488 | | public: |
489 | | static constexpr size_t kSizeBitCount = 64 - PerTableSeed::kBitCount - 1; |
490 | | |
491 | 0 | explicit HashtableSize(uninitialized_tag_t) {} |
492 | 269k | explicit HashtableSize(no_seed_empty_tag_t) : data_(0) {} |
493 | 219k | explicit HashtableSize(full_soo_tag_t) : data_(kSizeOneNoMetadata) {} |
494 | | |
495 | | // Returns actual size of the table. |
496 | 10.2M | size_t size() const { return static_cast<size_t>(data_ >> kSizeShift); } |
497 | 8.71M | void increment_size() { data_ += kSizeOneNoMetadata; } |
498 | 0 | void increment_size(size_t size) { |
499 | 0 | data_ += static_cast<uint64_t>(size) * kSizeOneNoMetadata; |
500 | 0 | } |
501 | 0 | void decrement_size() { data_ -= kSizeOneNoMetadata; } |
502 | | // Returns true if the table is empty. |
503 | 0 | bool empty() const { return data_ < kSizeOneNoMetadata; } |
504 | | // Sets the size to zero, but keeps all the metadata bits. |
505 | 234k | void set_size_to_zero_keep_metadata() { data_ = data_ & kMetadataMask; } |
506 | | |
507 | 76.0M | PerTableSeed seed() const { |
508 | 76.0M | return PerTableSeed(static_cast<size_t>(data_) & kSeedMask); |
509 | 76.0M | } |
510 | | |
511 | 50.7k | void generate_new_seed() { set_seed(NextSeed()); } |
512 | | |
513 | | // We need to use a constant seed when the table is sampled so that sampled |
514 | | // hashes use the same seed and can e.g. identify stuck bits accurately. |
515 | 0 | void set_sampled_seed() { set_seed(PerTableSeed::kSignBit); } |
516 | | |
517 | 0 | bool is_sampled_seed() const { |
518 | 0 | return (data_ & kSeedMask) == PerTableSeed::kSignBit; |
519 | 0 | } |
520 | | |
521 | | // Returns true if the table has infoz. |
522 | 9.08M | bool has_infoz() const { |
523 | 9.08M | return ABSL_PREDICT_FALSE((data_ & kHasInfozMask) != 0); |
524 | 9.08M | } |
525 | | |
526 | | // Sets the has_infoz bit. |
527 | 0 | void set_has_infoz() { data_ |= kHasInfozMask; } |
528 | | |
529 | 0 | void set_no_seed_for_testing() { data_ &= ~kSeedMask; } |
530 | | |
531 | | private: |
532 | 50.7k | void set_seed(uint16_t seed) { |
533 | 50.7k | data_ = (data_ & ~kSeedMask) | (seed | PerTableSeed::kSignBit); |
534 | 50.7k | } |
535 | | static constexpr size_t kSizeShift = 64 - kSizeBitCount; |
536 | | static constexpr uint64_t kSizeOneNoMetadata = uint64_t{1} << kSizeShift; |
537 | | static constexpr uint64_t kMetadataMask = kSizeOneNoMetadata - 1; |
538 | | static constexpr uint64_t kSeedMask = |
539 | | (uint64_t{1} << PerTableSeed::kBitCount) - 1; |
540 | | // The next bit after the seed. |
541 | | static constexpr uint64_t kHasInfozMask = kSeedMask + 1; |
542 | | uint64_t data_; |
543 | | }; |
544 | | |
545 | | // H1 is just the low bits of the hash. |
546 | 75.9M | inline size_t H1(size_t hash) { return hash; } |
547 | | |
548 | | // Extracts the H2 portion of a hash: the 7 most significant bits. |
549 | | // |
550 | | // These are used as an occupied control byte. |
551 | 84.6M | inline h2_t H2(size_t hash) { return hash >> (sizeof(size_t) * 8 - 7); } |
552 | | |
553 | | // When there is an insertion with no reserved growth, we rehash with |
554 | | // probability `min(1, RehashProbabilityConstant() / capacity())`. Using a |
555 | | // constant divided by capacity ensures that inserting N elements is still O(N) |
556 | | // in the average case. Using the constant 16 means that we expect to rehash ~8 |
557 | | // times more often than when generations are disabled. We are adding expected |
558 | | // rehash_probability * #insertions/capacity_growth = 16/capacity * ((7/8 - |
559 | | // 7/16) * capacity)/capacity_growth = ~7 extra rehashes per capacity growth. |
560 | 0 | inline size_t RehashProbabilityConstant() { return 16; } |
561 | | |
562 | | class CommonFieldsGenerationInfoEnabled { |
563 | | // A sentinel value for reserved_growth_ indicating that we just ran out of |
564 | | // reserved growth on the last insertion. When reserve is called and then |
565 | | // insertions take place, reserved_growth_'s state machine is N, ..., 1, |
566 | | // kReservedGrowthJustRanOut, 0. |
567 | | static constexpr size_t kReservedGrowthJustRanOut = |
568 | | (std::numeric_limits<size_t>::max)(); |
569 | | |
570 | | public: |
571 | | CommonFieldsGenerationInfoEnabled() = default; |
572 | | CommonFieldsGenerationInfoEnabled(CommonFieldsGenerationInfoEnabled&& that) |
573 | | : reserved_growth_(that.reserved_growth_), |
574 | | reservation_size_(that.reservation_size_), |
575 | 0 | generation_(that.generation_) { |
576 | 0 | that.reserved_growth_ = 0; |
577 | 0 | that.reservation_size_ = 0; |
578 | 0 | that.generation_ = EmptyGeneration(); |
579 | 0 | } |
580 | | CommonFieldsGenerationInfoEnabled& operator=( |
581 | | CommonFieldsGenerationInfoEnabled&&) = default; |
582 | | |
583 | | // Whether we should rehash on insert in order to detect bugs of using invalid |
584 | | // references. We rehash on the first insertion after reserved_growth_ reaches |
585 | | // 0 after a call to reserve. We also do a rehash with low probability |
586 | | // whenever reserved_growth_ is zero. |
587 | | bool should_rehash_for_bug_detection_on_insert(size_t capacity) const; |
588 | | // Similar to above, except that we don't depend on reserved_growth_. |
589 | | bool should_rehash_for_bug_detection_on_move(size_t capacity) const; |
590 | 0 | void maybe_increment_generation_on_insert() { |
591 | 0 | if (reserved_growth_ == kReservedGrowthJustRanOut) reserved_growth_ = 0; |
592 | 0 |
|
593 | 0 | if (reserved_growth_ > 0) { |
594 | 0 | if (--reserved_growth_ == 0) reserved_growth_ = kReservedGrowthJustRanOut; |
595 | 0 | } else { |
596 | 0 | increment_generation(); |
597 | 0 | } |
598 | 0 | } |
599 | 0 | void increment_generation() { *generation_ = NextGeneration(*generation_); } |
600 | 0 | void reset_reserved_growth(size_t reservation, size_t size) { |
601 | 0 | reserved_growth_ = reservation - size; |
602 | 0 | } |
603 | 0 | size_t reserved_growth() const { return reserved_growth_; } |
604 | 0 | void set_reserved_growth(size_t r) { reserved_growth_ = r; } |
605 | 0 | size_t reservation_size() const { return reservation_size_; } |
606 | 0 | void set_reservation_size(size_t r) { reservation_size_ = r; } |
607 | 0 | GenerationType generation() const { return *generation_; } |
608 | 0 | void set_generation(GenerationType g) { *generation_ = g; } |
609 | 0 | GenerationType* generation_ptr() const { return generation_; } |
610 | 0 | void set_generation_ptr(GenerationType* g) { generation_ = g; } |
611 | | |
612 | | private: |
613 | | // The number of insertions remaining that are guaranteed to not rehash due to |
614 | | // a prior call to reserve. Note: we store reserved growth in addition to |
615 | | // reservation size because calls to erase() decrease size_ but don't decrease |
616 | | // reserved growth. |
617 | | size_t reserved_growth_ = 0; |
618 | | // The maximum argument to reserve() since the container was cleared. We need |
619 | | // to keep track of this, in addition to reserved growth, because we reset |
620 | | // reserved growth to this when erase(begin(), end()) is called. |
621 | | size_t reservation_size_ = 0; |
622 | | // Pointer to the generation counter, which is used to validate iterators and |
623 | | // is stored in the backing array between the control bytes and the slots. |
624 | | // Note that we can't store the generation inside the container itself and |
625 | | // keep a pointer to the container in the iterators because iterators must |
626 | | // remain valid when the container is moved. |
627 | | // Note: we could derive this pointer from the control pointer, but it makes |
628 | | // the code more complicated, and there's a benefit in having the sizes of |
629 | | // raw_hash_set in sanitizer mode and non-sanitizer mode a bit more different, |
630 | | // which is that tests are less likely to rely on the size remaining the same. |
631 | | GenerationType* generation_ = EmptyGeneration(); |
632 | | }; |
633 | | |
634 | | class CommonFieldsGenerationInfoDisabled { |
635 | | public: |
636 | | CommonFieldsGenerationInfoDisabled() = default; |
637 | | CommonFieldsGenerationInfoDisabled(CommonFieldsGenerationInfoDisabled&&) = |
638 | | default; |
639 | | CommonFieldsGenerationInfoDisabled& operator=( |
640 | | CommonFieldsGenerationInfoDisabled&&) = default; |
641 | | |
642 | 0 | bool should_rehash_for_bug_detection_on_insert(size_t) const { return false; } |
643 | 0 | bool should_rehash_for_bug_detection_on_move(size_t) const { return false; } |
644 | 8.71M | void maybe_increment_generation_on_insert() {} |
645 | 0 | void increment_generation() {} |
646 | 0 | void reset_reserved_growth(size_t, size_t) {} |
647 | 0 | size_t reserved_growth() const { return 0; } |
648 | | void set_reserved_growth(size_t) {} |
649 | 0 | size_t reservation_size() const { return 0; } |
650 | 573k | void set_reservation_size(size_t) {} |
651 | 203k | GenerationType generation() const { return 0; } |
652 | 203k | void set_generation(GenerationType) {} |
653 | | GenerationType* generation_ptr() const { return nullptr; } |
654 | 203k | void set_generation_ptr(GenerationType*) {} |
655 | | }; |
656 | | |
657 | | class HashSetIteratorGenerationInfoEnabled { |
658 | | public: |
659 | | HashSetIteratorGenerationInfoEnabled() = default; |
660 | | explicit HashSetIteratorGenerationInfoEnabled( |
661 | | const GenerationType* generation_ptr) |
662 | 0 | : generation_ptr_(generation_ptr), generation_(*generation_ptr) {} |
663 | | |
664 | 0 | GenerationType generation() const { return generation_; } |
665 | 0 | void reset_generation() { generation_ = *generation_ptr_; } |
666 | 0 | const GenerationType* generation_ptr() const { return generation_ptr_; } |
667 | 0 | void set_generation_ptr(const GenerationType* ptr) { generation_ptr_ = ptr; } |
668 | | |
669 | | private: |
670 | | const GenerationType* generation_ptr_ = EmptyGeneration(); |
671 | | GenerationType generation_ = *generation_ptr_; |
672 | | }; |
673 | | |
674 | | class HashSetIteratorGenerationInfoDisabled { |
675 | | public: |
676 | | HashSetIteratorGenerationInfoDisabled() = default; |
677 | | explicit HashSetIteratorGenerationInfoDisabled(const GenerationType*) {} |
678 | | |
679 | | GenerationType generation() const { return 0; } |
680 | 0 | void reset_generation() {} |
681 | | const GenerationType* generation_ptr() const { return nullptr; } |
682 | 0 | void set_generation_ptr(const GenerationType*) {} |
683 | | }; |
684 | | |
685 | | #ifdef ABSL_SWISSTABLE_ENABLE_GENERATIONS |
686 | | using CommonFieldsGenerationInfo = CommonFieldsGenerationInfoEnabled; |
687 | | using HashSetIteratorGenerationInfo = HashSetIteratorGenerationInfoEnabled; |
688 | | #else |
689 | | using CommonFieldsGenerationInfo = CommonFieldsGenerationInfoDisabled; |
690 | | using HashSetIteratorGenerationInfo = HashSetIteratorGenerationInfoDisabled; |
691 | | #endif |
692 | | |
693 | | // Stored the information regarding number of slots we can still fill |
694 | | // without needing to rehash. |
695 | | // |
696 | | // We want to ensure sufficient number of empty slots in the table in order |
697 | | // to keep probe sequences relatively short. Empty slot in the probe group |
698 | | // is required to stop probing. |
699 | | // |
700 | | // Tombstones (kDeleted slots) are not included in the growth capacity, |
701 | | // because we'd like to rehash when the table is filled with tombstones and/or |
702 | | // full slots. |
703 | | // |
704 | | // GrowthInfo also stores a bit that encodes whether table may have any |
705 | | // deleted slots. |
706 | | // Most of the tables (>95%) have no deleted slots, so some functions can |
707 | | // be more efficient with this information. |
708 | | // |
709 | | // Callers can also force a rehash via the standard `rehash(0)`, |
710 | | // which will recompute this value as a side-effect. |
711 | | // |
712 | | // See also `CapacityToGrowth()`. |
713 | | class GrowthInfo { |
714 | | public: |
715 | | // Leaves data member uninitialized. |
716 | | GrowthInfo() = default; |
717 | | |
718 | | // Initializes the GrowthInfo assuming we can grow `growth_left` elements |
719 | | // and there are no kDeleted slots in the table. |
720 | 438k | void InitGrowthLeftNoDeleted(size_t growth_left) { |
721 | 438k | growth_left_info_ = growth_left; |
722 | 438k | } |
723 | | |
724 | | // Overwrites single full slot with an empty slot. |
725 | 0 | void OverwriteFullAsEmpty() { ++growth_left_info_; } |
726 | | |
727 | | // Overwrites single empty slot with a full slot. |
728 | 8.51M | void OverwriteEmptyAsFull() { |
729 | 8.51M | ABSL_SWISSTABLE_ASSERT(GetGrowthLeft() > 0); |
730 | 8.51M | --growth_left_info_; |
731 | 8.51M | } |
732 | | |
733 | | // Overwrites several empty slots with full slots. |
734 | 0 | void OverwriteManyEmptyAsFull(size_t count) { |
735 | 0 | ABSL_SWISSTABLE_ASSERT(GetGrowthLeft() >= count); |
736 | 0 | growth_left_info_ -= count; |
737 | 0 | } |
738 | | |
739 | | // Overwrites specified control element with full slot. |
740 | 0 | void OverwriteControlAsFull(ctrl_t ctrl) { |
741 | 0 | ABSL_SWISSTABLE_ASSERT(GetGrowthLeft() >= |
742 | 0 | static_cast<size_t>(IsEmpty(ctrl))); |
743 | 0 | growth_left_info_ -= static_cast<size_t>(IsEmpty(ctrl)); |
744 | 0 | } |
745 | | |
746 | | // Overwrites single full slot with a deleted slot. |
747 | 0 | void OverwriteFullAsDeleted() { growth_left_info_ |= kDeletedBit; } |
748 | | |
749 | | // Returns true if table satisfies two properties: |
750 | | // 1. Guaranteed to have no kDeleted slots. |
751 | | // 2. There is a place for at least one element to grow. |
752 | 8.81M | bool HasNoDeletedAndGrowthLeft() const { |
753 | 8.81M | return static_cast<std::make_signed_t<size_t>>(growth_left_info_) > 0; |
754 | 8.81M | } |
755 | | |
756 | | // Returns true if the table satisfies two properties: |
757 | | // 1. Guaranteed to have no kDeleted slots. |
758 | | // 2. There is no growth left. |
759 | 153k | bool HasNoGrowthLeftAndNoDeleted() const { return growth_left_info_ == 0; } |
760 | | |
761 | | // Returns true if GetGrowthLeft() == 0, but must be called only if |
762 | | // HasNoDeleted() is false. It is slightly more efficient. |
763 | 0 | bool HasNoGrowthLeftAssumingMayHaveDeleted() const { |
764 | 0 | ABSL_SWISSTABLE_ASSERT(!HasNoDeleted()); |
765 | 0 | return growth_left_info_ == kDeletedBit; |
766 | 0 | } |
767 | | |
768 | | // Returns true if table guaranteed to have no kDeleted slots. |
769 | 153k | bool HasNoDeleted() const { |
770 | 153k | return static_cast<std::make_signed_t<size_t>>(growth_left_info_) >= 0; |
771 | 153k | } |
772 | | |
773 | | // Returns the number of elements left to grow. |
774 | 8.81M | size_t GetGrowthLeft() const { return growth_left_info_ & kGrowthLeftMask; } |
775 | | |
776 | | private: |
777 | | static constexpr size_t kGrowthLeftMask = ((~size_t{}) >> 1); |
778 | | static constexpr size_t kDeletedBit = ~kGrowthLeftMask; |
779 | | // Topmost bit signal whenever there are deleted slots. |
780 | | size_t growth_left_info_; |
781 | | }; |
782 | | |
783 | | static_assert(sizeof(GrowthInfo) == sizeof(size_t), ""); |
784 | | static_assert(alignof(GrowthInfo) == alignof(size_t), ""); |
785 | | |
786 | | // Returns whether `n` is a valid capacity (i.e., number of slots). |
787 | | // |
788 | | // A valid capacity is a non-zero integer `2^m - 1`. |
789 | 948k | constexpr bool IsValidCapacity(size_t n) { return ((n + 1) & n) == 0 && n > 0; } |
790 | | |
791 | | // Whether a table is small enough that we don't need to hash any keys. |
792 | 290M | constexpr bool IsSmallCapacity(size_t capacity) { return capacity <= 1; } |
793 | | |
794 | | // Returns the number of "cloned control bytes". |
795 | | // |
796 | | // This is the number of control bytes that are present both at the beginning |
797 | | // of the control byte array and at the end, such that we can create a |
798 | | // `Group::kWidth`-width probe window starting from any control byte. |
799 | 202M | constexpr size_t NumClonedBytes() { return Group::kWidth - 1; } |
800 | | |
801 | | // Returns the number of control bytes including cloned. |
802 | 185M | constexpr size_t NumControlBytes(size_t capacity) { |
803 | 185M | return IsSmallCapacity(capacity) ? 0 : capacity + 1 + NumClonedBytes(); |
804 | 185M | } |
805 | | |
806 | | // Computes the offset from the start of the backing allocation of control. |
807 | | // infoz and growth_info are stored at the beginning of the backing array. |
808 | 27.4M | constexpr size_t ControlOffset(bool has_infoz) { |
809 | 27.4M | return (has_infoz ? sizeof(HashtablezInfoHandle) : 0) + sizeof(GrowthInfo); |
810 | 27.4M | } |
811 | | |
812 | | // Returns the offset of the next item after `offset` that is aligned to `align` |
813 | | // bytes. `align` must be a power of two. |
814 | 611k | constexpr size_t AlignUpTo(size_t offset, size_t align) { |
815 | 611k | return (offset + align - 1) & (~align + 1); |
816 | 611k | } |
817 | | |
818 | | // Helper class for computing offsets and allocation size of hash set fields. |
819 | | class RawHashSetLayout { |
820 | | public: |
821 | | // TODO(b/413062340): maybe don't allocate growth info for capacity 1 tables. |
822 | | // Doing so may require additional branches/complexity so it might not be |
823 | | // worth it. |
824 | | explicit RawHashSetLayout(size_t capacity, size_t slot_size, |
825 | | size_t slot_align, bool has_infoz) |
826 | | : control_offset_(ControlOffset(has_infoz)), |
827 | | generation_offset_(control_offset_ + NumControlBytes(capacity)), |
828 | | slot_offset_( |
829 | | AlignUpTo(generation_offset_ + NumGenerationBytes(), slot_align)), |
830 | | alloc_size_(slot_offset_ + capacity * slot_size) { |
831 | | ABSL_SWISSTABLE_ASSERT(IsValidCapacity(capacity)); |
832 | | ABSL_SWISSTABLE_ASSERT( |
833 | | slot_size <= |
834 | | ((std::numeric_limits<size_t>::max)() - slot_offset_) / capacity); |
835 | | } |
836 | | |
837 | | // Returns precomputed offset from the start of the backing allocation of |
838 | | // control. |
839 | 611k | size_t control_offset() const { return control_offset_; } |
840 | | |
841 | | // Given the capacity of a table, computes the offset (from the start of the |
842 | | // backing allocation) of the generation counter (if it exists). |
843 | 203k | size_t generation_offset() const { return generation_offset_; } |
844 | | |
845 | | // Given the capacity of a table, computes the offset (from the start of the |
846 | | // backing allocation) at which the slots begin. |
847 | 203k | size_t slot_offset() const { return slot_offset_; } |
848 | | |
849 | | // Given the capacity of a table, computes the total size of the backing |
850 | | // array. |
851 | 815k | size_t alloc_size() const { return alloc_size_; } |
852 | | |
853 | | private: |
854 | | size_t control_offset_; |
855 | | size_t generation_offset_; |
856 | | size_t slot_offset_; |
857 | | size_t alloc_size_; |
858 | | }; |
859 | | |
860 | | struct HashtableFreeFunctionsAccess; |
861 | | |
862 | | // This allows us to work around an uninitialized memory warning when |
863 | | // constructing begin() iterators in empty hashtables. |
864 | | template <typename T> |
865 | | union MaybeInitializedPtr { |
866 | 303M | T* get() const { ABSL_SWISSTABLE_IGNORE_UNINITIALIZED_RETURN(p); } absl::container_internal::MaybeInitializedPtr<void>::get() const Line | Count | Source | 866 | 119M | T* get() const { ABSL_SWISSTABLE_IGNORE_UNINITIALIZED_RETURN(p); } |
absl::container_internal::MaybeInitializedPtr<absl::container_internal::ctrl_t>::get() const Line | Count | Source | 866 | 184M | T* get() const { ABSL_SWISSTABLE_IGNORE_UNINITIALIZED_RETURN(p); } |
|
867 | 407k | void set(T* ptr) { p = ptr; } absl::container_internal::MaybeInitializedPtr<absl::container_internal::ctrl_t>::set(absl::container_internal::ctrl_t*) Line | Count | Source | 867 | 203k | void set(T* ptr) { p = ptr; } |
absl::container_internal::MaybeInitializedPtr<void>::set(void*) Line | Count | Source | 867 | 203k | void set(T* ptr) { p = ptr; } |
|
868 | | |
869 | | T* p; |
870 | | }; |
871 | | |
872 | | struct HeapPtrs { |
873 | | // The control bytes (and, also, a pointer near to the base of the backing |
874 | | // array). |
875 | | // |
876 | | // This contains `capacity + 1 + NumClonedBytes()` entries. |
877 | | // |
878 | | // Note that growth_info is stored immediately before this pointer. |
879 | | // May be uninitialized for small tables. |
880 | | MaybeInitializedPtr<ctrl_t> control; |
881 | | |
882 | | // The beginning of the slots, located at `SlotOffset()` bytes after |
883 | | // `control`. May be uninitialized for empty tables. |
884 | | // Note: we can't use `slots` because Qt defines "slots" as a macro. |
885 | | MaybeInitializedPtr<void> slot_array; |
886 | | }; |
887 | | |
888 | | // Returns the maximum size of the SOO slot. |
889 | 0 | constexpr size_t MaxSooSlotSize() { return sizeof(HeapPtrs); } |
890 | | |
891 | | // Manages the backing array pointers or the SOO slot. When raw_hash_set::is_soo |
892 | | // is true, the SOO slot is stored in `soo_data`. Otherwise, we use `heap`. |
893 | | union HeapOrSoo { |
894 | 203k | MaybeInitializedPtr<ctrl_t>& control() { |
895 | 203k | ABSL_SWISSTABLE_IGNORE_UNINITIALIZED_RETURN(heap.control); |
896 | 203k | } |
897 | 185M | MaybeInitializedPtr<ctrl_t> control() const { |
898 | 185M | ABSL_SWISSTABLE_IGNORE_UNINITIALIZED_RETURN(heap.control); |
899 | 185M | } |
900 | 203k | MaybeInitializedPtr<void>& slot_array() { |
901 | 203k | ABSL_SWISSTABLE_IGNORE_UNINITIALIZED_RETURN(heap.slot_array); |
902 | 203k | } |
903 | 119M | MaybeInitializedPtr<void> slot_array() const { |
904 | 119M | ABSL_SWISSTABLE_IGNORE_UNINITIALIZED_RETURN(heap.slot_array); |
905 | 119M | } |
906 | 653k | void* get_soo_data() { |
907 | 653k | ABSL_SWISSTABLE_IGNORE_UNINITIALIZED_RETURN(soo_data); |
908 | 653k | } |
909 | 0 | const void* get_soo_data() const { |
910 | 0 | ABSL_SWISSTABLE_IGNORE_UNINITIALIZED_RETURN(soo_data); |
911 | 0 | } |
912 | | |
913 | | HeapPtrs heap; |
914 | | unsigned char soo_data[MaxSooSlotSize()]; |
915 | | }; |
916 | | |
917 | | // Returns a reference to the GrowthInfo object stored immediately before |
918 | | // `control`. |
919 | 17.9M | inline GrowthInfo& GetGrowthInfoFromControl(ctrl_t* control) { |
920 | 17.9M | auto* gl_ptr = reinterpret_cast<GrowthInfo*>(control) - 1; |
921 | 17.9M | ABSL_SWISSTABLE_ASSERT( |
922 | 17.9M | reinterpret_cast<uintptr_t>(gl_ptr) % alignof(GrowthInfo) == 0); |
923 | 17.9M | return *gl_ptr; |
924 | 17.9M | } |
925 | | |
926 | | // CommonFields hold the fields in raw_hash_set that do not depend |
927 | | // on template parameters. This allows us to conveniently pass all |
928 | | // of this state to helper functions as a single argument. |
929 | | class CommonFields : public CommonFieldsGenerationInfo { |
930 | | public: |
931 | | explicit CommonFields(soo_tag_t) |
932 | 104k | : capacity_(SooCapacity()), size_(no_seed_empty_tag_t{}) {} |
933 | | explicit CommonFields(full_soo_tag_t) |
934 | 0 | : capacity_(SooCapacity()), size_(full_soo_tag_t{}) {} |
935 | | explicit CommonFields(non_soo_tag_t) |
936 | 0 | : capacity_(0), size_(no_seed_empty_tag_t{}) {} |
937 | | // For use in swapping. |
938 | 0 | explicit CommonFields(uninitialized_tag_t) : size_(uninitialized_tag_t{}) {} |
939 | | |
940 | | // Not copyable |
941 | | CommonFields(const CommonFields&) = delete; |
942 | | CommonFields& operator=(const CommonFields&) = delete; |
943 | | |
944 | | // Copy with guarantee that it is not SOO. |
945 | | CommonFields(non_soo_tag_t, const CommonFields& that) |
946 | | : capacity_(that.capacity_), |
947 | | size_(that.size_), |
948 | 0 | heap_or_soo_(that.heap_or_soo_) { |
949 | 0 | } |
950 | | |
951 | | // Movable |
952 | | CommonFields(CommonFields&& that) = default; |
953 | | CommonFields& operator=(CommonFields&&) = default; |
954 | | |
955 | | template <bool kSooEnabled> |
956 | | static CommonFields CreateDefault() { |
957 | | return kSooEnabled ? CommonFields{soo_tag_t{}} |
958 | | : CommonFields{non_soo_tag_t{}}; |
959 | | } |
960 | | |
961 | | // The inline data for SOO is written on top of control_/slots_. |
962 | 0 | const void* soo_data() const { return heap_or_soo_.get_soo_data(); } |
963 | 653k | void* soo_data() { return heap_or_soo_.get_soo_data(); } |
964 | | |
965 | | ctrl_t* control() const { |
966 | | ABSL_SWISSTABLE_ASSERT(capacity() > 0); |
967 | | // Assume that the control bytes don't alias `this`. |
968 | | ctrl_t* ctrl = heap_or_soo_.control().get(); |
969 | | [[maybe_unused]] size_t num_control_bytes = NumControlBytes(capacity()); |
970 | | ABSL_ASSUME(reinterpret_cast<uintptr_t>(ctrl + num_control_bytes) <= |
971 | | reinterpret_cast<uintptr_t>(this) || |
972 | | reinterpret_cast<uintptr_t>(this + 1) <= |
973 | | reinterpret_cast<uintptr_t>(ctrl)); |
974 | | ABSL_SWISSTABLE_IGNORE_UNINITIALIZED_RETURN(ctrl); |
975 | | } |
976 | | |
977 | 203k | void set_control(ctrl_t* c) { heap_or_soo_.control().set(c); } |
978 | | |
979 | | // Note: we can't use slots() because Qt defines "slots" as a macro. |
980 | 119M | void* slot_array() const { return heap_or_soo_.slot_array().get(); } |
981 | | MaybeInitializedPtr<void> slots_union() const { |
982 | | return heap_or_soo_.slot_array(); |
983 | | } |
984 | 203k | void set_slots(void* s) { heap_or_soo_.slot_array().set(s); } |
985 | | |
986 | | // The number of filled slots. |
987 | 10.2M | size_t size() const { return size_.size(); } |
988 | | // Sets the size to zero, but keeps hashinfoz bit and seed. |
989 | 234k | void set_size_to_zero() { size_.set_size_to_zero_keep_metadata(); } |
990 | | void set_empty_soo() { |
991 | | AssertInSooMode(); |
992 | | size_ = HashtableSize(no_seed_empty_tag_t{}); |
993 | | } |
994 | 219k | void set_full_soo() { |
995 | 219k | AssertInSooMode(); |
996 | 219k | size_ = HashtableSize(full_soo_tag_t{}); |
997 | 219k | } |
998 | 8.71M | void increment_size() { |
999 | 8.71M | ABSL_SWISSTABLE_ASSERT(size() < capacity()); |
1000 | 8.71M | size_.increment_size(); |
1001 | 8.71M | } |
1002 | 0 | void increment_size(size_t n) { |
1003 | 0 | ABSL_SWISSTABLE_ASSERT(size() + n <= capacity()); |
1004 | 0 | size_.increment_size(n); |
1005 | 0 | } |
1006 | 0 | void decrement_size() { |
1007 | 0 | ABSL_SWISSTABLE_ASSERT(!empty()); |
1008 | 0 | size_.decrement_size(); |
1009 | 0 | } |
1010 | 0 | bool empty() const { return size_.empty(); } |
1011 | | |
1012 | | // The seed used for the hash function. |
1013 | 76.0M | PerTableSeed seed() const { return size_.seed(); } |
1014 | | // Generates a new seed the hash function. |
1015 | | // The table will be invalidated if `!empty()` because hash is being changed. |
1016 | | // In such cases, we will need to rehash the table. |
1017 | 50.7k | void generate_new_seed(bool has_infoz) { |
1018 | | // Note: we can't use has_infoz() here because we set has_infoz later than |
1019 | | // we generate the seed. |
1020 | 50.7k | if (ABSL_PREDICT_FALSE(has_infoz)) { |
1021 | 0 | size_.set_sampled_seed(); |
1022 | 0 | return; |
1023 | 0 | } |
1024 | 50.7k | size_.generate_new_seed(); |
1025 | 50.7k | } |
1026 | 0 | void set_no_seed_for_testing() { size_.set_no_seed_for_testing(); } |
1027 | | |
1028 | | // The total number of available slots. |
1029 | 317M | size_t capacity() const { return capacity_; } |
1030 | 203k | void set_capacity(size_t c) { |
1031 | | // We allow setting above the max valid capacity for debugging purposes. |
1032 | 203k | ABSL_SWISSTABLE_ASSERT(c == 0 || IsValidCapacity(c) || |
1033 | 203k | c > kAboveMaxValidCapacity); |
1034 | 203k | capacity_ = c; |
1035 | 203k | } |
1036 | 104M | bool is_small() const { return IsSmallCapacity(capacity_); } |
1037 | | |
1038 | | // The number of slots we can still fill without needing to rehash. |
1039 | | // This is stored in the heap allocation before the control bytes. |
1040 | | // TODO(b/289225379): experiment with moving growth_info back inline to |
1041 | | // increase room for SOO. |
1042 | 153k | size_t growth_left() const { return growth_info().GetGrowthLeft(); } |
1043 | | |
1044 | 17.7M | GrowthInfo& growth_info() { |
1045 | 17.7M | ABSL_SWISSTABLE_ASSERT(!is_small()); |
1046 | 17.7M | return GetGrowthInfoFromControl(control()); |
1047 | 17.7M | } |
1048 | 153k | GrowthInfo growth_info() const { |
1049 | 153k | return const_cast<CommonFields*>(this)->growth_info(); |
1050 | 153k | } |
1051 | | |
1052 | 9.08M | bool has_infoz() const { return size_.has_infoz(); } |
1053 | 0 | void set_has_infoz() { |
1054 | 0 | ABSL_SWISSTABLE_ASSERT(size_.is_sampled_seed()); |
1055 | 0 | size_.set_has_infoz(); |
1056 | 0 | } |
1057 | | |
1058 | 0 | HashtablezInfoHandle* infoz_ptr() const { |
1059 | | // growth_info is stored before control bytes. |
1060 | 0 | ABSL_SWISSTABLE_ASSERT( |
1061 | 0 | reinterpret_cast<uintptr_t>(control()) % alignof(size_t) == 0); |
1062 | 0 | ABSL_SWISSTABLE_ASSERT(has_infoz()); |
1063 | 0 | return reinterpret_cast<HashtablezInfoHandle*>( |
1064 | 0 | control() - ControlOffset(/*has_infoz=*/true)); |
1065 | 0 | } |
1066 | | |
1067 | 9.03M | HashtablezInfoHandle infoz() { |
1068 | 9.03M | return has_infoz() ? *infoz_ptr() : HashtablezInfoHandle(); |
1069 | 9.03M | } |
1070 | 0 | void set_infoz(HashtablezInfoHandle infoz) { |
1071 | 0 | ABSL_SWISSTABLE_ASSERT(has_infoz()); |
1072 | 0 | *infoz_ptr() = infoz; |
1073 | 0 | } |
1074 | | |
1075 | 0 | bool should_rehash_for_bug_detection_on_insert() const { |
1076 | 0 | if constexpr (!SwisstableGenerationsEnabled()) { |
1077 | 0 | return false; |
1078 | 0 | } |
1079 | 0 | // As an optimization, we avoid calling ShouldRehashForBugDetection if we |
1080 | 0 | // will end up rehashing anyways. |
1081 | 0 | if (growth_left() == 0) return false; |
1082 | 0 | return CommonFieldsGenerationInfo:: |
1083 | 0 | should_rehash_for_bug_detection_on_insert(capacity()); |
1084 | 0 | } |
1085 | 0 | bool should_rehash_for_bug_detection_on_move() const { |
1086 | 0 | return CommonFieldsGenerationInfo::should_rehash_for_bug_detection_on_move( |
1087 | 0 | capacity()); |
1088 | 0 | } |
1089 | 0 | void reset_reserved_growth(size_t reservation) { |
1090 | 0 | CommonFieldsGenerationInfo::reset_reserved_growth(reservation, size()); |
1091 | 0 | } |
1092 | | |
1093 | | // The size of the backing array allocation. |
1094 | 0 | size_t alloc_size(size_t slot_size, size_t slot_align) const { |
1095 | 0 | return RawHashSetLayout(capacity(), slot_size, slot_align, has_infoz()) |
1096 | 0 | .alloc_size(); |
1097 | 0 | } |
1098 | | |
1099 | | // Move fields other than heap_or_soo_. |
1100 | 0 | void move_non_heap_or_soo_fields(CommonFields& that) { |
1101 | 0 | static_cast<CommonFieldsGenerationInfo&>(*this) = |
1102 | 0 | std::move(static_cast<CommonFieldsGenerationInfo&>(that)); |
1103 | 0 | capacity_ = that.capacity_; |
1104 | 0 | size_ = that.size_; |
1105 | 0 | } |
1106 | | |
1107 | | // Returns the number of control bytes set to kDeleted. For testing only. |
1108 | 0 | size_t TombstonesCount() const { |
1109 | 0 | return static_cast<size_t>( |
1110 | 0 | std::count(control(), control() + capacity(), ctrl_t::kDeleted)); |
1111 | 0 | } |
1112 | | |
1113 | | // Helper to enable sanitizer mode validation to protect against reentrant |
1114 | | // calls during element constructor/destructor. |
1115 | | template <typename F> |
1116 | | void RunWithReentrancyGuard(F f) { |
1117 | | #ifdef NDEBUG |
1118 | | f(); |
1119 | | return; |
1120 | | #endif |
1121 | | const size_t cap = capacity(); |
1122 | | set_capacity(InvalidCapacity::kReentrance); |
1123 | | f(); |
1124 | | set_capacity(cap); |
1125 | | } |
1126 | | |
1127 | | private: |
1128 | | // We store the has_infoz bit in the lowest bit of size_. |
1129 | 0 | static constexpr size_t HasInfozShift() { return 1; } |
1130 | 0 | static constexpr size_t HasInfozMask() { |
1131 | 0 | return (size_t{1} << HasInfozShift()) - 1; |
1132 | 0 | } |
1133 | | |
1134 | | // We can't assert that SOO is enabled because we don't have SooEnabled(), but |
1135 | | // we assert what we can. |
1136 | | void AssertInSooMode() const { |
1137 | | ABSL_SWISSTABLE_ASSERT(capacity() == SooCapacity()); |
1138 | | ABSL_SWISSTABLE_ASSERT(!has_infoz()); |
1139 | | } |
1140 | | |
1141 | | // The number of slots in the backing array. This is always 2^N-1 for an |
1142 | | // integer N. NOTE: we tried experimenting with compressing the capacity and |
1143 | | // storing it together with size_: (a) using 6 bits to store the corresponding |
1144 | | // power (N in 2^N-1), and (b) storing 2^N as the most significant bit of |
1145 | | // size_ and storing size in the low bits. Both of these experiments were |
1146 | | // regressions, presumably because we need capacity to do find operations. |
1147 | | size_t capacity_; |
1148 | | |
1149 | | // TODO(b/289225379): we could put size_ into HeapOrSoo and make capacity_ |
1150 | | // encode the size in SOO case. We would be making size()/capacity() more |
1151 | | // expensive in order to have more SOO space. |
1152 | | HashtableSize size_; |
1153 | | |
1154 | | // Either the control/slots pointers or the SOO slot. |
1155 | | HeapOrSoo heap_or_soo_; |
1156 | | }; |
1157 | | |
1158 | | template <class Policy, class Hash, class Eq, class Alloc> |
1159 | | class raw_hash_set; |
1160 | | |
1161 | | // Returns the next valid capacity after `n`. |
1162 | 153k | constexpr size_t NextCapacity(size_t n) { |
1163 | 153k | ABSL_SWISSTABLE_ASSERT(IsValidCapacity(n) || n == 0); |
1164 | 153k | return n * 2 + 1; |
1165 | 153k | } |
1166 | | |
1167 | | // Returns the previous valid capacity before `n`. |
1168 | | constexpr size_t PreviousCapacity(size_t n) { |
1169 | | ABSL_SWISSTABLE_ASSERT(IsValidCapacity(n)); |
1170 | | return n / 2; |
1171 | | } |
1172 | | |
1173 | | // Applies the following mapping to every byte in the control array: |
1174 | | // * kDeleted -> kEmpty |
1175 | | // * kEmpty -> kEmpty |
1176 | | // * _ -> kDeleted |
1177 | | // PRECONDITION: |
1178 | | // IsValidCapacity(capacity) |
1179 | | // ctrl[capacity] == ctrl_t::kSentinel |
1180 | | // ctrl[i] != ctrl_t::kSentinel for all i < capacity |
1181 | | void ConvertDeletedToEmptyAndFullToDeleted(ctrl_t* ctrl, size_t capacity); |
1182 | | |
1183 | | // Converts `n` into the next valid capacity, per `IsValidCapacity`. |
1184 | 0 | constexpr size_t NormalizeCapacity(size_t n) { |
1185 | 0 | return n ? ~size_t{} >> countl_zero(n) : 1; |
1186 | 0 | } |
1187 | | |
1188 | | // General notes on capacity/growth methods below: |
1189 | | // - We use 7/8th as maximum load factor. For 16-wide groups, that gives an |
1190 | | // average of two empty slots per group. |
1191 | | // - For (capacity+1) >= Group::kWidth, growth is 7/8*capacity. |
1192 | | // - For (capacity+1) < Group::kWidth, growth == capacity. In this case, we |
1193 | | // never need to probe (the whole table fits in one group) so we don't need a |
1194 | | // load factor less than 1. |
1195 | | |
1196 | | // Given `capacity`, applies the load factor; i.e., it returns the maximum |
1197 | | // number of values we should put into the table before a resizing rehash. |
1198 | 387k | constexpr size_t CapacityToGrowth(size_t capacity) { |
1199 | 387k | ABSL_SWISSTABLE_ASSERT(IsValidCapacity(capacity)); |
1200 | | // `capacity*7/8` |
1201 | 387k | if (Group::kWidth == 8 && capacity == 7) { |
1202 | | // x-x/8 does not work when x==7. |
1203 | 0 | return 6; |
1204 | 0 | } |
1205 | 387k | return capacity - capacity / 8; |
1206 | 387k | } |
1207 | | |
1208 | | // Given `size`, "unapplies" the load factor to find how large the capacity |
1209 | | // should be to stay within the load factor. |
1210 | | // |
1211 | | // For size == 0, returns 0. |
1212 | | // For other values, returns the same as `NormalizeCapacity(size*8/7)`. |
1213 | 0 | constexpr size_t SizeToCapacity(size_t size) { |
1214 | 0 | if (size == 0) { |
1215 | 0 | return 0; |
1216 | 0 | } |
1217 | | // The minimum possible capacity is NormalizeCapacity(size). |
1218 | | // Shifting right `~size_t{}` by `leading_zeros` yields |
1219 | | // NormalizeCapacity(size). |
1220 | 0 | int leading_zeros = absl::countl_zero(size); |
1221 | 0 | constexpr size_t kLast3Bits = size_t{7} << (sizeof(size_t) * 8 - 3); |
1222 | | // max_size_for_next_capacity = max_load_factor * next_capacity |
1223 | | // = (7/8) * (~size_t{} >> leading_zeros) |
1224 | | // = (7/8*~size_t{}) >> leading_zeros |
1225 | | // = kLast3Bits >> leading_zeros |
1226 | 0 | size_t max_size_for_next_capacity = kLast3Bits >> leading_zeros; |
1227 | | // Decrease shift if size is too big for the minimum capacity. |
1228 | 0 | leading_zeros -= static_cast<int>(size > max_size_for_next_capacity); |
1229 | | if constexpr (Group::kWidth == 8) { |
1230 | | // Formula doesn't work when size==7 for 8-wide groups. |
1231 | | leading_zeros -= (size == 7); |
1232 | | } |
1233 | 0 | return (~size_t{}) >> leading_zeros; |
1234 | 0 | } |
1235 | | |
1236 | | template <class InputIter> |
1237 | | size_t SelectBucketCountForIterRange(InputIter first, InputIter last, |
1238 | | size_t bucket_count) { |
1239 | | if (bucket_count != 0) { |
1240 | | return bucket_count; |
1241 | | } |
1242 | | if (base_internal::IsAtLeastIterator<std::random_access_iterator_tag, |
1243 | | InputIter>()) { |
1244 | | return SizeToCapacity(static_cast<size_t>(std::distance(first, last))); |
1245 | | } |
1246 | | return 0; |
1247 | | } |
1248 | | |
1249 | 0 | constexpr bool SwisstableDebugEnabled() { |
1250 | 0 | #if defined(ABSL_SWISSTABLE_ENABLE_GENERATIONS) || \ |
1251 | 0 | ABSL_OPTION_HARDENED == 1 || !defined(NDEBUG) |
1252 | 0 | return true; |
1253 | 0 | #else |
1254 | 0 | return false; |
1255 | 0 | #endif |
1256 | 0 | } |
1257 | | |
1258 | | inline void AssertIsFull(const ctrl_t* ctrl, GenerationType generation, |
1259 | | const GenerationType* generation_ptr, |
1260 | | const char* operation) { |
1261 | | if (!SwisstableDebugEnabled()) return; |
1262 | | // `SwisstableDebugEnabled()` is also true for release builds with hardening |
1263 | | // enabled. To minimize their impact in those builds: |
1264 | | // - use `ABSL_PREDICT_FALSE()` to provide a compiler hint for code layout |
1265 | | // - use `ABSL_RAW_LOG()` with a format string to reduce code size and improve |
1266 | | // the chances that the hot paths will be inlined. |
1267 | | if (ABSL_PREDICT_FALSE(ctrl == nullptr)) { |
1268 | | ABSL_RAW_LOG(FATAL, "%s called on end() iterator.", operation); |
1269 | | } |
1270 | | if (ABSL_PREDICT_FALSE(ctrl == DefaultIterControl())) { |
1271 | | ABSL_RAW_LOG(FATAL, "%s called on default-constructed iterator.", |
1272 | | operation); |
1273 | | } |
1274 | | if (SwisstableGenerationsEnabled()) { |
1275 | | if (ABSL_PREDICT_FALSE(generation != *generation_ptr)) { |
1276 | | ABSL_RAW_LOG(FATAL, |
1277 | | "%s called on invalid iterator. The table could have " |
1278 | | "rehashed or moved since this iterator was initialized.", |
1279 | | operation); |
1280 | | } |
1281 | | if (ABSL_PREDICT_FALSE(!IsFull(*ctrl))) { |
1282 | | ABSL_RAW_LOG( |
1283 | | FATAL, |
1284 | | "%s called on invalid iterator. The element was likely erased.", |
1285 | | operation); |
1286 | | } |
1287 | | } else { |
1288 | | if (ABSL_PREDICT_FALSE(!IsFull(*ctrl))) { |
1289 | | ABSL_RAW_LOG( |
1290 | | FATAL, |
1291 | | "%s called on invalid iterator. The element might have been erased " |
1292 | | "or the table might have rehashed. Consider running with " |
1293 | | "--config=asan to diagnose rehashing issues.", |
1294 | | operation); |
1295 | | } |
1296 | | } |
1297 | | } |
1298 | | |
1299 | | // Note that for comparisons, null/end iterators are valid. |
1300 | | inline void AssertIsValidForComparison(const ctrl_t* ctrl, |
1301 | | GenerationType generation, |
1302 | | const GenerationType* generation_ptr) { |
1303 | | if (!SwisstableDebugEnabled()) return; |
1304 | | const bool ctrl_is_valid_for_comparison = |
1305 | | ctrl == nullptr || ctrl == DefaultIterControl() || IsFull(*ctrl); |
1306 | | if (SwisstableGenerationsEnabled()) { |
1307 | | if (ABSL_PREDICT_FALSE(generation != *generation_ptr)) { |
1308 | | ABSL_RAW_LOG(FATAL, |
1309 | | "Invalid iterator comparison. The table could have rehashed " |
1310 | | "or moved since this iterator was initialized."); |
1311 | | } |
1312 | | if (ABSL_PREDICT_FALSE(!ctrl_is_valid_for_comparison)) { |
1313 | | ABSL_RAW_LOG( |
1314 | | FATAL, "Invalid iterator comparison. The element was likely erased."); |
1315 | | } |
1316 | | } else { |
1317 | | ABSL_HARDENING_ASSERT_SLOW( |
1318 | | ctrl_is_valid_for_comparison && |
1319 | | "Invalid iterator comparison. The element might have been erased or " |
1320 | | "the table might have rehashed. Consider running with --config=asan to " |
1321 | | "diagnose rehashing issues."); |
1322 | | } |
1323 | | } |
1324 | | |
1325 | | // If the two iterators come from the same container, then their pointers will |
1326 | | // interleave such that ctrl_a <= ctrl_b < slot_a <= slot_b or vice/versa. |
1327 | | // Note: we take slots by reference so that it's not UB if they're uninitialized |
1328 | | // as long as we don't read them (when ctrl is null). |
1329 | | inline bool AreItersFromSameContainer(const ctrl_t* ctrl_a, |
1330 | | const ctrl_t* ctrl_b, |
1331 | | const void* const& slot_a, |
1332 | 0 | const void* const& slot_b) { |
1333 | 0 | // If either control byte is null, then we can't tell. |
1334 | 0 | if (ctrl_a == nullptr || ctrl_b == nullptr) return true; |
1335 | 0 | const bool a_is_soo = IsSooControl(ctrl_a); |
1336 | 0 | if (a_is_soo != IsSooControl(ctrl_b)) return false; |
1337 | 0 | if (a_is_soo) return slot_a == slot_b; |
1338 | 0 |
|
1339 | 0 | const void* low_slot = slot_a; |
1340 | 0 | const void* hi_slot = slot_b; |
1341 | 0 | if (ctrl_a > ctrl_b) { |
1342 | 0 | std::swap(ctrl_a, ctrl_b); |
1343 | 0 | std::swap(low_slot, hi_slot); |
1344 | 0 | } |
1345 | 0 | return ctrl_b < low_slot && low_slot <= hi_slot; |
1346 | 0 | } |
1347 | | |
1348 | | // Asserts that two iterators come from the same container. |
1349 | | // Note: we take slots by reference so that it's not UB if they're uninitialized |
1350 | | // as long as we don't read them (when ctrl is null). |
1351 | | inline void AssertSameContainer(const ctrl_t* ctrl_a, const ctrl_t* ctrl_b, |
1352 | | const void* const& slot_a, |
1353 | | const void* const& slot_b, |
1354 | | const GenerationType* generation_ptr_a, |
1355 | | const GenerationType* generation_ptr_b) { |
1356 | | if (!SwisstableDebugEnabled()) return; |
1357 | | // `SwisstableDebugEnabled()` is also true for release builds with hardening |
1358 | | // enabled. To minimize their impact in those builds: |
1359 | | // - use `ABSL_PREDICT_FALSE()` to provide a compiler hint for code layout |
1360 | | // - use `ABSL_RAW_LOG()` with a format string to reduce code size and improve |
1361 | | // the chances that the hot paths will be inlined. |
1362 | | |
1363 | | // fail_if(is_invalid, message) crashes when is_invalid is true and provides |
1364 | | // an error message based on `message`. |
1365 | | const auto fail_if = [](bool is_invalid, const char* message) { |
1366 | | if (ABSL_PREDICT_FALSE(is_invalid)) { |
1367 | | ABSL_RAW_LOG(FATAL, "Invalid iterator comparison. %s", message); |
1368 | | } |
1369 | | }; |
1370 | | |
1371 | | const bool a_is_default = ctrl_a == DefaultIterControl(); |
1372 | | const bool b_is_default = ctrl_b == DefaultIterControl(); |
1373 | | if (a_is_default && b_is_default) return; |
1374 | | fail_if(a_is_default != b_is_default, |
1375 | | "Comparing default-constructed hashtable iterator with a " |
1376 | | "non-default-constructed hashtable iterator."); |
1377 | | |
1378 | | if (SwisstableGenerationsEnabled()) { |
1379 | | if (ABSL_PREDICT_TRUE(generation_ptr_a == generation_ptr_b)) return; |
1380 | | // Users don't need to know whether the tables are SOO so don't mention SOO |
1381 | | // in the debug message. |
1382 | | const bool a_is_soo = IsSooControl(ctrl_a); |
1383 | | const bool b_is_soo = IsSooControl(ctrl_b); |
1384 | | fail_if(a_is_soo != b_is_soo || (a_is_soo && b_is_soo), |
1385 | | "Comparing iterators from different hashtables."); |
1386 | | |
1387 | | const bool a_is_empty = IsEmptyGeneration(generation_ptr_a); |
1388 | | const bool b_is_empty = IsEmptyGeneration(generation_ptr_b); |
1389 | | fail_if(a_is_empty != b_is_empty, |
1390 | | "Comparing an iterator from an empty hashtable with an iterator " |
1391 | | "from a non-empty hashtable."); |
1392 | | fail_if(a_is_empty && b_is_empty, |
1393 | | "Comparing iterators from different empty hashtables."); |
1394 | | |
1395 | | const bool a_is_end = ctrl_a == nullptr; |
1396 | | const bool b_is_end = ctrl_b == nullptr; |
1397 | | fail_if(a_is_end || b_is_end, |
1398 | | "Comparing iterator with an end() iterator from a different " |
1399 | | "hashtable."); |
1400 | | fail_if(true, "Comparing non-end() iterators from different hashtables."); |
1401 | | } else { |
1402 | | ABSL_HARDENING_ASSERT_SLOW( |
1403 | | AreItersFromSameContainer(ctrl_a, ctrl_b, slot_a, slot_b) && |
1404 | | "Invalid iterator comparison. The iterators may be from different " |
1405 | | "containers or the container might have rehashed or moved. Consider " |
1406 | | "running with --config=asan to diagnose issues."); |
1407 | | } |
1408 | | } |
1409 | | |
1410 | | struct FindInfo { |
1411 | | size_t offset; |
1412 | | size_t probe_length; |
1413 | | }; |
1414 | | |
1415 | | // Whether a table fits entirely into a probing group. |
1416 | | // Arbitrary order of elements in such tables is correct. |
1417 | 274k | constexpr bool is_single_group(size_t capacity) { |
1418 | 274k | return capacity <= Group::kWidth; |
1419 | 274k | } |
1420 | | |
1421 | | // Begins a probing operation on `common.control`, using `hash`. |
1422 | 68.6M | inline probe_seq<Group::kWidth> probe_h1(size_t capacity, size_t h1) { |
1423 | 68.6M | return probe_seq<Group::kWidth>(h1, capacity); |
1424 | 68.6M | } |
1425 | 68.4M | inline probe_seq<Group::kWidth> probe(size_t capacity, size_t hash) { |
1426 | 68.4M | return probe_h1(capacity, H1(hash)); |
1427 | 68.4M | } |
1428 | 68.4M | inline probe_seq<Group::kWidth> probe(const CommonFields& common, size_t hash) { |
1429 | 68.4M | return probe(common.capacity(), hash); |
1430 | 68.4M | } |
1431 | | |
1432 | | constexpr size_t kProbedElementIndexSentinel = ~size_t{}; |
1433 | | |
1434 | | // Implementation detail of transfer_unprobed_elements_to_next_capacity_fn. |
1435 | | // Tries to find the new index for an element whose hash corresponds to |
1436 | | // `h1` for growth to the next capacity. |
1437 | | // Returns kProbedElementIndexSentinel if full probing is required. |
1438 | | // |
1439 | | // If element is located in the first probing group in the table before growth, |
1440 | | // returns one of two positions: `old_index` or `old_index + old_capacity + 1`. |
1441 | | // |
1442 | | // Otherwise, we will try to insert it into the first probe group of the new |
1443 | | // table. We only attempt to do so if the first probe group is already |
1444 | | // initialized. |
1445 | | template <typename = void> |
1446 | | inline size_t TryFindNewIndexWithoutProbing(size_t h1, size_t old_index, |
1447 | | size_t old_capacity, |
1448 | | ctrl_t* new_ctrl, |
1449 | | size_t new_capacity) { |
1450 | | size_t index_diff = old_index - h1; |
1451 | | // The first probe group starts with h1 & capacity. |
1452 | | // All following groups start at (h1 + Group::kWidth * K) & capacity. |
1453 | | // We can find an index within the floating group as index_diff modulo |
1454 | | // Group::kWidth. |
1455 | | // Both old and new capacity are larger than Group::kWidth so we can avoid |
1456 | | // computing `& capacity`. |
1457 | | size_t in_floating_group_index = index_diff & (Group::kWidth - 1); |
1458 | | // By subtracting we will get the difference between the first probe group |
1459 | | // and the probe group corresponding to old_index. |
1460 | | index_diff -= in_floating_group_index; |
1461 | | if (ABSL_PREDICT_TRUE((index_diff & old_capacity) == 0)) { |
1462 | | size_t new_index = (h1 + in_floating_group_index) & new_capacity; |
1463 | | ABSL_ASSUME(new_index != kProbedElementIndexSentinel); |
1464 | | return new_index; |
1465 | | } |
1466 | | ABSL_SWISSTABLE_ASSERT(((old_index - h1) & old_capacity) >= Group::kWidth); |
1467 | | // Try to insert element into the first probe group. |
1468 | | // new_ctrl is not yet fully initialized so we can't use regular search via |
1469 | | // find_first_non_full. |
1470 | | |
1471 | | // We can search in the first probe group only if it is located in already |
1472 | | // initialized part of the table. |
1473 | | if (ABSL_PREDICT_FALSE((h1 & old_capacity) >= old_index)) { |
1474 | | return kProbedElementIndexSentinel; |
1475 | | } |
1476 | | size_t offset = h1 & new_capacity; |
1477 | | Group new_g(new_ctrl + offset); |
1478 | | if (auto mask = new_g.MaskNonFull(); ABSL_PREDICT_TRUE(mask)) { |
1479 | | size_t result = offset + mask.LowestBitSet(); |
1480 | | ABSL_ASSUME(result != kProbedElementIndexSentinel); |
1481 | | return result; |
1482 | | } |
1483 | | return kProbedElementIndexSentinel; |
1484 | | } |
1485 | | |
1486 | | // Extern template for inline function keeps possibility of inlining. |
1487 | | // When compiler decided to not inline, no symbols will be added to the |
1488 | | // corresponding translation unit. |
1489 | | extern template size_t TryFindNewIndexWithoutProbing(size_t h1, |
1490 | | size_t old_index, |
1491 | | size_t old_capacity, |
1492 | | ctrl_t* new_ctrl, |
1493 | | size_t new_capacity); |
1494 | | |
1495 | | // Sets sanitizer poisoning for slot corresponding to control byte being set. |
1496 | | inline void DoSanitizeOnSetCtrl(const CommonFields& c, size_t i, ctrl_t h, |
1497 | 8.73M | size_t slot_size) { |
1498 | 8.73M | ABSL_SWISSTABLE_ASSERT(i < c.capacity()); |
1499 | 8.73M | auto* slot_i = static_cast<const char*>(c.slot_array()) + i * slot_size; |
1500 | 8.73M | if (IsFull(h)) { |
1501 | 8.73M | SanitizerUnpoisonMemoryRegion(slot_i, slot_size); |
1502 | 8.73M | } else { |
1503 | 0 | SanitizerPoisonMemoryRegion(slot_i, slot_size); |
1504 | 0 | } |
1505 | 8.73M | } |
1506 | | |
1507 | | // Sets `ctrl[i]` to `h`. |
1508 | | // |
1509 | | // Unlike setting it directly, this function will perform bounds checks and |
1510 | | // mirror the value to the cloned tail if necessary. |
1511 | | inline void SetCtrl(const CommonFields& c, size_t i, ctrl_t h, |
1512 | 8.51M | size_t slot_size) { |
1513 | 8.51M | ABSL_SWISSTABLE_ASSERT(!c.is_small()); |
1514 | 8.51M | DoSanitizeOnSetCtrl(c, i, h, slot_size); |
1515 | 8.51M | ctrl_t* ctrl = c.control(); |
1516 | 8.51M | ctrl[i] = h; |
1517 | 8.51M | ctrl[((i - NumClonedBytes()) & c.capacity()) + |
1518 | 8.51M | (NumClonedBytes() & c.capacity())] = h; |
1519 | 8.51M | } |
1520 | | // Overload for setting to an occupied `h2_t` rather than a special `ctrl_t`. |
1521 | 8.51M | inline void SetCtrl(const CommonFields& c, size_t i, h2_t h, size_t slot_size) { |
1522 | 8.51M | SetCtrl(c, i, static_cast<ctrl_t>(h), slot_size); |
1523 | 8.51M | } |
1524 | | |
1525 | | // Like SetCtrl, but in a single group table, we can save some operations when |
1526 | | // setting the cloned control byte. |
1527 | | inline void SetCtrlInSingleGroupTable(const CommonFields& c, size_t i, ctrl_t h, |
1528 | 60.5k | size_t slot_size) { |
1529 | 60.5k | ABSL_SWISSTABLE_ASSERT(!c.is_small()); |
1530 | 60.5k | ABSL_SWISSTABLE_ASSERT(is_single_group(c.capacity())); |
1531 | 60.5k | DoSanitizeOnSetCtrl(c, i, h, slot_size); |
1532 | 60.5k | ctrl_t* ctrl = c.control(); |
1533 | 60.5k | ctrl[i] = h; |
1534 | 60.5k | ctrl[i + c.capacity() + 1] = h; |
1535 | 60.5k | } |
1536 | | // Overload for setting to an occupied `h2_t` rather than a special `ctrl_t`. |
1537 | | inline void SetCtrlInSingleGroupTable(const CommonFields& c, size_t i, h2_t h, |
1538 | 60.5k | size_t slot_size) { |
1539 | 60.5k | SetCtrlInSingleGroupTable(c, i, static_cast<ctrl_t>(h), slot_size); |
1540 | 60.5k | } |
1541 | | |
1542 | | // Like SetCtrl, but in a table with capacity >= Group::kWidth - 1, |
1543 | | // we can save some operations when setting the cloned control byte. |
1544 | | inline void SetCtrlInLargeTable(const CommonFields& c, size_t i, ctrl_t h, |
1545 | 162k | size_t slot_size) { |
1546 | 162k | ABSL_SWISSTABLE_ASSERT(c.capacity() >= Group::kWidth - 1); |
1547 | 162k | DoSanitizeOnSetCtrl(c, i, h, slot_size); |
1548 | 162k | ctrl_t* ctrl = c.control(); |
1549 | 162k | ctrl[i] = h; |
1550 | 162k | ctrl[((i - NumClonedBytes()) & c.capacity()) + NumClonedBytes()] = h; |
1551 | 162k | } |
1552 | | // Overload for setting to an occupied `h2_t` rather than a special `ctrl_t`. |
1553 | | inline void SetCtrlInLargeTable(const CommonFields& c, size_t i, h2_t h, |
1554 | 162k | size_t slot_size) { |
1555 | 162k | SetCtrlInLargeTable(c, i, static_cast<ctrl_t>(h), slot_size); |
1556 | 162k | } |
1557 | | |
1558 | | // growth_info (which is a size_t) is stored with the backing array. |
1559 | 0 | constexpr size_t BackingArrayAlignment(size_t align_of_slot) { |
1560 | 0 | return (std::max)(align_of_slot, alignof(GrowthInfo)); |
1561 | 0 | } |
1562 | | |
1563 | | // Returns the address of the ith slot in slots where each slot occupies |
1564 | | // slot_size. |
1565 | 292k | inline void* SlotAddress(void* slot_array, size_t slot, size_t slot_size) { |
1566 | 292k | return static_cast<void*>(static_cast<char*>(slot_array) + |
1567 | 292k | (slot * slot_size)); |
1568 | 292k | } |
1569 | | |
1570 | | // Iterates over all full slots and calls `cb(const ctrl_t*, void*)`. |
1571 | | // No insertion to the table is allowed during `cb` call. |
1572 | | // Erasure is allowed only for the element passed to the callback. |
1573 | | // The table must not be in SOO mode. |
1574 | | void IterateOverFullSlots(const CommonFields& c, size_t slot_size, |
1575 | | absl::FunctionRef<void(const ctrl_t*, void*)> cb); |
1576 | | |
1577 | | template <typename CharAlloc> |
1578 | | constexpr bool ShouldSampleHashtablezInfoForAlloc() { |
1579 | | // Folks with custom allocators often make unwarranted assumptions about the |
1580 | | // behavior of their classes vis-a-vis trivial destructability and what |
1581 | | // calls they will or won't make. Avoid sampling for people with custom |
1582 | | // allocators to get us out of this mess. This is not a hard guarantee but |
1583 | | // a workaround while we plan the exact guarantee we want to provide. |
1584 | | return std::is_same_v<CharAlloc, std::allocator<char>>; |
1585 | | } |
1586 | | |
1587 | | // Allocates `n` bytes for a backing array. |
1588 | | template <size_t AlignOfBackingArray, typename Alloc> |
1589 | | ABSL_ATTRIBUTE_NOINLINE void* AllocateBackingArray(void* alloc, size_t n) { |
1590 | | return Allocate<AlignOfBackingArray>(static_cast<Alloc*>(alloc), n); |
1591 | | } |
1592 | | |
1593 | | template <size_t AlignOfBackingArray, typename Alloc> |
1594 | | ABSL_ATTRIBUTE_NOINLINE void DeallocateBackingArray( |
1595 | | void* alloc, size_t capacity, ctrl_t* ctrl, size_t slot_size, |
1596 | | size_t slot_align, bool had_infoz) { |
1597 | | RawHashSetLayout layout(capacity, slot_size, slot_align, had_infoz); |
1598 | | void* backing_array = ctrl - layout.control_offset(); |
1599 | | // Unpoison before returning the memory to the allocator. |
1600 | | SanitizerUnpoisonMemoryRegion(backing_array, layout.alloc_size()); |
1601 | | Deallocate<AlignOfBackingArray>(static_cast<Alloc*>(alloc), backing_array, |
1602 | | layout.alloc_size()); |
1603 | | } |
1604 | | |
1605 | | // PolicyFunctions bundles together some information for a particular |
1606 | | // raw_hash_set<T, ...> instantiation. This information is passed to |
1607 | | // type-erased functions that want to do small amounts of type-specific |
1608 | | // work. |
1609 | | struct PolicyFunctions { |
1610 | | uint32_t key_size; |
1611 | | uint32_t value_size; |
1612 | | uint32_t slot_size; |
1613 | | uint16_t slot_align; |
1614 | | bool soo_enabled; |
1615 | | bool is_hashtablez_eligible; |
1616 | | |
1617 | | // Returns the pointer to the hash function stored in the set. |
1618 | | void* (*hash_fn)(CommonFields& common); |
1619 | | |
1620 | | // Returns the hash of the pointed-to slot. |
1621 | | HashSlotFn hash_slot; |
1622 | | |
1623 | | // Transfers the contents of `count` slots from src_slot to dst_slot. |
1624 | | // We use ability to transfer several slots in single group table growth. |
1625 | | void (*transfer_n)(void* set, void* dst_slot, void* src_slot, size_t count); |
1626 | | |
1627 | | // Returns the pointer to the CharAlloc stored in the set. |
1628 | | void* (*get_char_alloc)(CommonFields& common); |
1629 | | |
1630 | | // Allocates n bytes for the backing store for common. |
1631 | | void* (*alloc)(void* alloc, size_t n); |
1632 | | |
1633 | | // Deallocates the backing store from common. |
1634 | | void (*dealloc)(void* alloc, size_t capacity, ctrl_t* ctrl, size_t slot_size, |
1635 | | size_t slot_align, bool had_infoz); |
1636 | | |
1637 | | // Implementation detail of GrowToNextCapacity. |
1638 | | // Iterates over all full slots and transfers unprobed elements. |
1639 | | // Initializes the new control bytes except mirrored bytes and kSentinel. |
1640 | | // Caller must finish the initialization. |
1641 | | // All slots corresponding to the full control bytes are transferred. |
1642 | | // Probed elements are reported by `encode_probed_element` callback. |
1643 | | // encode_probed_element may overwrite old_ctrl buffer till source_offset. |
1644 | | // Different encoding is used depending on the capacity of the table. |
1645 | | // See ProbedItem*Bytes classes for details. |
1646 | | void (*transfer_unprobed_elements_to_next_capacity)( |
1647 | | CommonFields& common, const ctrl_t* old_ctrl, void* old_slots, |
1648 | | // TODO(b/382423690): Try to use absl::FunctionRef here. |
1649 | | void* probed_storage, |
1650 | | void (*encode_probed_element)(void* probed_storage, h2_t h2, |
1651 | | size_t source_offset, size_t h1)); |
1652 | | |
1653 | 407k | uint8_t soo_capacity() const { |
1654 | 407k | return static_cast<uint8_t>(soo_enabled ? SooCapacity() : 0); |
1655 | 407k | } |
1656 | | }; |
1657 | | |
1658 | | // Returns the maximum valid size for a table with 1-byte slots. |
1659 | | // This function is an utility shared by MaxValidSize and IsAboveValidSize. |
1660 | | // Template parameter is only used to enable testing. |
1661 | | template <size_t kSizeOfSizeT = sizeof(size_t)> |
1662 | 0 | constexpr size_t MaxValidSizeFor1ByteSlot() { |
1663 | 0 | if constexpr (kSizeOfSizeT == 8) { |
1664 | 0 | return CapacityToGrowth( |
1665 | 0 | static_cast<size_t>(uint64_t{1} << HashtableSize::kSizeBitCount) - 1); |
1666 | | } else { |
1667 | | static_assert(kSizeOfSizeT == 4); |
1668 | | return CapacityToGrowth((size_t{1} << (kSizeOfSizeT * 8 - 2)) - 1); |
1669 | | } |
1670 | 0 | } |
1671 | | |
1672 | | // Returns the maximum valid size for a table with provided slot size. |
1673 | | // Template parameter is only used to enable testing. |
1674 | | template <size_t kSizeOfSizeT = sizeof(size_t)> |
1675 | 0 | constexpr size_t MaxValidSize(size_t slot_size) { |
1676 | 0 | if constexpr (kSizeOfSizeT == 8) { |
1677 | | // For small slot sizes we are limited by HashtableSize::kSizeBitCount. |
1678 | 0 | if (slot_size < size_t{1} << (64 - HashtableSize::kSizeBitCount)) { |
1679 | 0 | return MaxValidSizeFor1ByteSlot<kSizeOfSizeT>(); |
1680 | 0 | } |
1681 | 0 | return (size_t{1} << (kSizeOfSizeT * 8 - 2)) / slot_size; |
1682 | | } else { |
1683 | | return MaxValidSizeFor1ByteSlot<kSizeOfSizeT>() / slot_size; |
1684 | | } |
1685 | 0 | } |
1686 | | |
1687 | | // Returns true if size is larger than the maximum valid size. |
1688 | | // It is an optimization to avoid the division operation in the common case. |
1689 | | // Template parameter is only used to enable testing. |
1690 | | template <size_t kSizeOfSizeT = sizeof(size_t)> |
1691 | 0 | constexpr bool IsAboveValidSize(size_t size, size_t slot_size) { |
1692 | 0 | if constexpr (kSizeOfSizeT == 8) { |
1693 | | // For small slot sizes we are limited by HashtableSize::kSizeBitCount. |
1694 | 0 | if (ABSL_PREDICT_TRUE(slot_size < |
1695 | 0 | (size_t{1} << (64 - HashtableSize::kSizeBitCount)))) { |
1696 | 0 | return size > MaxValidSizeFor1ByteSlot<kSizeOfSizeT>(); |
1697 | 0 | } |
1698 | 0 | return size > MaxValidSize<kSizeOfSizeT>(slot_size); |
1699 | | } else { |
1700 | | return uint64_t{size} * slot_size > |
1701 | | MaxValidSizeFor1ByteSlot<kSizeOfSizeT>(); |
1702 | | } |
1703 | 0 | } |
1704 | | |
1705 | | // Returns the index of the SOO slot when growing from SOO to non-SOO in a |
1706 | | // single group. See also InitializeSmallControlBytesAfterSoo(). It's important |
1707 | | // to use index 1 so that when resizing from capacity 1 to 3, we can still have |
1708 | | // random iteration order between the first two inserted elements. |
1709 | | // I.e. it allows inserting the second element at either index 0 or 2. |
1710 | 101k | constexpr size_t SooSlotIndex() { return 1; } |
1711 | | |
1712 | | // Maximum capacity for the algorithm for small table after SOO. |
1713 | | // Note that typical size after SOO is 3, but we allow up to 7. |
1714 | | // Allowing till 16 would require additional store that can be avoided. |
1715 | 0 | constexpr size_t MaxSmallAfterSooCapacity() { return 7; } |
1716 | | |
1717 | | // Type erased version of raw_hash_set::reserve. |
1718 | | // Requires: `new_size > policy.soo_capacity`. |
1719 | | void ReserveTableToFitNewSize(CommonFields& common, |
1720 | | const PolicyFunctions& policy, size_t new_size); |
1721 | | |
1722 | | // Resizes empty non-allocated table to the next valid capacity after |
1723 | | // `bucket_count`. Requires: |
1724 | | // 1. `c.capacity() == policy.soo_capacity`. |
1725 | | // 2. `c.empty()`. |
1726 | | // 3. `new_size > policy.soo_capacity`. |
1727 | | // The table will be attempted to be sampled. |
1728 | | void ReserveEmptyNonAllocatedTableToFitBucketCount( |
1729 | | CommonFields& common, const PolicyFunctions& policy, size_t bucket_count); |
1730 | | |
1731 | | // Type erased version of raw_hash_set::rehash. |
1732 | | void Rehash(CommonFields& common, const PolicyFunctions& policy, size_t n); |
1733 | | |
1734 | | // Type erased version of copy constructor. |
1735 | | void Copy(CommonFields& common, const PolicyFunctions& policy, |
1736 | | const CommonFields& other, |
1737 | | absl::FunctionRef<void(void*, const void*)> copy_fn); |
1738 | | |
1739 | | // Returns the optimal size for memcpy when transferring SOO slot. |
1740 | | // Otherwise, returns the optimal size for memcpy SOO slot transfer |
1741 | | // to SooSlotIndex(). |
1742 | | // At the destination we are allowed to copy upto twice more bytes, |
1743 | | // because there is at least one more slot after SooSlotIndex(). |
1744 | | // The result must not exceed MaxSooSlotSize(). |
1745 | | // Some of the cases are merged to minimize the number of function |
1746 | | // instantiations. |
1747 | | constexpr size_t OptimalMemcpySizeForSooSlotTransfer( |
1748 | 0 | size_t slot_size, size_t max_soo_slot_size = MaxSooSlotSize()) { |
1749 | 0 | static_assert(MaxSooSlotSize() >= 8, "unexpectedly small SOO slot size"); |
1750 | 0 | if (slot_size == 1) { |
1751 | 0 | return 1; |
1752 | 0 | } |
1753 | 0 | if (slot_size <= 3) { |
1754 | 0 | return 4; |
1755 | 0 | } |
1756 | 0 | // We are merging 4 and 8 into one case because we expect them to be the |
1757 | 0 | // hottest cases. Copying 8 bytes is as fast on common architectures. |
1758 | 0 | if (slot_size <= 8) { |
1759 | 0 | return 8; |
1760 | 0 | } |
1761 | 0 | if (max_soo_slot_size <= 16) { |
1762 | 0 | return max_soo_slot_size; |
1763 | 0 | } |
1764 | 0 | if (slot_size <= 16) { |
1765 | 0 | return 16; |
1766 | 0 | } |
1767 | 0 | if (max_soo_slot_size <= 24) { |
1768 | 0 | return max_soo_slot_size; |
1769 | 0 | } |
1770 | 0 | static_assert(MaxSooSlotSize() <= 24, "unexpectedly large SOO slot size"); |
1771 | 0 | return 24; |
1772 | 0 | } |
1773 | | |
1774 | | // Resizes SOO table to the NextCapacity(SooCapacity()) and prepares insert for |
1775 | | // the given new_hash. Returns the offset of the new element. |
1776 | | // All possible template combinations are defined in cc file to improve |
1777 | | // compilation time. |
1778 | | template <size_t SooSlotMemcpySize, bool TransferUsesMemcpy> |
1779 | | size_t GrowSooTableToNextCapacityAndPrepareInsert( |
1780 | | CommonFields& common, const PolicyFunctions& policy, |
1781 | | absl::FunctionRef<size_t(size_t)> get_hash, bool force_sampling); |
1782 | | |
1783 | | // PrepareInsert for small tables (is_small()==true). |
1784 | | // Returns the new control and the new slot. |
1785 | | // Hash is only computed if the table is sampled or grew to large size |
1786 | | // (is_small()==false). |
1787 | | std::pair<ctrl_t*, void*> PrepareInsertSmallNonSoo( |
1788 | | CommonFields& common, const PolicyFunctions& policy, |
1789 | | absl::FunctionRef<size_t(size_t)> get_hash); |
1790 | | |
1791 | | // Resizes table with allocated slots and change the table seed. |
1792 | | // Tables with SOO enabled must have capacity > policy.soo_capacity. |
1793 | | // No sampling will be performed since table is already allocated. |
1794 | | void ResizeAllocatedTableWithSeedChange(CommonFields& common, |
1795 | | const PolicyFunctions& policy, |
1796 | | size_t new_capacity); |
1797 | | |
1798 | | // ClearBackingArray clears the backing array, either modifying it in place, |
1799 | | // or creating a new one based on the value of "reuse". |
1800 | | // REQUIRES: c.capacity > 0 |
1801 | | void ClearBackingArray(CommonFields& c, const PolicyFunctions& policy, |
1802 | | void* alloc, bool reuse, bool soo_enabled); |
1803 | | |
1804 | | // Type-erased version of raw_hash_set::erase_meta_only. |
1805 | | void EraseMetaOnly(CommonFields& c, const ctrl_t* ctrl, size_t slot_size); |
1806 | | |
1807 | | // For trivially relocatable types we use memcpy directly. This allows us to |
1808 | | // share the same function body for raw_hash_set instantiations that have the |
1809 | | // same slot size as long as they are relocatable. |
1810 | | // Separate function for relocating single slot cause significant binary bloat. |
1811 | | template <size_t SizeOfSlot> |
1812 | | ABSL_ATTRIBUTE_NOINLINE void TransferNRelocatable(void*, void* dst, void* src, |
1813 | | size_t count) { |
1814 | | // TODO(b/382423690): Experiment with making specialization for power of 2 and |
1815 | | // non power of 2. This would require passing the size of the slot. |
1816 | | memcpy(dst, src, SizeOfSlot * count); |
1817 | | } |
1818 | | |
1819 | | // Returns a pointer to `common`. This is used to implement type erased |
1820 | | // raw_hash_set::get_hash_ref_fn and raw_hash_set::get_alloc_ref_fn for the |
1821 | | // empty class cases. |
1822 | | void* GetRefForEmptyClass(CommonFields& common); |
1823 | | |
1824 | | // Given the hash of a value not currently in the table and the first empty |
1825 | | // slot in the probe sequence, finds a viable slot index to insert it at. |
1826 | | // |
1827 | | // In case there's no space left, the table can be resized or rehashed |
1828 | | // (for tables with deleted slots, see FindInsertPositionWithGrowthOrRehash). |
1829 | | // |
1830 | | // In the case of absence of deleted slots and positive growth_left, the element |
1831 | | // can be inserted in the provided `target` position. |
1832 | | // |
1833 | | // When the table has deleted slots (according to GrowthInfo), the target |
1834 | | // position will be searched one more time using `find_first_non_full`. |
1835 | | // |
1836 | | // REQUIRES: `!common.is_small()`. |
1837 | | // REQUIRES: At least one non-full slot available. |
1838 | | // REQUIRES: `target` is a valid empty position to insert. |
1839 | | size_t PrepareInsertLarge(CommonFields& common, const PolicyFunctions& policy, |
1840 | | size_t hash, FindInfo target); |
1841 | | |
1842 | | // Same as above, but with generations enabled, we may end up changing the seed, |
1843 | | // which means we need to be able to recompute the hash. |
1844 | | size_t PrepareInsertLargeGenerationsEnabled( |
1845 | | CommonFields& common, const PolicyFunctions& policy, size_t hash, |
1846 | | FindInfo target, absl::FunctionRef<size_t(size_t)> recompute_hash); |
1847 | | |
1848 | | // A SwissTable. |
1849 | | // |
1850 | | // Policy: a policy defines how to perform different operations on |
1851 | | // the slots of the hashtable (see hash_policy_traits.h for the full interface |
1852 | | // of policy). |
1853 | | // |
1854 | | // Hash: a (possibly polymorphic) functor that hashes keys of the hashtable. The |
1855 | | // functor should accept a key and return size_t as hash. For best performance |
1856 | | // it is important that the hash function provides high entropy across all bits |
1857 | | // of the hash. |
1858 | | // |
1859 | | // Eq: a (possibly polymorphic) functor that compares two keys for equality. It |
1860 | | // should accept two (of possibly different type) keys and return a bool: true |
1861 | | // if they are equal, false if they are not. If two keys compare equal, then |
1862 | | // their hash values as defined by Hash MUST be equal. |
1863 | | // |
1864 | | // Allocator: an Allocator |
1865 | | // [https://en.cppreference.com/w/cpp/named_req/Allocator] with which |
1866 | | // the storage of the hashtable will be allocated and the elements will be |
1867 | | // constructed and destroyed. |
1868 | | template <class Policy, class Hash, class Eq, class Alloc> |
1869 | | class raw_hash_set { |
1870 | | using PolicyTraits = hash_policy_traits<Policy>; |
1871 | | using KeyArgImpl = |
1872 | | KeyArg<IsTransparent<Eq>::value && IsTransparent<Hash>::value>; |
1873 | | |
1874 | | public: |
1875 | | using init_type = typename PolicyTraits::init_type; |
1876 | | using key_type = typename PolicyTraits::key_type; |
1877 | | using allocator_type = Alloc; |
1878 | | using size_type = size_t; |
1879 | | using difference_type = ptrdiff_t; |
1880 | | using hasher = Hash; |
1881 | | using key_equal = Eq; |
1882 | | using policy_type = Policy; |
1883 | | using value_type = typename PolicyTraits::value_type; |
1884 | | using reference = value_type&; |
1885 | | using const_reference = const value_type&; |
1886 | | using pointer = typename absl::allocator_traits< |
1887 | | allocator_type>::template rebind_traits<value_type>::pointer; |
1888 | | using const_pointer = typename absl::allocator_traits< |
1889 | | allocator_type>::template rebind_traits<value_type>::const_pointer; |
1890 | | |
1891 | | private: |
1892 | | // Alias used for heterogeneous lookup functions. |
1893 | | // `key_arg<K>` evaluates to `K` when the functors are transparent and to |
1894 | | // `key_type` otherwise. It permits template argument deduction on `K` for the |
1895 | | // transparent case. |
1896 | | template <class K> |
1897 | | using key_arg = typename KeyArgImpl::template type<K, key_type>; |
1898 | | |
1899 | | using slot_type = typename PolicyTraits::slot_type; |
1900 | | |
1901 | | constexpr static bool kIsDefaultHash = |
1902 | | std::is_same_v<hasher, absl::Hash<key_type>> || |
1903 | | std::is_same_v<hasher, absl::container_internal::StringHash>; |
1904 | | |
1905 | | // TODO(b/289225379): we could add extra SOO space inside raw_hash_set |
1906 | | // after CommonFields to allow inlining larger slot_types (e.g. std::string), |
1907 | | // but it's a bit complicated if we want to support incomplete mapped_type in |
1908 | | // flat_hash_map. We could potentially do this for flat_hash_set and for an |
1909 | | // allowlist of `mapped_type`s of flat_hash_map that includes e.g. arithmetic |
1910 | | // types, strings, cords, and pairs/tuples of allowlisted types. |
1911 | | constexpr static bool SooEnabled() { |
1912 | | return PolicyTraits::soo_enabled() && |
1913 | | sizeof(slot_type) <= sizeof(HeapOrSoo) && |
1914 | | alignof(slot_type) <= alignof(HeapOrSoo); |
1915 | | } |
1916 | | |
1917 | | constexpr static size_t DefaultCapacity() { |
1918 | | return SooEnabled() ? SooCapacity() : 0; |
1919 | | } |
1920 | | |
1921 | | // Whether `size` fits in the SOO capacity of this table. |
1922 | | bool fits_in_soo(size_t size) const { |
1923 | | return SooEnabled() && size <= SooCapacity(); |
1924 | | } |
1925 | | // Whether this table is in SOO mode or non-SOO mode. |
1926 | | bool is_soo() const { return fits_in_soo(capacity()); } |
1927 | | bool is_full_soo() const { return is_soo() && !empty(); } |
1928 | | |
1929 | | bool is_small() const { return common().is_small(); } |
1930 | | |
1931 | | // Give an early error when key_type is not hashable/eq. |
1932 | | auto KeyTypeCanBeHashed(const Hash& h, const key_type& k) -> decltype(h(k)); |
1933 | | auto KeyTypeCanBeEq(const Eq& eq, const key_type& k) -> decltype(eq(k, k)); |
1934 | | |
1935 | | using AllocTraits = absl::allocator_traits<allocator_type>; |
1936 | | using SlotAlloc = typename absl::allocator_traits< |
1937 | | allocator_type>::template rebind_alloc<slot_type>; |
1938 | | // People are often sloppy with the exact type of their allocator (sometimes |
1939 | | // it has an extra const or is missing the pair, but rebinds made it work |
1940 | | // anyway). |
1941 | | using CharAlloc = |
1942 | | typename absl::allocator_traits<Alloc>::template rebind_alloc<char>; |
1943 | | using SlotAllocTraits = typename absl::allocator_traits< |
1944 | | allocator_type>::template rebind_traits<slot_type>; |
1945 | | |
1946 | | static_assert(std::is_lvalue_reference<reference>::value, |
1947 | | "Policy::element() must return a reference"); |
1948 | | |
1949 | | // An enabler for insert(T&&): T must be convertible to init_type or be the |
1950 | | // same as [cv] value_type [ref]. |
1951 | | template <class T> |
1952 | | using Insertable = absl::disjunction< |
1953 | | std::is_same<absl::remove_cvref_t<reference>, absl::remove_cvref_t<T>>, |
1954 | | std::is_convertible<T, init_type>>; |
1955 | | template <class T> |
1956 | | using IsNotBitField = std::is_pointer<T*>; |
1957 | | |
1958 | | // RequiresNotInit is a workaround for gcc prior to 7.1. |
1959 | | // See https://godbolt.org/g/Y4xsUh. |
1960 | | template <class T> |
1961 | | using RequiresNotInit = |
1962 | | typename std::enable_if<!std::is_same<T, init_type>::value, int>::type; |
1963 | | |
1964 | | template <class... Ts> |
1965 | | using IsDecomposable = IsDecomposable<void, PolicyTraits, Hash, Eq, Ts...>; |
1966 | | |
1967 | | template <class T> |
1968 | | using IsDecomposableAndInsertable = |
1969 | | IsDecomposable<std::enable_if_t<Insertable<T>::value, T>>; |
1970 | | |
1971 | | // Evaluates to true if an assignment from the given type would require the |
1972 | | // source object to remain alive for the life of the element. |
1973 | | template <class U> |
1974 | | using IsLifetimeBoundAssignmentFrom = std::conditional_t< |
1975 | | policy_trait_element_is_owner<Policy>::value, std::false_type, |
1976 | | type_traits_internal::IsLifetimeBoundAssignment<init_type, U>>; |
1977 | | |
1978 | | public: |
1979 | | static_assert(std::is_same<pointer, value_type*>::value, |
1980 | | "Allocators with custom pointer types are not supported"); |
1981 | | static_assert(std::is_same<const_pointer, const value_type*>::value, |
1982 | | "Allocators with custom pointer types are not supported"); |
1983 | | |
1984 | | class iterator : private HashSetIteratorGenerationInfo { |
1985 | | friend class raw_hash_set; |
1986 | | friend struct HashtableFreeFunctionsAccess; |
1987 | | |
1988 | | public: |
1989 | | using iterator_category = std::forward_iterator_tag; |
1990 | | using value_type = typename raw_hash_set::value_type; |
1991 | | using reference = |
1992 | | absl::conditional_t<PolicyTraits::constant_iterators::value, |
1993 | | const value_type&, value_type&>; |
1994 | | using pointer = absl::remove_reference_t<reference>*; |
1995 | | using difference_type = typename raw_hash_set::difference_type; |
1996 | | |
1997 | | iterator() {} |
1998 | | |
1999 | | // PRECONDITION: not an end() iterator. |
2000 | | reference operator*() const { |
2001 | | AssertIsFull(ctrl_, generation(), generation_ptr(), "operator*()"); |
2002 | | return unchecked_deref(); |
2003 | | } |
2004 | | |
2005 | | // PRECONDITION: not an end() iterator. |
2006 | | pointer operator->() const { |
2007 | | AssertIsFull(ctrl_, generation(), generation_ptr(), "operator->"); |
2008 | | return &operator*(); |
2009 | | } |
2010 | | |
2011 | | // PRECONDITION: not an end() iterator. |
2012 | | iterator& operator++() { |
2013 | | AssertIsFull(ctrl_, generation(), generation_ptr(), "operator++"); |
2014 | | ++ctrl_; |
2015 | | ++slot_; |
2016 | | skip_empty_or_deleted(); |
2017 | | if (ABSL_PREDICT_FALSE(*ctrl_ == ctrl_t::kSentinel)) ctrl_ = nullptr; |
2018 | | return *this; |
2019 | | } |
2020 | | // PRECONDITION: not an end() iterator. |
2021 | | iterator operator++(int) { |
2022 | | auto tmp = *this; |
2023 | | ++*this; |
2024 | | return tmp; |
2025 | | } |
2026 | | |
2027 | | friend bool operator==(const iterator& a, const iterator& b) { |
2028 | | AssertIsValidForComparison(a.ctrl_, a.generation(), a.generation_ptr()); |
2029 | | AssertIsValidForComparison(b.ctrl_, b.generation(), b.generation_ptr()); |
2030 | | AssertSameContainer(a.ctrl_, b.ctrl_, a.slot_, b.slot_, |
2031 | | a.generation_ptr(), b.generation_ptr()); |
2032 | | return a.ctrl_ == b.ctrl_; |
2033 | | } |
2034 | | friend bool operator!=(const iterator& a, const iterator& b) { |
2035 | | return !(a == b); |
2036 | | } |
2037 | | |
2038 | | private: |
2039 | | iterator(ctrl_t* ctrl, slot_type* slot, |
2040 | | const GenerationType* generation_ptr) |
2041 | | : HashSetIteratorGenerationInfo(generation_ptr), |
2042 | | ctrl_(ctrl), |
2043 | | slot_(slot) { |
2044 | | // This assumption helps the compiler know that any non-end iterator is |
2045 | | // not equal to any end iterator. |
2046 | | ABSL_ASSUME(ctrl != nullptr); |
2047 | | } |
2048 | | // This constructor is used in begin() to avoid an MSan |
2049 | | // use-of-uninitialized-value error. Delegating from this constructor to |
2050 | | // the previous one doesn't avoid the error. |
2051 | | iterator(ctrl_t* ctrl, MaybeInitializedPtr<void> slot, |
2052 | | const GenerationType* generation_ptr) |
2053 | | : HashSetIteratorGenerationInfo(generation_ptr), |
2054 | | ctrl_(ctrl), |
2055 | | slot_(to_slot(slot.get())) { |
2056 | | // This assumption helps the compiler know that any non-end iterator is |
2057 | | // not equal to any end iterator. |
2058 | | ABSL_ASSUME(ctrl != nullptr); |
2059 | | } |
2060 | | // For end() iterators. |
2061 | | explicit iterator(const GenerationType* generation_ptr) |
2062 | | : HashSetIteratorGenerationInfo(generation_ptr), ctrl_(nullptr) {} |
2063 | | |
2064 | | // Fixes up `ctrl_` to point to a full or sentinel by advancing `ctrl_` and |
2065 | | // `slot_` until they reach one. |
2066 | | void skip_empty_or_deleted() { |
2067 | | while (IsEmptyOrDeleted(*ctrl_)) { |
2068 | | auto mask = GroupFullEmptyOrDeleted{ctrl_}.MaskFullOrSentinel(); |
2069 | | // Generally it is possible to compute `shift` branchless. |
2070 | | // This branch is useful to: |
2071 | | // 1. Avoid checking `IsEmptyOrDeleted` after the shift for the most |
2072 | | // common dense table case. |
2073 | | // 2. Avoid the cost of `LowestBitSet` for extremely sparse tables. |
2074 | | if (ABSL_PREDICT_TRUE(mask)) { |
2075 | | auto shift = mask.LowestBitSet(); |
2076 | | ctrl_ += shift; |
2077 | | slot_ += shift; |
2078 | | return; |
2079 | | } |
2080 | | ctrl_ += Group::kWidth; |
2081 | | slot_ += Group::kWidth; |
2082 | | } |
2083 | | } |
2084 | | |
2085 | | ctrl_t* control() const { return ctrl_; } |
2086 | | slot_type* slot() const { return slot_; } |
2087 | | |
2088 | | // We use DefaultIterControl() for default-constructed iterators so that |
2089 | | // they can be distinguished from end iterators, which have nullptr ctrl_. |
2090 | | ctrl_t* ctrl_ = DefaultIterControl(); |
2091 | | // To avoid uninitialized member warnings, put slot_ in an anonymous union. |
2092 | | // The member is not initialized on singleton and end iterators. |
2093 | | union { |
2094 | | slot_type* slot_; |
2095 | | }; |
2096 | | |
2097 | | // An equality check which skips ABSL Hardening iterator invalidation |
2098 | | // checks. |
2099 | | // Should be used when the lifetimes of the iterators are well-enough |
2100 | | // understood to prove that they cannot be invalid. |
2101 | | bool unchecked_equals(const iterator& b) { return ctrl_ == b.control(); } |
2102 | | |
2103 | | // Dereferences the iterator without ABSL Hardening iterator invalidation |
2104 | | // checks. |
2105 | | reference unchecked_deref() const { return PolicyTraits::element(slot_); } |
2106 | | }; |
2107 | | |
2108 | | class const_iterator { |
2109 | | friend class raw_hash_set; |
2110 | | template <class Container, typename Enabler> |
2111 | | friend struct absl::container_internal::hashtable_debug_internal:: |
2112 | | HashtableDebugAccess; |
2113 | | |
2114 | | public: |
2115 | | using iterator_category = typename iterator::iterator_category; |
2116 | | using value_type = typename raw_hash_set::value_type; |
2117 | | using reference = typename raw_hash_set::const_reference; |
2118 | | using pointer = typename raw_hash_set::const_pointer; |
2119 | | using difference_type = typename raw_hash_set::difference_type; |
2120 | | |
2121 | | const_iterator() = default; |
2122 | | // Implicit construction from iterator. |
2123 | | const_iterator(iterator i) : inner_(std::move(i)) {} // NOLINT |
2124 | | |
2125 | | reference operator*() const { return *inner_; } |
2126 | | pointer operator->() const { return inner_.operator->(); } |
2127 | | |
2128 | | const_iterator& operator++() { |
2129 | | ++inner_; |
2130 | | return *this; |
2131 | | } |
2132 | | const_iterator operator++(int) { return inner_++; } |
2133 | | |
2134 | | friend bool operator==(const const_iterator& a, const const_iterator& b) { |
2135 | | return a.inner_ == b.inner_; |
2136 | | } |
2137 | | friend bool operator!=(const const_iterator& a, const const_iterator& b) { |
2138 | | return !(a == b); |
2139 | | } |
2140 | | |
2141 | | private: |
2142 | | const_iterator(const ctrl_t* ctrl, const slot_type* slot, |
2143 | | const GenerationType* gen) |
2144 | | : inner_(const_cast<ctrl_t*>(ctrl), const_cast<slot_type*>(slot), gen) { |
2145 | | } |
2146 | | ctrl_t* control() const { return inner_.control(); } |
2147 | | slot_type* slot() const { return inner_.slot(); } |
2148 | | |
2149 | | iterator inner_; |
2150 | | |
2151 | | bool unchecked_equals(const const_iterator& b) { |
2152 | | return inner_.unchecked_equals(b.inner_); |
2153 | | } |
2154 | | }; |
2155 | | |
2156 | | using node_type = node_handle<Policy, hash_policy_traits<Policy>, Alloc>; |
2157 | | using insert_return_type = InsertReturnType<iterator, node_type>; |
2158 | | |
2159 | | // Note: can't use `= default` due to non-default noexcept (causes |
2160 | | // problems for some compilers). NOLINTNEXTLINE |
2161 | | raw_hash_set() noexcept( |
2162 | | std::is_nothrow_default_constructible<hasher>::value && |
2163 | | std::is_nothrow_default_constructible<key_equal>::value && |
2164 | | std::is_nothrow_default_constructible<allocator_type>::value) {} |
2165 | | |
2166 | | explicit raw_hash_set( |
2167 | | size_t bucket_count, const hasher& hash = hasher(), |
2168 | | const key_equal& eq = key_equal(), |
2169 | | const allocator_type& alloc = allocator_type()) |
2170 | | : settings_(CommonFields::CreateDefault<SooEnabled()>(), hash, eq, |
2171 | | alloc) { |
2172 | | if (bucket_count > DefaultCapacity()) { |
2173 | | ReserveEmptyNonAllocatedTableToFitBucketCount( |
2174 | | common(), GetPolicyFunctions(), bucket_count); |
2175 | | } |
2176 | | } |
2177 | | |
2178 | | raw_hash_set(size_t bucket_count, const hasher& hash, |
2179 | | const allocator_type& alloc) |
2180 | | : raw_hash_set(bucket_count, hash, key_equal(), alloc) {} |
2181 | | |
2182 | | raw_hash_set(size_t bucket_count, const allocator_type& alloc) |
2183 | | : raw_hash_set(bucket_count, hasher(), key_equal(), alloc) {} |
2184 | | |
2185 | | explicit raw_hash_set(const allocator_type& alloc) |
2186 | | : raw_hash_set(0, hasher(), key_equal(), alloc) {} |
2187 | | |
2188 | | template <class InputIter> |
2189 | | raw_hash_set(InputIter first, InputIter last, size_t bucket_count = 0, |
2190 | | const hasher& hash = hasher(), const key_equal& eq = key_equal(), |
2191 | | const allocator_type& alloc = allocator_type()) |
2192 | | : raw_hash_set(SelectBucketCountForIterRange(first, last, bucket_count), |
2193 | | hash, eq, alloc) { |
2194 | | insert(first, last); |
2195 | | } |
2196 | | |
2197 | | template <class InputIter> |
2198 | | raw_hash_set(InputIter first, InputIter last, size_t bucket_count, |
2199 | | const hasher& hash, const allocator_type& alloc) |
2200 | | : raw_hash_set(first, last, bucket_count, hash, key_equal(), alloc) {} |
2201 | | |
2202 | | template <class InputIter> |
2203 | | raw_hash_set(InputIter first, InputIter last, size_t bucket_count, |
2204 | | const allocator_type& alloc) |
2205 | | : raw_hash_set(first, last, bucket_count, hasher(), key_equal(), alloc) {} |
2206 | | |
2207 | | template <class InputIter> |
2208 | | raw_hash_set(InputIter first, InputIter last, const allocator_type& alloc) |
2209 | | : raw_hash_set(first, last, 0, hasher(), key_equal(), alloc) {} |
2210 | | |
2211 | | // Instead of accepting std::initializer_list<value_type> as the first |
2212 | | // argument like std::unordered_set<value_type> does, we have two overloads |
2213 | | // that accept std::initializer_list<T> and std::initializer_list<init_type>. |
2214 | | // This is advantageous for performance. |
2215 | | // |
2216 | | // // Turns {"abc", "def"} into std::initializer_list<std::string>, then |
2217 | | // // copies the strings into the set. |
2218 | | // std::unordered_set<std::string> s = {"abc", "def"}; |
2219 | | // |
2220 | | // // Turns {"abc", "def"} into std::initializer_list<const char*>, then |
2221 | | // // copies the strings into the set. |
2222 | | // absl::flat_hash_set<std::string> s = {"abc", "def"}; |
2223 | | // |
2224 | | // The same trick is used in insert(). |
2225 | | // |
2226 | | // The enabler is necessary to prevent this constructor from triggering where |
2227 | | // the copy constructor is meant to be called. |
2228 | | // |
2229 | | // absl::flat_hash_set<int> a, b{a}; |
2230 | | // |
2231 | | // RequiresNotInit<T> is a workaround for gcc prior to 7.1. |
2232 | | template <class T, RequiresNotInit<T> = 0, |
2233 | | std::enable_if_t<Insertable<T>::value, int> = 0> |
2234 | | raw_hash_set(std::initializer_list<T> init, size_t bucket_count = 0, |
2235 | | const hasher& hash = hasher(), const key_equal& eq = key_equal(), |
2236 | | const allocator_type& alloc = allocator_type()) |
2237 | | : raw_hash_set(init.begin(), init.end(), bucket_count, hash, eq, alloc) {} |
2238 | | |
2239 | | raw_hash_set(std::initializer_list<init_type> init, size_t bucket_count = 0, |
2240 | | const hasher& hash = hasher(), const key_equal& eq = key_equal(), |
2241 | | const allocator_type& alloc = allocator_type()) |
2242 | | : raw_hash_set(init.begin(), init.end(), bucket_count, hash, eq, alloc) {} |
2243 | | |
2244 | | template <class T, RequiresNotInit<T> = 0, |
2245 | | std::enable_if_t<Insertable<T>::value, int> = 0> |
2246 | | raw_hash_set(std::initializer_list<T> init, size_t bucket_count, |
2247 | | const hasher& hash, const allocator_type& alloc) |
2248 | | : raw_hash_set(init, bucket_count, hash, key_equal(), alloc) {} |
2249 | | |
2250 | | raw_hash_set(std::initializer_list<init_type> init, size_t bucket_count, |
2251 | | const hasher& hash, const allocator_type& alloc) |
2252 | | : raw_hash_set(init, bucket_count, hash, key_equal(), alloc) {} |
2253 | | |
2254 | | template <class T, RequiresNotInit<T> = 0, |
2255 | | std::enable_if_t<Insertable<T>::value, int> = 0> |
2256 | | raw_hash_set(std::initializer_list<T> init, size_t bucket_count, |
2257 | | const allocator_type& alloc) |
2258 | | : raw_hash_set(init, bucket_count, hasher(), key_equal(), alloc) {} |
2259 | | |
2260 | | raw_hash_set(std::initializer_list<init_type> init, size_t bucket_count, |
2261 | | const allocator_type& alloc) |
2262 | | : raw_hash_set(init, bucket_count, hasher(), key_equal(), alloc) {} |
2263 | | |
2264 | | template <class T, RequiresNotInit<T> = 0, |
2265 | | std::enable_if_t<Insertable<T>::value, int> = 0> |
2266 | | raw_hash_set(std::initializer_list<T> init, const allocator_type& alloc) |
2267 | | : raw_hash_set(init, 0, hasher(), key_equal(), alloc) {} |
2268 | | |
2269 | | raw_hash_set(std::initializer_list<init_type> init, |
2270 | | const allocator_type& alloc) |
2271 | | : raw_hash_set(init, 0, hasher(), key_equal(), alloc) {} |
2272 | | |
2273 | | raw_hash_set(const raw_hash_set& that) |
2274 | | : raw_hash_set(that, AllocTraits::select_on_container_copy_construction( |
2275 | | allocator_type(that.char_alloc_ref()))) {} |
2276 | | |
2277 | | raw_hash_set(const raw_hash_set& that, const allocator_type& a) |
2278 | | : raw_hash_set(0, that.hash_ref(), that.eq_ref(), a) { |
2279 | | that.AssertNotDebugCapacity(); |
2280 | | if (that.empty()) return; |
2281 | | Copy(common(), GetPolicyFunctions(), that.common(), |
2282 | | [this](void* dst, const void* src) { |
2283 | | // TODO(b/413598253): type erase for trivially copyable types via |
2284 | | // PolicyTraits. |
2285 | | construct(to_slot(dst), |
2286 | | PolicyTraits::element( |
2287 | | static_cast<slot_type*>(const_cast<void*>(src)))); |
2288 | | }); |
2289 | | } |
2290 | | |
2291 | | ABSL_ATTRIBUTE_NOINLINE raw_hash_set(raw_hash_set&& that) noexcept( |
2292 | | std::is_nothrow_copy_constructible<hasher>::value && |
2293 | | std::is_nothrow_copy_constructible<key_equal>::value && |
2294 | | std::is_nothrow_copy_constructible<allocator_type>::value) |
2295 | | : // Hash, equality and allocator are copied instead of moved because |
2296 | | // `that` must be left valid. If Hash is std::function<Key>, moving it |
2297 | | // would create a nullptr functor that cannot be called. |
2298 | | // Note: we avoid using exchange for better generated code. |
2299 | | settings_(PolicyTraits::transfer_uses_memcpy() || !that.is_full_soo() |
2300 | | ? std::move(that.common()) |
2301 | | : CommonFields{full_soo_tag_t{}}, |
2302 | | that.hash_ref(), that.eq_ref(), that.char_alloc_ref()) { |
2303 | | if (!PolicyTraits::transfer_uses_memcpy() && that.is_full_soo()) { |
2304 | | transfer(soo_slot(), that.soo_slot()); |
2305 | | } |
2306 | | that.common() = CommonFields::CreateDefault<SooEnabled()>(); |
2307 | | annotate_for_bug_detection_on_move(that); |
2308 | | } |
2309 | | |
2310 | | raw_hash_set(raw_hash_set&& that, const allocator_type& a) |
2311 | | : settings_(CommonFields::CreateDefault<SooEnabled()>(), that.hash_ref(), |
2312 | | that.eq_ref(), a) { |
2313 | | if (CharAlloc(a) == that.char_alloc_ref()) { |
2314 | | swap_common(that); |
2315 | | annotate_for_bug_detection_on_move(that); |
2316 | | } else { |
2317 | | move_elements_allocs_unequal(std::move(that)); |
2318 | | } |
2319 | | } |
2320 | | |
2321 | | raw_hash_set& operator=(const raw_hash_set& that) { |
2322 | | that.AssertNotDebugCapacity(); |
2323 | | if (ABSL_PREDICT_FALSE(this == &that)) return *this; |
2324 | | constexpr bool propagate_alloc = |
2325 | | AllocTraits::propagate_on_container_copy_assignment::value; |
2326 | | // TODO(ezb): maybe avoid allocating a new backing array if this->capacity() |
2327 | | // is an exact match for that.size(). If this->capacity() is too big, then |
2328 | | // it would make iteration very slow to reuse the allocation. Maybe we can |
2329 | | // do the same heuristic as clear() and reuse if it's small enough. |
2330 | | allocator_type alloc(propagate_alloc ? that.char_alloc_ref() |
2331 | | : char_alloc_ref()); |
2332 | | raw_hash_set tmp(that, alloc); |
2333 | | // NOLINTNEXTLINE: not returning *this for performance. |
2334 | | return assign_impl<propagate_alloc>(std::move(tmp)); |
2335 | | } |
2336 | | |
2337 | | raw_hash_set& operator=(raw_hash_set&& that) noexcept( |
2338 | | absl::allocator_traits<allocator_type>::is_always_equal::value && |
2339 | | std::is_nothrow_move_assignable<hasher>::value && |
2340 | | std::is_nothrow_move_assignable<key_equal>::value) { |
2341 | | // TODO(sbenza): We should only use the operations from the noexcept clause |
2342 | | // to make sure we actually adhere to that contract. |
2343 | | // NOLINTNEXTLINE: not returning *this for performance. |
2344 | | return move_assign( |
2345 | | std::move(that), |
2346 | | typename AllocTraits::propagate_on_container_move_assignment()); |
2347 | | } |
2348 | | |
2349 | | ~raw_hash_set() { |
2350 | | destructor_impl(); |
2351 | | if constexpr (SwisstableAssertAccessToDestroyedTable()) { |
2352 | | common().set_capacity(InvalidCapacity::kDestroyed); |
2353 | | } |
2354 | | } |
2355 | | |
2356 | | iterator begin() ABSL_ATTRIBUTE_LIFETIME_BOUND { |
2357 | | if (ABSL_PREDICT_FALSE(empty())) return end(); |
2358 | | if (is_small()) return single_iterator(); |
2359 | | iterator it = {control(), common().slots_union(), |
2360 | | common().generation_ptr()}; |
2361 | | it.skip_empty_or_deleted(); |
2362 | | ABSL_SWISSTABLE_ASSERT(IsFull(*it.control())); |
2363 | | return it; |
2364 | | } |
2365 | | iterator end() ABSL_ATTRIBUTE_LIFETIME_BOUND { |
2366 | | AssertNotDebugCapacity(); |
2367 | | return iterator(common().generation_ptr()); |
2368 | | } |
2369 | | |
2370 | | const_iterator begin() const ABSL_ATTRIBUTE_LIFETIME_BOUND { |
2371 | | return const_cast<raw_hash_set*>(this)->begin(); |
2372 | | } |
2373 | | const_iterator end() const ABSL_ATTRIBUTE_LIFETIME_BOUND { |
2374 | | return const_cast<raw_hash_set*>(this)->end(); |
2375 | | } |
2376 | | const_iterator cbegin() const ABSL_ATTRIBUTE_LIFETIME_BOUND { |
2377 | | return begin(); |
2378 | | } |
2379 | | const_iterator cend() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return end(); } |
2380 | | |
2381 | | bool empty() const { return !size(); } |
2382 | | size_t size() const { |
2383 | | AssertNotDebugCapacity(); |
2384 | | return common().size(); |
2385 | | } |
2386 | | size_t capacity() const { |
2387 | | const size_t cap = common().capacity(); |
2388 | | // Compiler complains when using functions in ASSUME so use local variable. |
2389 | | [[maybe_unused]] static constexpr size_t kDefaultCapacity = |
2390 | | DefaultCapacity(); |
2391 | | ABSL_ASSUME(cap >= kDefaultCapacity); |
2392 | | return cap; |
2393 | | } |
2394 | | size_t max_size() const { return MaxValidSize(sizeof(slot_type)); } |
2395 | | |
2396 | | ABSL_ATTRIBUTE_REINITIALIZES void clear() { |
2397 | | if (SwisstableGenerationsEnabled() && |
2398 | | capacity() >= InvalidCapacity::kMovedFrom) { |
2399 | | common().set_capacity(DefaultCapacity()); |
2400 | | } |
2401 | | AssertNotDebugCapacity(); |
2402 | | // Iterating over this container is O(bucket_count()). When bucket_count() |
2403 | | // is much greater than size(), iteration becomes prohibitively expensive. |
2404 | | // For clear() it is more important to reuse the allocated array when the |
2405 | | // container is small because allocation takes comparatively long time |
2406 | | // compared to destruction of the elements of the container. So we pick the |
2407 | | // largest bucket_count() threshold for which iteration is still fast and |
2408 | | // past that we simply deallocate the array. |
2409 | | const size_t cap = capacity(); |
2410 | | if (cap == 0) { |
2411 | | // Already guaranteed to be empty; so nothing to do. |
2412 | | } else if (is_small()) { |
2413 | | if (!empty()) { |
2414 | | destroy(single_slot()); |
2415 | | decrement_small_size(); |
2416 | | } |
2417 | | } else { |
2418 | | destroy_slots(); |
2419 | | clear_backing_array(/*reuse=*/cap < 128); |
2420 | | } |
2421 | | common().set_reserved_growth(0); |
2422 | | common().set_reservation_size(0); |
2423 | | } |
2424 | | |
2425 | | // This overload kicks in when the argument is an rvalue of insertable and |
2426 | | // decomposable type other than init_type. |
2427 | | // |
2428 | | // flat_hash_map<std::string, int> m; |
2429 | | // m.insert(std::make_pair("abc", 42)); |
2430 | | template <class T, |
2431 | | int = std::enable_if_t<IsDecomposableAndInsertable<T>::value && |
2432 | | IsNotBitField<T>::value && |
2433 | | !IsLifetimeBoundAssignmentFrom<T>::value, |
2434 | | int>()> |
2435 | | std::pair<iterator, bool> insert(T&& value) ABSL_ATTRIBUTE_LIFETIME_BOUND { |
2436 | | return emplace(std::forward<T>(value)); |
2437 | | } |
2438 | | |
2439 | | template <class T, int&..., |
2440 | | std::enable_if_t<IsDecomposableAndInsertable<T>::value && |
2441 | | IsNotBitField<T>::value && |
2442 | | IsLifetimeBoundAssignmentFrom<T>::value, |
2443 | | int> = 0> |
2444 | | std::pair<iterator, bool> insert( |
2445 | | T&& value ABSL_INTERNAL_ATTRIBUTE_CAPTURED_BY(this)) |
2446 | | ABSL_ATTRIBUTE_LIFETIME_BOUND { |
2447 | | return this->template insert<T, 0>(std::forward<T>(value)); |
2448 | | } |
2449 | | |
2450 | | // This overload kicks in when the argument is a bitfield or an lvalue of |
2451 | | // insertable and decomposable type. |
2452 | | // |
2453 | | // union { int n : 1; }; |
2454 | | // flat_hash_set<int> s; |
2455 | | // s.insert(n); |
2456 | | // |
2457 | | // flat_hash_set<std::string> s; |
2458 | | // const char* p = "hello"; |
2459 | | // s.insert(p); |
2460 | | // |
2461 | | template <class T, int = std::enable_if_t< |
2462 | | IsDecomposableAndInsertable<const T&>::value && |
2463 | | !IsLifetimeBoundAssignmentFrom<const T&>::value, |
2464 | | int>()> |
2465 | | std::pair<iterator, bool> insert(const T& value) |
2466 | | ABSL_ATTRIBUTE_LIFETIME_BOUND { |
2467 | | return emplace(value); |
2468 | | } |
2469 | | template <class T, int&..., |
2470 | | std::enable_if_t<IsDecomposableAndInsertable<const T&>::value && |
2471 | | IsLifetimeBoundAssignmentFrom<const T&>::value, |
2472 | | int> = 0> |
2473 | | std::pair<iterator, bool> insert( |
2474 | | const T& value ABSL_INTERNAL_ATTRIBUTE_CAPTURED_BY(this)) |
2475 | | ABSL_ATTRIBUTE_LIFETIME_BOUND { |
2476 | | return this->template insert<T, 0>(value); |
2477 | | } |
2478 | | |
2479 | | // This overload kicks in when the argument is an rvalue of init_type. Its |
2480 | | // purpose is to handle brace-init-list arguments. |
2481 | | // |
2482 | | // flat_hash_map<std::string, int> s; |
2483 | | // s.insert({"abc", 42}); |
2484 | | std::pair<iterator, bool> insert(init_type&& value) |
2485 | | ABSL_ATTRIBUTE_LIFETIME_BOUND |
2486 | | #if __cplusplus >= 202002L |
2487 | | requires(!IsLifetimeBoundAssignmentFrom<init_type>::value) |
2488 | | #endif |
2489 | | { |
2490 | | return emplace(std::move(value)); |
2491 | | } |
2492 | | #if __cplusplus >= 202002L |
2493 | | std::pair<iterator, bool> insert( |
2494 | | init_type&& value ABSL_INTERNAL_ATTRIBUTE_CAPTURED_BY(this)) |
2495 | | ABSL_ATTRIBUTE_LIFETIME_BOUND |
2496 | | requires(IsLifetimeBoundAssignmentFrom<init_type>::value) |
2497 | | { |
2498 | | return emplace(std::move(value)); |
2499 | | } |
2500 | | #endif |
2501 | | |
2502 | | template <class T, |
2503 | | int = std::enable_if_t<IsDecomposableAndInsertable<T>::value && |
2504 | | IsNotBitField<T>::value && |
2505 | | !IsLifetimeBoundAssignmentFrom<T>::value, |
2506 | | int>()> |
2507 | | iterator insert(const_iterator, T&& value) ABSL_ATTRIBUTE_LIFETIME_BOUND { |
2508 | | return insert(std::forward<T>(value)).first; |
2509 | | } |
2510 | | template <class T, int&..., |
2511 | | std::enable_if_t<IsDecomposableAndInsertable<T>::value && |
2512 | | IsNotBitField<T>::value && |
2513 | | IsLifetimeBoundAssignmentFrom<T>::value, |
2514 | | int> = 0> |
2515 | | iterator insert(const_iterator hint, |
2516 | | T&& value ABSL_INTERNAL_ATTRIBUTE_CAPTURED_BY(this)) |
2517 | | ABSL_ATTRIBUTE_LIFETIME_BOUND { |
2518 | | return this->template insert<T, 0>(hint, std::forward<T>(value)); |
2519 | | } |
2520 | | |
2521 | | template <class T, std::enable_if_t< |
2522 | | IsDecomposableAndInsertable<const T&>::value, int> = 0> |
2523 | | iterator insert(const_iterator, |
2524 | | const T& value) ABSL_ATTRIBUTE_LIFETIME_BOUND { |
2525 | | return insert(value).first; |
2526 | | } |
2527 | | |
2528 | | iterator insert(const_iterator, |
2529 | | init_type&& value) ABSL_ATTRIBUTE_LIFETIME_BOUND { |
2530 | | return insert(std::move(value)).first; |
2531 | | } |
2532 | | |
2533 | | template <class InputIt> |
2534 | | void insert(InputIt first, InputIt last) { |
2535 | | for (; first != last; ++first) emplace(*first); |
2536 | | } |
2537 | | |
2538 | | template <class T, RequiresNotInit<T> = 0, |
2539 | | std::enable_if_t<Insertable<const T&>::value, int> = 0> |
2540 | | void insert(std::initializer_list<T> ilist) { |
2541 | | insert(ilist.begin(), ilist.end()); |
2542 | | } |
2543 | | |
2544 | | void insert(std::initializer_list<init_type> ilist) { |
2545 | | insert(ilist.begin(), ilist.end()); |
2546 | | } |
2547 | | |
2548 | | insert_return_type insert(node_type&& node) ABSL_ATTRIBUTE_LIFETIME_BOUND { |
2549 | | if (!node) return {end(), false, node_type()}; |
2550 | | const auto& elem = PolicyTraits::element(CommonAccess::GetSlot(node)); |
2551 | | auto res = PolicyTraits::apply( |
2552 | | InsertSlot<false>{*this, std::move(*CommonAccess::GetSlot(node))}, |
2553 | | elem); |
2554 | | if (res.second) { |
2555 | | CommonAccess::Reset(&node); |
2556 | | return {res.first, true, node_type()}; |
2557 | | } else { |
2558 | | return {res.first, false, std::move(node)}; |
2559 | | } |
2560 | | } |
2561 | | |
2562 | | iterator insert(const_iterator, |
2563 | | node_type&& node) ABSL_ATTRIBUTE_LIFETIME_BOUND { |
2564 | | auto res = insert(std::move(node)); |
2565 | | node = std::move(res.node); |
2566 | | return res.position; |
2567 | | } |
2568 | | |
2569 | | // This overload kicks in if we can deduce the key from args. This enables us |
2570 | | // to avoid constructing value_type if an entry with the same key already |
2571 | | // exists. |
2572 | | // |
2573 | | // For example: |
2574 | | // |
2575 | | // flat_hash_map<std::string, std::string> m = {{"abc", "def"}}; |
2576 | | // // Creates no std::string copies and makes no heap allocations. |
2577 | | // m.emplace("abc", "xyz"); |
2578 | | template <class... Args, |
2579 | | std::enable_if_t<IsDecomposable<Args...>::value, int> = 0> |
2580 | | std::pair<iterator, bool> emplace(Args&&... args) |
2581 | | ABSL_ATTRIBUTE_LIFETIME_BOUND { |
2582 | | return PolicyTraits::apply(EmplaceDecomposable{*this}, |
2583 | | std::forward<Args>(args)...); |
2584 | | } |
2585 | | |
2586 | | // This overload kicks in if we cannot deduce the key from args. It constructs |
2587 | | // value_type unconditionally and then either moves it into the table or |
2588 | | // destroys. |
2589 | | template <class... Args, |
2590 | | std::enable_if_t<!IsDecomposable<Args...>::value, int> = 0> |
2591 | | std::pair<iterator, bool> emplace(Args&&... args) |
2592 | | ABSL_ATTRIBUTE_LIFETIME_BOUND { |
2593 | | alignas(slot_type) unsigned char raw[sizeof(slot_type)]; |
2594 | | slot_type* slot = to_slot(&raw); |
2595 | | |
2596 | | construct(slot, std::forward<Args>(args)...); |
2597 | | const auto& elem = PolicyTraits::element(slot); |
2598 | | return PolicyTraits::apply(InsertSlot<true>{*this, std::move(*slot)}, elem); |
2599 | | } |
2600 | | |
2601 | | template <class... Args> |
2602 | | iterator emplace_hint(const_iterator, |
2603 | | Args&&... args) ABSL_ATTRIBUTE_LIFETIME_BOUND { |
2604 | | return emplace(std::forward<Args>(args)...).first; |
2605 | | } |
2606 | | |
2607 | | // Extension API: support for lazy emplace. |
2608 | | // |
2609 | | // Looks up key in the table. If found, returns the iterator to the element. |
2610 | | // Otherwise calls `f` with one argument of type `raw_hash_set::constructor`, |
2611 | | // and returns an iterator to the new element. |
2612 | | // |
2613 | | // `f` must abide by several restrictions: |
2614 | | // - it MUST call `raw_hash_set::constructor` with arguments as if a |
2615 | | // `raw_hash_set::value_type` is constructed, |
2616 | | // - it MUST NOT access the container before the call to |
2617 | | // `raw_hash_set::constructor`, and |
2618 | | // - it MUST NOT erase the lazily emplaced element. |
2619 | | // Doing any of these is undefined behavior. |
2620 | | // |
2621 | | // For example: |
2622 | | // |
2623 | | // std::unordered_set<ArenaString> s; |
2624 | | // // Makes ArenaStr even if "abc" is in the map. |
2625 | | // s.insert(ArenaString(&arena, "abc")); |
2626 | | // |
2627 | | // flat_hash_set<ArenaStr> s; |
2628 | | // // Makes ArenaStr only if "abc" is not in the map. |
2629 | | // s.lazy_emplace("abc", [&](const constructor& ctor) { |
2630 | | // ctor(&arena, "abc"); |
2631 | | // }); |
2632 | | // |
2633 | | // WARNING: This API is currently experimental. If there is a way to implement |
2634 | | // the same thing with the rest of the API, prefer that. |
2635 | | class constructor { |
2636 | | friend class raw_hash_set; |
2637 | | |
2638 | | public: |
2639 | | template <class... Args> |
2640 | | void operator()(Args&&... args) const { |
2641 | | ABSL_SWISSTABLE_ASSERT(*slot_); |
2642 | | PolicyTraits::construct(alloc_, *slot_, std::forward<Args>(args)...); |
2643 | | *slot_ = nullptr; |
2644 | | } |
2645 | | |
2646 | | private: |
2647 | | constructor(allocator_type* a, slot_type** slot) : alloc_(a), slot_(slot) {} |
2648 | | |
2649 | | allocator_type* alloc_; |
2650 | | slot_type** slot_; |
2651 | | }; |
2652 | | |
2653 | | template <class K = key_type, class F> |
2654 | | iterator lazy_emplace(const key_arg<K>& key, |
2655 | | F&& f) ABSL_ATTRIBUTE_LIFETIME_BOUND { |
2656 | | auto res = find_or_prepare_insert(key); |
2657 | | if (res.second) { |
2658 | | slot_type* slot = res.first.slot(); |
2659 | | allocator_type alloc(char_alloc_ref()); |
2660 | | std::forward<F>(f)(constructor(&alloc, &slot)); |
2661 | | ABSL_SWISSTABLE_ASSERT(!slot); |
2662 | | } |
2663 | | return res.first; |
2664 | | } |
2665 | | |
2666 | | // Extension API: support for heterogeneous keys. |
2667 | | // |
2668 | | // std::unordered_set<std::string> s; |
2669 | | // // Turns "abc" into std::string. |
2670 | | // s.erase("abc"); |
2671 | | // |
2672 | | // flat_hash_set<std::string> s; |
2673 | | // // Uses "abc" directly without copying it into std::string. |
2674 | | // s.erase("abc"); |
2675 | | template <class K = key_type> |
2676 | | size_type erase(const key_arg<K>& key) { |
2677 | | auto it = find(key); |
2678 | | if (it == end()) return 0; |
2679 | | erase(it); |
2680 | | return 1; |
2681 | | } |
2682 | | |
2683 | | // Erases the element pointed to by `it`. Unlike `std::unordered_set::erase`, |
2684 | | // this method returns void to reduce algorithmic complexity to O(1). The |
2685 | | // iterator is invalidated so any increment should be done before calling |
2686 | | // erase (e.g. `erase(it++)`). |
2687 | | void erase(const_iterator cit) { erase(cit.inner_); } |
2688 | | |
2689 | | // This overload is necessary because otherwise erase<K>(const K&) would be |
2690 | | // a better match if non-const iterator is passed as an argument. |
2691 | | void erase(iterator it) { |
2692 | | ABSL_SWISSTABLE_ASSERT(capacity() > 0); |
2693 | | AssertNotDebugCapacity(); |
2694 | | AssertIsFull(it.control(), it.generation(), it.generation_ptr(), "erase()"); |
2695 | | destroy(it.slot()); |
2696 | | erase_meta_only(it); |
2697 | | } |
2698 | | |
2699 | | iterator erase(const_iterator first, |
2700 | | const_iterator last) ABSL_ATTRIBUTE_LIFETIME_BOUND { |
2701 | | AssertNotDebugCapacity(); |
2702 | | // We check for empty first because clear_backing_array requires that |
2703 | | // capacity() > 0 as a precondition. |
2704 | | if (empty()) return end(); |
2705 | | if (first == last) return last.inner_; |
2706 | | if (is_small()) { |
2707 | | destroy(single_slot()); |
2708 | | erase_meta_only(single_iterator()); |
2709 | | return end(); |
2710 | | } |
2711 | | if (first == begin() && last == end()) { |
2712 | | // TODO(ezb): we access control bytes in destroy_slots so it could make |
2713 | | // sense to combine destroy_slots and clear_backing_array to avoid cache |
2714 | | // misses when the table is large. Note that we also do this in clear(). |
2715 | | destroy_slots(); |
2716 | | clear_backing_array(/*reuse=*/true); |
2717 | | common().set_reserved_growth(common().reservation_size()); |
2718 | | return end(); |
2719 | | } |
2720 | | while (first != last) { |
2721 | | erase(first++); |
2722 | | } |
2723 | | return last.inner_; |
2724 | | } |
2725 | | |
2726 | | // Moves elements from `src` into `this`. |
2727 | | // If the element already exists in `this`, it is left unmodified in `src`. |
2728 | | template <typename H, typename E> |
2729 | | void merge(raw_hash_set<Policy, H, E, Alloc>& src) { // NOLINT |
2730 | | AssertNotDebugCapacity(); |
2731 | | src.AssertNotDebugCapacity(); |
2732 | | assert(this != &src); |
2733 | | // Returns whether insertion took place. |
2734 | | const auto insert_slot = [this](slot_type* src_slot) { |
2735 | | return PolicyTraits::apply(InsertSlot<false>{*this, std::move(*src_slot)}, |
2736 | | PolicyTraits::element(src_slot)) |
2737 | | .second; |
2738 | | }; |
2739 | | |
2740 | | if (src.is_small()) { |
2741 | | if (src.empty()) return; |
2742 | | if (insert_slot(src.single_slot())) |
2743 | | src.erase_meta_only(src.single_iterator()); |
2744 | | return; |
2745 | | } |
2746 | | for (auto it = src.begin(), e = src.end(); it != e;) { |
2747 | | auto next = std::next(it); |
2748 | | if (insert_slot(it.slot())) src.erase_meta_only(it); |
2749 | | it = next; |
2750 | | } |
2751 | | } |
2752 | | |
2753 | | template <typename H, typename E> |
2754 | | void merge(raw_hash_set<Policy, H, E, Alloc>&& src) { |
2755 | | merge(src); |
2756 | | } |
2757 | | |
2758 | | node_type extract(const_iterator position) { |
2759 | | AssertNotDebugCapacity(); |
2760 | | AssertIsFull(position.control(), position.inner_.generation(), |
2761 | | position.inner_.generation_ptr(), "extract()"); |
2762 | | allocator_type alloc(char_alloc_ref()); |
2763 | | auto node = CommonAccess::Transfer<node_type>(alloc, position.slot()); |
2764 | | erase_meta_only(position); |
2765 | | return node; |
2766 | | } |
2767 | | |
2768 | | template <class K = key_type, |
2769 | | std::enable_if_t<!std::is_same<K, iterator>::value, int> = 0> |
2770 | | node_type extract(const key_arg<K>& key) { |
2771 | | auto it = find(key); |
2772 | | return it == end() ? node_type() : extract(const_iterator{it}); |
2773 | | } |
2774 | | |
2775 | | void swap(raw_hash_set& that) noexcept( |
2776 | | IsNoThrowSwappable<hasher>() && IsNoThrowSwappable<key_equal>() && |
2777 | | IsNoThrowSwappable<allocator_type>( |
2778 | | typename AllocTraits::propagate_on_container_swap{})) { |
2779 | | AssertNotDebugCapacity(); |
2780 | | that.AssertNotDebugCapacity(); |
2781 | | using std::swap; |
2782 | | swap_common(that); |
2783 | | swap(hash_ref(), that.hash_ref()); |
2784 | | swap(eq_ref(), that.eq_ref()); |
2785 | | SwapAlloc(char_alloc_ref(), that.char_alloc_ref(), |
2786 | | typename AllocTraits::propagate_on_container_swap{}); |
2787 | | } |
2788 | | |
2789 | | void rehash(size_t n) { Rehash(common(), GetPolicyFunctions(), n); } |
2790 | | |
2791 | | void reserve(size_t n) { |
2792 | | if (ABSL_PREDICT_TRUE(n > DefaultCapacity())) { |
2793 | | ReserveTableToFitNewSize(common(), GetPolicyFunctions(), n); |
2794 | | } |
2795 | | } |
2796 | | |
2797 | | // Extension API: support for heterogeneous keys. |
2798 | | // |
2799 | | // std::unordered_set<std::string> s; |
2800 | | // // Turns "abc" into std::string. |
2801 | | // s.count("abc"); |
2802 | | // |
2803 | | // ch_set<std::string> s; |
2804 | | // // Uses "abc" directly without copying it into std::string. |
2805 | | // s.count("abc"); |
2806 | | template <class K = key_type> |
2807 | | size_t count(const key_arg<K>& key) const { |
2808 | | return find(key) == end() ? 0 : 1; |
2809 | | } |
2810 | | |
2811 | | // Issues CPU prefetch instructions for the memory needed to find or insert |
2812 | | // a key. Like all lookup functions, this support heterogeneous keys. |
2813 | | // |
2814 | | // NOTE: This is a very low level operation and should not be used without |
2815 | | // specific benchmarks indicating its importance. |
2816 | | template <class K = key_type> |
2817 | | void prefetch([[maybe_unused]] const key_arg<K>& key) const { |
2818 | | if (capacity() == DefaultCapacity()) return; |
2819 | | // Avoid probing if we won't be able to prefetch the addresses received. |
2820 | | #ifdef ABSL_HAVE_PREFETCH |
2821 | | prefetch_heap_block(); |
2822 | | if (is_small()) return; |
2823 | | auto seq = probe(common(), hash_of(key)); |
2824 | | PrefetchToLocalCache(control() + seq.offset()); |
2825 | | PrefetchToLocalCache(slot_array() + seq.offset()); |
2826 | | #endif // ABSL_HAVE_PREFETCH |
2827 | | } |
2828 | | |
2829 | | template <class K = key_type> |
2830 | | ABSL_DEPRECATE_AND_INLINE() |
2831 | | iterator find(const key_arg<K>& key, |
2832 | | size_t) ABSL_ATTRIBUTE_LIFETIME_BOUND { |
2833 | | return find(key); |
2834 | | } |
2835 | | // The API of find() has one extension: the type of the key argument doesn't |
2836 | | // have to be key_type. This is so called heterogeneous key support. |
2837 | | template <class K = key_type> |
2838 | | iterator find(const key_arg<K>& key) ABSL_ATTRIBUTE_LIFETIME_BOUND { |
2839 | | AssertOnFind(key); |
2840 | | if (is_small()) return find_small(key); |
2841 | | prefetch_heap_block(); |
2842 | | return find_large(key, hash_of(key)); |
2843 | | } |
2844 | | |
2845 | | template <class K = key_type> |
2846 | | ABSL_DEPRECATE_AND_INLINE() |
2847 | | const_iterator find(const key_arg<K>& key, |
2848 | | size_t) const ABSL_ATTRIBUTE_LIFETIME_BOUND { |
2849 | | return find(key); |
2850 | | } |
2851 | | template <class K = key_type> |
2852 | | const_iterator find(const key_arg<K>& key) const |
2853 | | ABSL_ATTRIBUTE_LIFETIME_BOUND { |
2854 | | return const_cast<raw_hash_set*>(this)->find(key); |
2855 | | } |
2856 | | |
2857 | | template <class K = key_type> |
2858 | | bool contains(const key_arg<K>& key) const { |
2859 | | // Here neither the iterator returned by `find()` nor `end()` can be invalid |
2860 | | // outside of potential thread-safety issues. |
2861 | | // `find()`'s return value is constructed, used, and then destructed |
2862 | | // all in this context. |
2863 | | return !find(key).unchecked_equals(end()); |
2864 | | } |
2865 | | |
2866 | | template <class K = key_type> |
2867 | | std::pair<iterator, iterator> equal_range(const key_arg<K>& key) |
2868 | | ABSL_ATTRIBUTE_LIFETIME_BOUND { |
2869 | | auto it = find(key); |
2870 | | if (it != end()) return {it, std::next(it)}; |
2871 | | return {it, it}; |
2872 | | } |
2873 | | template <class K = key_type> |
2874 | | std::pair<const_iterator, const_iterator> equal_range( |
2875 | | const key_arg<K>& key) const ABSL_ATTRIBUTE_LIFETIME_BOUND { |
2876 | | auto it = find(key); |
2877 | | if (it != end()) return {it, std::next(it)}; |
2878 | | return {it, it}; |
2879 | | } |
2880 | | |
2881 | | size_t bucket_count() const { return capacity(); } |
2882 | | float load_factor() const { |
2883 | | return capacity() ? static_cast<double>(size()) / capacity() : 0.0; |
2884 | | } |
2885 | | float max_load_factor() const { return 1.0f; } |
2886 | | void max_load_factor(float) { |
2887 | | // Does nothing. |
2888 | | } |
2889 | | |
2890 | | hasher hash_function() const { return hash_ref(); } |
2891 | | key_equal key_eq() const { return eq_ref(); } |
2892 | | allocator_type get_allocator() const { |
2893 | | return allocator_type(char_alloc_ref()); |
2894 | | } |
2895 | | |
2896 | | friend bool operator==(const raw_hash_set& a, const raw_hash_set& b) { |
2897 | | if (a.size() != b.size()) return false; |
2898 | | const raw_hash_set* outer = &a; |
2899 | | const raw_hash_set* inner = &b; |
2900 | | if (outer->capacity() > inner->capacity()) std::swap(outer, inner); |
2901 | | for (const value_type& elem : *outer) { |
2902 | | auto it = PolicyTraits::apply(FindElement{*inner}, elem); |
2903 | | if (it == inner->end()) return false; |
2904 | | // Note: we used key_equal to check for key equality in FindElement, but |
2905 | | // we may need to do an additional comparison using |
2906 | | // value_type::operator==. E.g. the keys could be equal and the |
2907 | | // mapped_types could be unequal in a map or even in a set, key_equal |
2908 | | // could ignore some fields that aren't ignored by operator==. |
2909 | | static constexpr bool kKeyEqIsValueEq = |
2910 | | std::is_same<key_type, value_type>::value && |
2911 | | std::is_same<key_equal, hash_default_eq<key_type>>::value; |
2912 | | if (!kKeyEqIsValueEq && !(*it == elem)) return false; |
2913 | | } |
2914 | | return true; |
2915 | | } |
2916 | | |
2917 | | friend bool operator!=(const raw_hash_set& a, const raw_hash_set& b) { |
2918 | | return !(a == b); |
2919 | | } |
2920 | | |
2921 | | template <typename H> |
2922 | | friend typename std::enable_if<H::template is_hashable<value_type>::value, |
2923 | | H>::type |
2924 | | AbslHashValue(H h, const raw_hash_set& s) { |
2925 | | return H::combine(H::combine_unordered(std::move(h), s.begin(), s.end()), |
2926 | | hash_internal::WeaklyMixedInteger{s.size()}); |
2927 | | } |
2928 | | |
2929 | | friend void swap(raw_hash_set& a, |
2930 | | raw_hash_set& b) noexcept(noexcept(a.swap(b))) { |
2931 | | a.swap(b); |
2932 | | } |
2933 | | |
2934 | | private: |
2935 | | template <class Container, typename Enabler> |
2936 | | friend struct absl::container_internal::hashtable_debug_internal:: |
2937 | | HashtableDebugAccess; |
2938 | | |
2939 | | friend struct absl::container_internal::HashtableFreeFunctionsAccess; |
2940 | | |
2941 | | struct FindElement { |
2942 | | template <class K, class... Args> |
2943 | | const_iterator operator()(const K& key, Args&&...) const { |
2944 | | return s.find(key); |
2945 | | } |
2946 | | const raw_hash_set& s; |
2947 | | }; |
2948 | | |
2949 | | struct EmplaceDecomposable { |
2950 | | template <class K, class... Args> |
2951 | | std::pair<iterator, bool> operator()(const K& key, Args&&... args) const { |
2952 | | auto res = s.find_or_prepare_insert(key); |
2953 | | if (res.second) { |
2954 | | s.emplace_at(res.first, std::forward<Args>(args)...); |
2955 | | } |
2956 | | return res; |
2957 | | } |
2958 | | raw_hash_set& s; |
2959 | | }; |
2960 | | |
2961 | | template <bool do_destroy> |
2962 | | struct InsertSlot { |
2963 | | template <class K, class... Args> |
2964 | | std::pair<iterator, bool> operator()(const K& key, Args&&...) && { |
2965 | | auto res = s.find_or_prepare_insert(key); |
2966 | | if (res.second) { |
2967 | | s.transfer(res.first.slot(), &slot); |
2968 | | } else if (do_destroy) { |
2969 | | s.destroy(&slot); |
2970 | | } |
2971 | | return res; |
2972 | | } |
2973 | | raw_hash_set& s; |
2974 | | // Constructed slot. Either moved into place or destroyed. |
2975 | | slot_type&& slot; |
2976 | | }; |
2977 | | |
2978 | | template <typename... Args> |
2979 | | inline void construct(slot_type* slot, Args&&... args) { |
2980 | | common().RunWithReentrancyGuard([&] { |
2981 | | allocator_type alloc(char_alloc_ref()); |
2982 | | PolicyTraits::construct(&alloc, slot, std::forward<Args>(args)...); |
2983 | | }); |
2984 | | } |
2985 | | inline void destroy(slot_type* slot) { |
2986 | | common().RunWithReentrancyGuard([&] { |
2987 | | allocator_type alloc(char_alloc_ref()); |
2988 | | PolicyTraits::destroy(&alloc, slot); |
2989 | | }); |
2990 | | } |
2991 | | inline void transfer(slot_type* to, slot_type* from) { |
2992 | | common().RunWithReentrancyGuard([&] { |
2993 | | allocator_type alloc(char_alloc_ref()); |
2994 | | PolicyTraits::transfer(&alloc, to, from); |
2995 | | }); |
2996 | | } |
2997 | | |
2998 | | // TODO(b/289225379): consider having a helper class that has the impls for |
2999 | | // SOO functionality. |
3000 | | template <class K = key_type> |
3001 | | iterator find_small(const key_arg<K>& key) { |
3002 | | ABSL_SWISSTABLE_ASSERT(is_small()); |
3003 | | return empty() || !equal_to(key, single_slot()) ? end() : single_iterator(); |
3004 | | } |
3005 | | |
3006 | | template <class K = key_type> |
3007 | | iterator find_large(const key_arg<K>& key, size_t hash) { |
3008 | | ABSL_SWISSTABLE_ASSERT(!is_small()); |
3009 | | auto seq = probe(common(), hash); |
3010 | | const h2_t h2 = H2(hash); |
3011 | | const ctrl_t* ctrl = control(); |
3012 | | while (true) { |
3013 | | #ifndef ABSL_HAVE_MEMORY_SANITIZER |
3014 | | absl::PrefetchToLocalCache(slot_array() + seq.offset()); |
3015 | | #endif |
3016 | | Group g{ctrl + seq.offset()}; |
3017 | | for (uint32_t i : g.Match(h2)) { |
3018 | | if (ABSL_PREDICT_TRUE(equal_to(key, slot_array() + seq.offset(i)))) |
3019 | | return iterator_at(seq.offset(i)); |
3020 | | } |
3021 | | if (ABSL_PREDICT_TRUE(g.MaskEmpty())) return end(); |
3022 | | seq.next(); |
3023 | | ABSL_SWISSTABLE_ASSERT(seq.index() <= capacity() && "full table!"); |
3024 | | } |
3025 | | } |
3026 | | |
3027 | | // Returns true if the table needs to be sampled. |
3028 | | // This should be called on insertion into an empty SOO table and in copy |
3029 | | // construction when the size can fit in SOO capacity. |
3030 | | bool should_sample_soo() const { |
3031 | | ABSL_SWISSTABLE_ASSERT(is_soo()); |
3032 | | if (!ShouldSampleHashtablezInfoForAlloc<CharAlloc>()) return false; |
3033 | | return ABSL_PREDICT_FALSE(ShouldSampleNextTable()); |
3034 | | } |
3035 | | |
3036 | | void clear_backing_array(bool reuse) { |
3037 | | ABSL_SWISSTABLE_ASSERT(capacity() > DefaultCapacity()); |
3038 | | ClearBackingArray(common(), GetPolicyFunctions(), &char_alloc_ref(), reuse, |
3039 | | SooEnabled()); |
3040 | | } |
3041 | | |
3042 | | void destroy_slots() { |
3043 | | ABSL_SWISSTABLE_ASSERT(!is_small()); |
3044 | | if (PolicyTraits::template destroy_is_trivial<Alloc>()) return; |
3045 | | auto destroy_slot = [&](const ctrl_t*, void* slot) { |
3046 | | this->destroy(static_cast<slot_type*>(slot)); |
3047 | | }; |
3048 | | if constexpr (SwisstableAssertAccessToDestroyedTable()) { |
3049 | | CommonFields common_copy(non_soo_tag_t{}, this->common()); |
3050 | | common().set_capacity(InvalidCapacity::kDestroyed); |
3051 | | IterateOverFullSlots(common_copy, sizeof(slot_type), destroy_slot); |
3052 | | common().set_capacity(common_copy.capacity()); |
3053 | | } else { |
3054 | | IterateOverFullSlots(common(), sizeof(slot_type), destroy_slot); |
3055 | | } |
3056 | | } |
3057 | | |
3058 | | void dealloc() { |
3059 | | ABSL_SWISSTABLE_ASSERT(capacity() > DefaultCapacity()); |
3060 | | // Unpoison before returning the memory to the allocator. |
3061 | | SanitizerUnpoisonMemoryRegion(slot_array(), sizeof(slot_type) * capacity()); |
3062 | | infoz().Unregister(); |
3063 | | DeallocateBackingArray<BackingArrayAlignment(alignof(slot_type)), |
3064 | | CharAlloc>(&char_alloc_ref(), capacity(), control(), |
3065 | | sizeof(slot_type), alignof(slot_type), |
3066 | | common().has_infoz()); |
3067 | | } |
3068 | | |
3069 | | void destructor_impl() { |
3070 | | if (SwisstableGenerationsEnabled() && |
3071 | | capacity() >= InvalidCapacity::kMovedFrom) { |
3072 | | return; |
3073 | | } |
3074 | | if (capacity() == 0) return; |
3075 | | if (is_small()) { |
3076 | | if (!empty()) { |
3077 | | ABSL_SWISSTABLE_IGNORE_UNINITIALIZED(destroy(single_slot())); |
3078 | | } |
3079 | | if constexpr (SooEnabled()) return; |
3080 | | } else { |
3081 | | destroy_slots(); |
3082 | | } |
3083 | | dealloc(); |
3084 | | } |
3085 | | |
3086 | | // Erases, but does not destroy, the value pointed to by `it`. |
3087 | | // |
3088 | | // This merely updates the pertinent control byte. This can be used in |
3089 | | // conjunction with Policy::transfer to move the object to another place. |
3090 | | void erase_meta_only(const_iterator it) { |
3091 | | if (is_soo()) { |
3092 | | common().set_empty_soo(); |
3093 | | return; |
3094 | | } |
3095 | | EraseMetaOnly(common(), it.control(), sizeof(slot_type)); |
3096 | | } |
3097 | | |
3098 | | template <class K> |
3099 | | ABSL_ATTRIBUTE_ALWAYS_INLINE bool equal_to(const K& key, |
3100 | | slot_type* slot) const { |
3101 | | return PolicyTraits::apply(EqualElement<K, key_equal>{key, eq_ref()}, |
3102 | | PolicyTraits::element(slot)); |
3103 | | } |
3104 | | template <class K> |
3105 | | ABSL_ATTRIBUTE_ALWAYS_INLINE size_t hash_of(const K& key) const { |
3106 | | return HashElement<hasher, kIsDefaultHash>{hash_ref(), |
3107 | | common().seed().seed()}(key); |
3108 | | } |
3109 | | ABSL_ATTRIBUTE_ALWAYS_INLINE size_t hash_of(slot_type* slot) const { |
3110 | | return PolicyTraits::apply( |
3111 | | HashElement<hasher, kIsDefaultHash>{hash_ref(), common().seed().seed()}, |
3112 | | PolicyTraits::element(slot)); |
3113 | | } |
3114 | | |
3115 | | // Casting directly from e.g. char* to slot_type* can cause compilation errors |
3116 | | // on objective-C. This function converts to void* first, avoiding the issue. |
3117 | | static ABSL_ATTRIBUTE_ALWAYS_INLINE slot_type* to_slot(void* buf) { |
3118 | | return static_cast<slot_type*>(buf); |
3119 | | } |
3120 | | |
3121 | | // Requires that lhs does not have a full SOO slot. |
3122 | | static void move_common(bool rhs_is_full_soo, CharAlloc& rhs_alloc, |
3123 | | CommonFields& lhs, CommonFields&& rhs) { |
3124 | | if (PolicyTraits::transfer_uses_memcpy() || !rhs_is_full_soo) { |
3125 | | lhs = std::move(rhs); |
3126 | | } else { |
3127 | | lhs.move_non_heap_or_soo_fields(rhs); |
3128 | | rhs.RunWithReentrancyGuard([&] { |
3129 | | lhs.RunWithReentrancyGuard([&] { |
3130 | | PolicyTraits::transfer(&rhs_alloc, to_slot(lhs.soo_data()), |
3131 | | to_slot(rhs.soo_data())); |
3132 | | }); |
3133 | | }); |
3134 | | } |
3135 | | } |
3136 | | |
3137 | | // Swaps common fields making sure to avoid memcpy'ing a full SOO slot if we |
3138 | | // aren't allowed to do so. |
3139 | | void swap_common(raw_hash_set& that) { |
3140 | | using std::swap; |
3141 | | if (PolicyTraits::transfer_uses_memcpy()) { |
3142 | | swap(common(), that.common()); |
3143 | | return; |
3144 | | } |
3145 | | CommonFields tmp = CommonFields(uninitialized_tag_t{}); |
3146 | | const bool that_is_full_soo = that.is_full_soo(); |
3147 | | move_common(that_is_full_soo, that.char_alloc_ref(), tmp, |
3148 | | std::move(that.common())); |
3149 | | move_common(is_full_soo(), char_alloc_ref(), that.common(), |
3150 | | std::move(common())); |
3151 | | move_common(that_is_full_soo, that.char_alloc_ref(), common(), |
3152 | | std::move(tmp)); |
3153 | | } |
3154 | | |
3155 | | void annotate_for_bug_detection_on_move([[maybe_unused]] raw_hash_set& that) { |
3156 | | // We only enable moved-from validation when generations are enabled (rather |
3157 | | // than using NDEBUG) to avoid issues in which NDEBUG is enabled in some |
3158 | | // translation units but not in others. |
3159 | | if (SwisstableGenerationsEnabled()) { |
3160 | | that.common().set_capacity(this == &that ? InvalidCapacity::kSelfMovedFrom |
3161 | | : InvalidCapacity::kMovedFrom); |
3162 | | } |
3163 | | if (!SwisstableGenerationsEnabled() || capacity() == DefaultCapacity() || |
3164 | | capacity() > kAboveMaxValidCapacity) { |
3165 | | return; |
3166 | | } |
3167 | | common().increment_generation(); |
3168 | | if (!empty() && common().should_rehash_for_bug_detection_on_move()) { |
3169 | | ResizeAllocatedTableWithSeedChange(common(), GetPolicyFunctions(), |
3170 | | capacity()); |
3171 | | } |
3172 | | } |
3173 | | |
3174 | | template <bool propagate_alloc> |
3175 | | raw_hash_set& assign_impl(raw_hash_set&& that) { |
3176 | | // We don't bother checking for this/that aliasing. We just need to avoid |
3177 | | // breaking the invariants in that case. |
3178 | | destructor_impl(); |
3179 | | move_common(that.is_full_soo(), that.char_alloc_ref(), common(), |
3180 | | std::move(that.common())); |
3181 | | hash_ref() = that.hash_ref(); |
3182 | | eq_ref() = that.eq_ref(); |
3183 | | CopyAlloc(char_alloc_ref(), that.char_alloc_ref(), |
3184 | | std::integral_constant<bool, propagate_alloc>()); |
3185 | | that.common() = CommonFields::CreateDefault<SooEnabled()>(); |
3186 | | annotate_for_bug_detection_on_move(that); |
3187 | | return *this; |
3188 | | } |
3189 | | |
3190 | | raw_hash_set& move_elements_allocs_unequal(raw_hash_set&& that) { |
3191 | | const size_t size = that.size(); |
3192 | | if (size == 0) return *this; |
3193 | | reserve(size); |
3194 | | for (iterator it = that.begin(); it != that.end(); ++it) { |
3195 | | insert(std::move(PolicyTraits::element(it.slot()))); |
3196 | | that.destroy(it.slot()); |
3197 | | } |
3198 | | if (!that.is_soo()) that.dealloc(); |
3199 | | that.common() = CommonFields::CreateDefault<SooEnabled()>(); |
3200 | | annotate_for_bug_detection_on_move(that); |
3201 | | return *this; |
3202 | | } |
3203 | | |
3204 | | raw_hash_set& move_assign(raw_hash_set&& that, |
3205 | | std::true_type /*propagate_alloc*/) { |
3206 | | return assign_impl<true>(std::move(that)); |
3207 | | } |
3208 | | raw_hash_set& move_assign(raw_hash_set&& that, |
3209 | | std::false_type /*propagate_alloc*/) { |
3210 | | if (char_alloc_ref() == that.char_alloc_ref()) { |
3211 | | return assign_impl<false>(std::move(that)); |
3212 | | } |
3213 | | // Aliasing can't happen here because allocs would compare equal above. |
3214 | | assert(this != &that); |
3215 | | destructor_impl(); |
3216 | | // We can't take over that's memory so we need to move each element. |
3217 | | // While moving elements, this should have that's hash/eq so copy hash/eq |
3218 | | // before moving elements. |
3219 | | hash_ref() = that.hash_ref(); |
3220 | | eq_ref() = that.eq_ref(); |
3221 | | return move_elements_allocs_unequal(std::move(that)); |
3222 | | } |
3223 | | |
3224 | | template <class K> |
3225 | | std::pair<iterator, bool> find_or_prepare_insert_soo(const K& key) { |
3226 | | ABSL_SWISSTABLE_ASSERT(is_soo()); |
3227 | | bool force_sampling; |
3228 | | if (empty()) { |
3229 | | if (!should_sample_soo()) { |
3230 | | common().set_full_soo(); |
3231 | | return {single_iterator(), true}; |
3232 | | } |
3233 | | force_sampling = true; |
3234 | | } else if (equal_to(key, single_slot())) { |
3235 | | return {single_iterator(), false}; |
3236 | | } else { |
3237 | | force_sampling = false; |
3238 | | } |
3239 | | ABSL_SWISSTABLE_ASSERT(capacity() == 1); |
3240 | | constexpr bool kUseMemcpy = |
3241 | | PolicyTraits::transfer_uses_memcpy() && SooEnabled(); |
3242 | | size_t index = GrowSooTableToNextCapacityAndPrepareInsert< |
3243 | | kUseMemcpy ? OptimalMemcpySizeForSooSlotTransfer(sizeof(slot_type)) : 0, |
3244 | | kUseMemcpy>(common(), GetPolicyFunctions(), |
3245 | | HashKey<hasher, K, kIsDefaultHash>{hash_ref(), key}, |
3246 | | force_sampling); |
3247 | | return {iterator_at(index), true}; |
3248 | | } |
3249 | | |
3250 | | template <class K> |
3251 | | std::pair<iterator, bool> find_or_prepare_insert_small(const K& key) { |
3252 | | ABSL_SWISSTABLE_ASSERT(is_small()); |
3253 | | if constexpr (SooEnabled()) { |
3254 | | return find_or_prepare_insert_soo(key); |
3255 | | } |
3256 | | if (!empty()) { |
3257 | | if (equal_to(key, single_slot())) { |
3258 | | return {single_iterator(), false}; |
3259 | | } |
3260 | | } |
3261 | | return {iterator_at_ptr(PrepareInsertSmallNonSoo( |
3262 | | common(), GetPolicyFunctions(), |
3263 | | HashKey<hasher, K, kIsDefaultHash>{hash_ref(), key})), |
3264 | | true}; |
3265 | | } |
3266 | | |
3267 | | template <class K> |
3268 | | std::pair<iterator, bool> find_or_prepare_insert_large(const K& key) { |
3269 | | ABSL_SWISSTABLE_ASSERT(!is_soo()); |
3270 | | prefetch_heap_block(); |
3271 | | const size_t hash = hash_of(key); |
3272 | | auto seq = probe(common(), hash); |
3273 | | const h2_t h2 = H2(hash); |
3274 | | const ctrl_t* ctrl = control(); |
3275 | | while (true) { |
3276 | | #ifndef ABSL_HAVE_MEMORY_SANITIZER |
3277 | | absl::PrefetchToLocalCache(slot_array() + seq.offset()); |
3278 | | #endif |
3279 | | Group g{ctrl + seq.offset()}; |
3280 | | for (uint32_t i : g.Match(h2)) { |
3281 | | if (ABSL_PREDICT_TRUE(equal_to(key, slot_array() + seq.offset(i)))) |
3282 | | return {iterator_at(seq.offset(i)), false}; |
3283 | | } |
3284 | | auto mask_empty = g.MaskEmpty(); |
3285 | | if (ABSL_PREDICT_TRUE(mask_empty)) { |
3286 | | size_t target = seq.offset(mask_empty.LowestBitSet()); |
3287 | | size_t index = |
3288 | | SwisstableGenerationsEnabled() |
3289 | | ? PrepareInsertLargeGenerationsEnabled( |
3290 | | common(), GetPolicyFunctions(), hash, |
3291 | | FindInfo{target, seq.index()}, |
3292 | | HashKey<hasher, K, kIsDefaultHash>{hash_ref(), key}) |
3293 | | : PrepareInsertLarge(common(), GetPolicyFunctions(), hash, |
3294 | | FindInfo{target, seq.index()}); |
3295 | | return {iterator_at(index), true}; |
3296 | | } |
3297 | | seq.next(); |
3298 | | ABSL_SWISSTABLE_ASSERT(seq.index() <= capacity() && "full table!"); |
3299 | | } |
3300 | | } |
3301 | | |
3302 | | protected: |
3303 | | // Asserts for correctness that we run on find/find_or_prepare_insert. |
3304 | | template <class K> |
3305 | | void AssertOnFind([[maybe_unused]] const K& key) { |
3306 | | AssertHashEqConsistent(key); |
3307 | | AssertNotDebugCapacity(); |
3308 | | } |
3309 | | |
3310 | | // Asserts that the capacity is not a sentinel invalid value. |
3311 | | void AssertNotDebugCapacity() const { |
3312 | | #ifdef NDEBUG |
3313 | | if (!SwisstableGenerationsEnabled()) { |
3314 | | return; |
3315 | | } |
3316 | | #endif |
3317 | | if (ABSL_PREDICT_TRUE(capacity() < |
3318 | | InvalidCapacity::kAboveMaxValidCapacity)) { |
3319 | | return; |
3320 | | } |
3321 | | assert(capacity() != InvalidCapacity::kReentrance && |
3322 | | "Reentrant container access during element construction/destruction " |
3323 | | "is not allowed."); |
3324 | | if constexpr (SwisstableAssertAccessToDestroyedTable()) { |
3325 | | if (capacity() == InvalidCapacity::kDestroyed) { |
3326 | | ABSL_RAW_LOG(FATAL, "Use of destroyed hash table."); |
3327 | | } |
3328 | | } |
3329 | | if (SwisstableGenerationsEnabled() && |
3330 | | ABSL_PREDICT_FALSE(capacity() >= InvalidCapacity::kMovedFrom)) { |
3331 | | if (capacity() == InvalidCapacity::kSelfMovedFrom) { |
3332 | | // If this log triggers, then a hash table was move-assigned to itself |
3333 | | // and then used again later without being reinitialized. |
3334 | | ABSL_RAW_LOG(FATAL, "Use of self-move-assigned hash table."); |
3335 | | } |
3336 | | ABSL_RAW_LOG(FATAL, "Use of moved-from hash table."); |
3337 | | } |
3338 | | } |
3339 | | |
3340 | | // Asserts that hash and equal functors provided by the user are consistent, |
3341 | | // meaning that `eq(k1, k2)` implies `hash(k1)==hash(k2)`. |
3342 | | template <class K> |
3343 | | void AssertHashEqConsistent(const K& key) { |
3344 | | #ifdef NDEBUG |
3345 | | return; |
3346 | | #endif |
3347 | | // If the hash/eq functors are known to be consistent, then skip validation. |
3348 | | if (std::is_same<hasher, absl::container_internal::StringHash>::value && |
3349 | | std::is_same<key_equal, absl::container_internal::StringEq>::value) { |
3350 | | return; |
3351 | | } |
3352 | | if (std::is_scalar<key_type>::value && |
3353 | | std::is_same<hasher, absl::Hash<key_type>>::value && |
3354 | | std::is_same<key_equal, std::equal_to<key_type>>::value) { |
3355 | | return; |
3356 | | } |
3357 | | if (empty()) return; |
3358 | | |
3359 | | const size_t hash_of_arg = hash_of(key); |
3360 | | const auto assert_consistent = [&](const ctrl_t*, void* slot) { |
3361 | | const bool is_key_equal = equal_to(key, to_slot(slot)); |
3362 | | if (!is_key_equal) return; |
3363 | | |
3364 | | [[maybe_unused]] const bool is_hash_equal = |
3365 | | hash_of_arg == hash_of(to_slot(slot)); |
3366 | | assert((!is_key_equal || is_hash_equal) && |
3367 | | "eq(k1, k2) must imply that hash(k1) == hash(k2). " |
3368 | | "hash/eq functors are inconsistent."); |
3369 | | }; |
3370 | | |
3371 | | if (is_small()) { |
3372 | | assert_consistent(/*unused*/ nullptr, single_slot()); |
3373 | | return; |
3374 | | } |
3375 | | // We only do validation for small tables so that it's constant time. |
3376 | | if (capacity() > 16) return; |
3377 | | IterateOverFullSlots(common(), sizeof(slot_type), assert_consistent); |
3378 | | } |
3379 | | |
3380 | | // Attempts to find `key` in the table; if it isn't found, returns an iterator |
3381 | | // where the value can be inserted into, with the control byte already set to |
3382 | | // `key`'s H2. Returns a bool indicating whether an insertion can take place. |
3383 | | template <class K> |
3384 | | std::pair<iterator, bool> find_or_prepare_insert(const K& key) { |
3385 | | AssertOnFind(key); |
3386 | | if (is_small()) return find_or_prepare_insert_small(key); |
3387 | | return find_or_prepare_insert_large(key); |
3388 | | } |
3389 | | |
3390 | | // Constructs the value in the space pointed by the iterator. This only works |
3391 | | // after an unsuccessful find_or_prepare_insert() and before any other |
3392 | | // modifications happen in the raw_hash_set. |
3393 | | // |
3394 | | // PRECONDITION: iter was returned from find_or_prepare_insert(k), where k is |
3395 | | // the key decomposed from `forward<Args>(args)...`, and the bool returned by |
3396 | | // find_or_prepare_insert(k) was true. |
3397 | | // POSTCONDITION: *m.iterator_at(i) == value_type(forward<Args>(args)...). |
3398 | | template <class... Args> |
3399 | | void emplace_at(iterator iter, Args&&... args) { |
3400 | | construct(iter.slot(), std::forward<Args>(args)...); |
3401 | | |
3402 | | // When is_small, find calls find_small and if size is 0, then it will |
3403 | | // return an end iterator. This can happen in the raw_hash_set copy ctor. |
3404 | | assert((is_small() || |
3405 | | PolicyTraits::apply(FindElement{*this}, *iter) == iter) && |
3406 | | "constructed value does not match the lookup key"); |
3407 | | } |
3408 | | |
3409 | | iterator iterator_at(size_t i) ABSL_ATTRIBUTE_LIFETIME_BOUND { |
3410 | | return {control() + i, slot_array() + i, common().generation_ptr()}; |
3411 | | } |
3412 | | const_iterator iterator_at(size_t i) const ABSL_ATTRIBUTE_LIFETIME_BOUND { |
3413 | | return const_cast<raw_hash_set*>(this)->iterator_at(i); |
3414 | | } |
3415 | | iterator iterator_at_ptr(std::pair<ctrl_t*, void*> ptrs) |
3416 | | ABSL_ATTRIBUTE_LIFETIME_BOUND { |
3417 | | return {ptrs.first, to_slot(ptrs.second), common().generation_ptr()}; |
3418 | | } |
3419 | | |
3420 | | reference unchecked_deref(iterator it) { return it.unchecked_deref(); } |
3421 | | |
3422 | | private: |
3423 | | friend struct RawHashSetTestOnlyAccess; |
3424 | | |
3425 | | // The number of slots we can still fill without needing to rehash. |
3426 | | // |
3427 | | // This is stored separately due to tombstones: we do not include tombstones |
3428 | | // in the growth capacity, because we'd like to rehash when the table is |
3429 | | // otherwise filled with tombstones: otherwise, probe sequences might get |
3430 | | // unacceptably long without triggering a rehash. Callers can also force a |
3431 | | // rehash via the standard `rehash(0)`, which will recompute this value as a |
3432 | | // side-effect. |
3433 | | // |
3434 | | // See `CapacityToGrowth()`. |
3435 | | size_t growth_left() const { |
3436 | | return common().growth_left(); |
3437 | | } |
3438 | | |
3439 | | GrowthInfo& growth_info() { |
3440 | | return common().growth_info(); |
3441 | | } |
3442 | | GrowthInfo growth_info() const { |
3443 | | return common().growth_info(); |
3444 | | } |
3445 | | |
3446 | | // Prefetch the heap-allocated memory region to resolve potential TLB and |
3447 | | // cache misses. This is intended to overlap with execution of calculating the |
3448 | | // hash for a key. |
3449 | | void prefetch_heap_block() const { |
3450 | | ABSL_SWISSTABLE_ASSERT(!is_soo()); |
3451 | | #if ABSL_HAVE_BUILTIN(__builtin_prefetch) || defined(__GNUC__) |
3452 | | __builtin_prefetch(control(), 0, 1); |
3453 | | #endif |
3454 | | } |
3455 | | |
3456 | | CommonFields& common() { return settings_.template get<0>(); } |
3457 | | const CommonFields& common() const { return settings_.template get<0>(); } |
3458 | | |
3459 | | ctrl_t* control() const { |
3460 | | ABSL_SWISSTABLE_ASSERT(!is_soo()); |
3461 | | return common().control(); |
3462 | | } |
3463 | | slot_type* slot_array() const { |
3464 | | ABSL_SWISSTABLE_ASSERT(!is_soo()); |
3465 | | return static_cast<slot_type*>(common().slot_array()); |
3466 | | } |
3467 | | slot_type* soo_slot() { |
3468 | | ABSL_SWISSTABLE_ASSERT(is_soo()); |
3469 | | ABSL_SWISSTABLE_IGNORE_UNINITIALIZED_RETURN( |
3470 | | static_cast<slot_type*>(common().soo_data())); |
3471 | | } |
3472 | | const slot_type* soo_slot() const { |
3473 | | ABSL_SWISSTABLE_IGNORE_UNINITIALIZED_RETURN( |
3474 | | const_cast<raw_hash_set*>(this)->soo_slot()); |
3475 | | } |
3476 | | slot_type* single_slot() { |
3477 | | ABSL_SWISSTABLE_ASSERT(is_small()); |
3478 | | return SooEnabled() ? soo_slot() : slot_array(); |
3479 | | } |
3480 | | const slot_type* single_slot() const { |
3481 | | return const_cast<raw_hash_set*>(this)->single_slot(); |
3482 | | } |
3483 | | void decrement_small_size() { |
3484 | | ABSL_SWISSTABLE_ASSERT(is_small()); |
3485 | | SooEnabled() ? common().set_empty_soo() : common().decrement_size(); |
3486 | | if (!SooEnabled()) { |
3487 | | SanitizerPoisonObject(single_slot()); |
3488 | | } |
3489 | | } |
3490 | | iterator single_iterator() { |
3491 | | return {SooControl(), single_slot(), common().generation_ptr()}; |
3492 | | } |
3493 | | const_iterator single_iterator() const { |
3494 | | return const_cast<raw_hash_set*>(this)->single_iterator(); |
3495 | | } |
3496 | | HashtablezInfoHandle infoz() { |
3497 | | ABSL_SWISSTABLE_ASSERT(!is_soo()); |
3498 | | return common().infoz(); |
3499 | | } |
3500 | | |
3501 | | hasher& hash_ref() { return settings_.template get<1>(); } |
3502 | | const hasher& hash_ref() const { return settings_.template get<1>(); } |
3503 | | key_equal& eq_ref() { return settings_.template get<2>(); } |
3504 | | const key_equal& eq_ref() const { return settings_.template get<2>(); } |
3505 | | CharAlloc& char_alloc_ref() { return settings_.template get<3>(); } |
3506 | | const CharAlloc& char_alloc_ref() const { |
3507 | | return settings_.template get<3>(); |
3508 | | } |
3509 | | |
3510 | | static void* get_char_alloc_ref_fn(CommonFields& common) { |
3511 | | auto* h = reinterpret_cast<raw_hash_set*>(&common); |
3512 | | return &h->char_alloc_ref(); |
3513 | | } |
3514 | | static void* get_hash_ref_fn(CommonFields& common) { |
3515 | | auto* h = reinterpret_cast<raw_hash_set*>(&common); |
3516 | | // TODO(b/397453582): Remove support for const hasher. |
3517 | | return const_cast<std::remove_const_t<hasher>*>(&h->hash_ref()); |
3518 | | } |
3519 | | static void transfer_n_slots_fn(void* set, void* dst, void* src, |
3520 | | size_t count) { |
3521 | | auto* src_slot = to_slot(src); |
3522 | | auto* dst_slot = to_slot(dst); |
3523 | | |
3524 | | auto* h = static_cast<raw_hash_set*>(set); |
3525 | | for (; count > 0; --count, ++src_slot, ++dst_slot) { |
3526 | | h->transfer(dst_slot, src_slot); |
3527 | | } |
3528 | | } |
3529 | | |
3530 | | // TODO(b/382423690): Try to type erase entire function or at least type erase |
3531 | | // by GetKey + Hash for memcpyable types. |
3532 | | // TODO(b/382423690): Try to type erase for big slots: sizeof(slot_type) > 16. |
3533 | | static void transfer_unprobed_elements_to_next_capacity_fn( |
3534 | | CommonFields& common, const ctrl_t* old_ctrl, void* old_slots, |
3535 | | void* probed_storage, |
3536 | | void (*encode_probed_element)(void* probed_storage, h2_t h2, |
3537 | | size_t source_offset, size_t h1)) { |
3538 | | const size_t new_capacity = common.capacity(); |
3539 | | const size_t old_capacity = PreviousCapacity(new_capacity); |
3540 | | ABSL_ASSUME(old_capacity + 1 >= Group::kWidth); |
3541 | | ABSL_ASSUME((old_capacity + 1) % Group::kWidth == 0); |
3542 | | |
3543 | | auto* set = reinterpret_cast<raw_hash_set*>(&common); |
3544 | | slot_type* old_slots_ptr = to_slot(old_slots); |
3545 | | ctrl_t* new_ctrl = common.control(); |
3546 | | slot_type* new_slots = set->slot_array(); |
3547 | | |
3548 | | for (size_t group_index = 0; group_index < old_capacity; |
3549 | | group_index += Group::kWidth) { |
3550 | | GroupFullEmptyOrDeleted old_g(old_ctrl + group_index); |
3551 | | std::memset(new_ctrl + group_index, static_cast<int8_t>(ctrl_t::kEmpty), |
3552 | | Group::kWidth); |
3553 | | std::memset(new_ctrl + group_index + old_capacity + 1, |
3554 | | static_cast<int8_t>(ctrl_t::kEmpty), Group::kWidth); |
3555 | | // TODO(b/382423690): try to type erase everything outside of the loop. |
3556 | | // We will share a lot of code in expense of one function call per group. |
3557 | | for (auto in_fixed_group_index : old_g.MaskFull()) { |
3558 | | size_t old_index = group_index + in_fixed_group_index; |
3559 | | slot_type* old_slot = old_slots_ptr + old_index; |
3560 | | // TODO(b/382423690): try to avoid entire hash calculation since we need |
3561 | | // only one new bit of h1. |
3562 | | size_t hash = set->hash_of(old_slot); |
3563 | | size_t h1 = H1(hash); |
3564 | | h2_t h2 = H2(hash); |
3565 | | size_t new_index = TryFindNewIndexWithoutProbing( |
3566 | | h1, old_index, old_capacity, new_ctrl, new_capacity); |
3567 | | // Note that encode_probed_element is allowed to use old_ctrl buffer |
3568 | | // till and included the old_index. |
3569 | | if (ABSL_PREDICT_FALSE(new_index == kProbedElementIndexSentinel)) { |
3570 | | encode_probed_element(probed_storage, h2, old_index, h1); |
3571 | | continue; |
3572 | | } |
3573 | | ABSL_SWISSTABLE_ASSERT((new_index & old_capacity) <= old_index); |
3574 | | ABSL_SWISSTABLE_ASSERT(IsEmpty(new_ctrl[new_index])); |
3575 | | new_ctrl[new_index] = static_cast<ctrl_t>(h2); |
3576 | | auto* new_slot = new_slots + new_index; |
3577 | | SanitizerUnpoisonMemoryRegion(new_slot, sizeof(slot_type)); |
3578 | | set->transfer(new_slot, old_slot); |
3579 | | SanitizerPoisonMemoryRegion(old_slot, sizeof(slot_type)); |
3580 | | } |
3581 | | } |
3582 | | } |
3583 | | |
3584 | | static const PolicyFunctions& GetPolicyFunctions() { |
3585 | | static_assert(sizeof(slot_type) <= (std::numeric_limits<uint32_t>::max)(), |
3586 | | "Slot size is too large. Use std::unique_ptr for value type " |
3587 | | "or use absl::node_hash_{map,set}."); |
3588 | | static_assert(alignof(slot_type) <= |
3589 | | size_t{(std::numeric_limits<uint16_t>::max)()}); |
3590 | | static_assert(sizeof(key_type) <= |
3591 | | size_t{(std::numeric_limits<uint32_t>::max)()}); |
3592 | | static_assert(sizeof(value_type) <= |
3593 | | size_t{(std::numeric_limits<uint32_t>::max)()}); |
3594 | | static constexpr size_t kBackingArrayAlignment = |
3595 | | BackingArrayAlignment(alignof(slot_type)); |
3596 | | static constexpr PolicyFunctions value = { |
3597 | | static_cast<uint32_t>(sizeof(key_type)), |
3598 | | static_cast<uint32_t>(sizeof(value_type)), |
3599 | | static_cast<uint32_t>(sizeof(slot_type)), |
3600 | | static_cast<uint16_t>(alignof(slot_type)), SooEnabled(), |
3601 | | ShouldSampleHashtablezInfoForAlloc<CharAlloc>(), |
3602 | | // TODO(b/328722020): try to type erase |
3603 | | // for standard layout and alignof(Hash) <= alignof(CommonFields). |
3604 | | std::is_empty_v<hasher> ? &GetRefForEmptyClass |
3605 | | : &raw_hash_set::get_hash_ref_fn, |
3606 | | PolicyTraits::template get_hash_slot_fn<hasher, kIsDefaultHash>(), |
3607 | | PolicyTraits::transfer_uses_memcpy() |
3608 | | ? TransferNRelocatable<sizeof(slot_type)> |
3609 | | : &raw_hash_set::transfer_n_slots_fn, |
3610 | | std::is_empty_v<Alloc> ? &GetRefForEmptyClass |
3611 | | : &raw_hash_set::get_char_alloc_ref_fn, |
3612 | | &AllocateBackingArray<kBackingArrayAlignment, CharAlloc>, |
3613 | | &DeallocateBackingArray<kBackingArrayAlignment, CharAlloc>, |
3614 | | &raw_hash_set::transfer_unprobed_elements_to_next_capacity_fn}; |
3615 | | return value; |
3616 | | } |
3617 | | |
3618 | | // Bundle together CommonFields plus other objects which might be empty. |
3619 | | // CompressedTuple will ensure that sizeof is not affected by any of the empty |
3620 | | // fields that occur after CommonFields. |
3621 | | absl::container_internal::CompressedTuple<CommonFields, hasher, key_equal, |
3622 | | CharAlloc> |
3623 | | settings_{CommonFields::CreateDefault<SooEnabled()>(), hasher{}, |
3624 | | key_equal{}, CharAlloc{}}; |
3625 | | }; |
3626 | | |
3627 | | // Friend access for free functions in raw_hash_set.h. |
3628 | | struct HashtableFreeFunctionsAccess { |
3629 | | template <class Predicate, typename Set> |
3630 | | static typename Set::size_type EraseIf(Predicate& pred, Set* c) { |
3631 | | if (c->empty()) { |
3632 | | return 0; |
3633 | | } |
3634 | | if (c->is_small()) { |
3635 | | auto it = c->single_iterator(); |
3636 | | if (!pred(*it)) { |
3637 | | ABSL_SWISSTABLE_ASSERT(c->size() == 1 && |
3638 | | "hash table was modified unexpectedly"); |
3639 | | return 0; |
3640 | | } |
3641 | | c->destroy(it.slot()); |
3642 | | c->erase_meta_only(it); |
3643 | | return 1; |
3644 | | } |
3645 | | [[maybe_unused]] const size_t original_size_for_assert = c->size(); |
3646 | | size_t num_deleted = 0; |
3647 | | using SlotType = typename Set::slot_type; |
3648 | | IterateOverFullSlots( |
3649 | | c->common(), sizeof(SlotType), |
3650 | | [&](const ctrl_t* ctrl, void* slot_void) { |
3651 | | auto* slot = static_cast<SlotType*>(slot_void); |
3652 | | if (pred(Set::PolicyTraits::element(slot))) { |
3653 | | c->destroy(slot); |
3654 | | EraseMetaOnly(c->common(), ctrl, sizeof(*slot)); |
3655 | | ++num_deleted; |
3656 | | } |
3657 | | }); |
3658 | | // NOTE: IterateOverFullSlots allow removal of the current element, so we |
3659 | | // verify the size additionally here. |
3660 | | ABSL_SWISSTABLE_ASSERT(original_size_for_assert - num_deleted == |
3661 | | c->size() && |
3662 | | "hash table was modified unexpectedly"); |
3663 | | return num_deleted; |
3664 | | } |
3665 | | |
3666 | | template <class Callback, typename Set> |
3667 | | static void ForEach(Callback& cb, Set* c) { |
3668 | | if (c->empty()) { |
3669 | | return; |
3670 | | } |
3671 | | if (c->is_small()) { |
3672 | | cb(*c->single_iterator()); |
3673 | | return; |
3674 | | } |
3675 | | using SlotType = typename Set::slot_type; |
3676 | | using ElementTypeWithConstness = decltype(*c->begin()); |
3677 | | IterateOverFullSlots( |
3678 | | c->common(), sizeof(SlotType), [&cb](const ctrl_t*, void* slot) { |
3679 | | ElementTypeWithConstness& element = |
3680 | | Set::PolicyTraits::element(static_cast<SlotType*>(slot)); |
3681 | | cb(element); |
3682 | | }); |
3683 | | } |
3684 | | }; |
3685 | | |
3686 | | // Erases all elements that satisfy the predicate `pred` from the container `c`. |
3687 | | template <typename P, typename H, typename E, typename A, typename Predicate> |
3688 | | typename raw_hash_set<P, H, E, A>::size_type EraseIf( |
3689 | | Predicate& pred, raw_hash_set<P, H, E, A>* c) { |
3690 | | return HashtableFreeFunctionsAccess::EraseIf(pred, c); |
3691 | | } |
3692 | | |
3693 | | // Calls `cb` for all elements in the container `c`. |
3694 | | template <typename P, typename H, typename E, typename A, typename Callback> |
3695 | | void ForEach(Callback& cb, raw_hash_set<P, H, E, A>* c) { |
3696 | | return HashtableFreeFunctionsAccess::ForEach(cb, c); |
3697 | | } |
3698 | | template <typename P, typename H, typename E, typename A, typename Callback> |
3699 | | void ForEach(Callback& cb, const raw_hash_set<P, H, E, A>* c) { |
3700 | | return HashtableFreeFunctionsAccess::ForEach(cb, c); |
3701 | | } |
3702 | | |
3703 | | namespace hashtable_debug_internal { |
3704 | | template <typename Set> |
3705 | | struct HashtableDebugAccess<Set, absl::void_t<typename Set::raw_hash_set>> { |
3706 | | using Traits = typename Set::PolicyTraits; |
3707 | | using Slot = typename Traits::slot_type; |
3708 | | |
3709 | | constexpr static bool kIsDefaultHash = Set::kIsDefaultHash; |
3710 | | |
3711 | | static size_t GetNumProbes(const Set& set, |
3712 | | const typename Set::key_type& key) { |
3713 | | if (set.is_small()) return 0; |
3714 | | size_t num_probes = 0; |
3715 | | const size_t hash = set.hash_of(key); |
3716 | | auto seq = probe(set.common(), hash); |
3717 | | const h2_t h2 = H2(hash); |
3718 | | const ctrl_t* ctrl = set.control(); |
3719 | | while (true) { |
3720 | | container_internal::Group g{ctrl + seq.offset()}; |
3721 | | for (uint32_t i : g.Match(h2)) { |
3722 | | if (set.equal_to(key, set.slot_array() + seq.offset(i))) |
3723 | | return num_probes; |
3724 | | ++num_probes; |
3725 | | } |
3726 | | if (g.MaskEmpty()) return num_probes; |
3727 | | seq.next(); |
3728 | | ++num_probes; |
3729 | | } |
3730 | | } |
3731 | | |
3732 | | static size_t AllocatedByteSize(const Set& c) { |
3733 | | size_t capacity = c.capacity(); |
3734 | | if (capacity == 0) return 0; |
3735 | | size_t m = |
3736 | | c.is_soo() ? 0 : c.common().alloc_size(sizeof(Slot), alignof(Slot)); |
3737 | | |
3738 | | size_t per_slot = Traits::space_used(static_cast<const Slot*>(nullptr)); |
3739 | | if (per_slot != ~size_t{}) { |
3740 | | m += per_slot * c.size(); |
3741 | | } else { |
3742 | | for (auto it = c.begin(); it != c.end(); ++it) { |
3743 | | m += Traits::space_used(it.slot()); |
3744 | | } |
3745 | | } |
3746 | | return m; |
3747 | | } |
3748 | | }; |
3749 | | |
3750 | | } // namespace hashtable_debug_internal |
3751 | | |
3752 | | // Extern template instantiations reduce binary size and linker input size. |
3753 | | // Function definition is in raw_hash_set.cc. |
3754 | | extern template size_t GrowSooTableToNextCapacityAndPrepareInsert<0, false>( |
3755 | | CommonFields&, const PolicyFunctions&, absl::FunctionRef<size_t(size_t)>, |
3756 | | bool); |
3757 | | extern template size_t GrowSooTableToNextCapacityAndPrepareInsert<1, true>( |
3758 | | CommonFields&, const PolicyFunctions&, absl::FunctionRef<size_t(size_t)>, |
3759 | | bool); |
3760 | | extern template size_t GrowSooTableToNextCapacityAndPrepareInsert<4, true>( |
3761 | | CommonFields&, const PolicyFunctions&, absl::FunctionRef<size_t(size_t)>, |
3762 | | bool); |
3763 | | extern template size_t GrowSooTableToNextCapacityAndPrepareInsert<8, true>( |
3764 | | CommonFields&, const PolicyFunctions&, absl::FunctionRef<size_t(size_t)>, |
3765 | | bool); |
3766 | | #if UINTPTR_MAX == UINT64_MAX |
3767 | | extern template size_t GrowSooTableToNextCapacityAndPrepareInsert<16, true>( |
3768 | | CommonFields&, const PolicyFunctions&, absl::FunctionRef<size_t(size_t)>, |
3769 | | bool); |
3770 | | #endif |
3771 | | |
3772 | | } // namespace container_internal |
3773 | | ABSL_NAMESPACE_END |
3774 | | } // namespace absl |
3775 | | |
3776 | | #undef ABSL_SWISSTABLE_ENABLE_GENERATIONS |
3777 | | #undef ABSL_SWISSTABLE_IGNORE_UNINITIALIZED |
3778 | | #undef ABSL_SWISSTABLE_IGNORE_UNINITIALIZED_RETURN |
3779 | | #undef ABSL_SWISSTABLE_ASSERT |
3780 | | |
3781 | | #endif // ABSL_CONTAINER_INTERNAL_RAW_HASH_SET_H_ |