Coverage Report

Created: 2025-10-09 07:07

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