Coverage Report

Created: 2026-02-26 07:14

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