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