Coverage Report

Created: 2025-11-24 06:23

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