Coverage Report

Created: 2025-12-31 06:30

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