Coverage Report

Created: 2026-02-14 07:09

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