Coverage Report

Created: 2025-07-09 06:39

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