blob: 74b2ef4cc29f2b043bc585b2203eab1b778eb34f [file] [log] [blame]
Austin Schuh36244a12019-09-21 17:52:38 -07001// 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// find() also supports passing the hash explicitly:
45//
46// iterator find(const key_type& key, size_t hash);
47// template <class U>
48// iterator find(const U& key, size_t hash);
49//
50// In addition the pointer to element and iterator stability guarantees are
51// weaker: all iterators and pointers are invalidated after a new element is
52// inserted.
53//
54// IMPLEMENTATION DETAILS
55//
56// The table stores elements inline in a slot array. In addition to the slot
57// array the table maintains some control state per slot. The extra state is one
58// byte per slot and stores empty or deleted marks, or alternatively 7 bits from
59// the hash of an occupied slot. The table is split into logical groups of
60// slots, like so:
61//
62// Group 1 Group 2 Group 3
63// +---------------+---------------+---------------+
64// | | | | | | | | | | | | | | | | | | | | | | | | |
65// +---------------+---------------+---------------+
66//
67// On lookup the hash is split into two parts:
68// - H2: 7 bits (those stored in the control bytes)
69// - H1: the rest of the bits
70// The groups are probed using H1. For each group the slots are matched to H2 in
71// parallel. Because H2 is 7 bits (128 states) and the number of slots per group
72// is low (8 or 16) in almost all cases a match in H2 is also a lookup hit.
73//
74// On insert, once the right group is found (as in lookup), its slots are
75// filled in order.
76//
77// On erase a slot is cleared. In case the group did not have any empty slots
78// before the erase, the erased slot is marked as deleted.
79//
80// Groups without empty slots (but maybe with deleted slots) extend the probe
81// sequence. The probing algorithm is quadratic. Given N the number of groups,
82// the probing function for the i'th probe is:
83//
84// P(0) = H1 % N
85//
86// P(i) = (P(i - 1) + i) % N
87//
88// This probing function guarantees that after N probes, all the groups of the
89// table will be probed exactly once.
90
91#ifndef ABSL_CONTAINER_INTERNAL_RAW_HASH_SET_H_
92#define ABSL_CONTAINER_INTERNAL_RAW_HASH_SET_H_
93
94#include <algorithm>
95#include <cmath>
96#include <cstdint>
97#include <cstring>
98#include <iterator>
99#include <limits>
100#include <memory>
101#include <tuple>
102#include <type_traits>
103#include <utility>
104
Austin Schuh36244a12019-09-21 17:52:38 -0700105#include "absl/base/internal/endian.h"
Austin Schuhb4691e92020-12-31 12:37:18 -0800106#include "absl/base/optimization.h"
Austin Schuh36244a12019-09-21 17:52:38 -0700107#include "absl/base/port.h"
108#include "absl/container/internal/common.h"
109#include "absl/container/internal/compressed_tuple.h"
110#include "absl/container/internal/container_memory.h"
111#include "absl/container/internal/hash_policy_traits.h"
112#include "absl/container/internal/hashtable_debug_hooks.h"
113#include "absl/container/internal/hashtablez_sampler.h"
114#include "absl/container/internal/have_sse.h"
115#include "absl/container/internal/layout.h"
116#include "absl/memory/memory.h"
117#include "absl/meta/type_traits.h"
Austin Schuhb4691e92020-12-31 12:37:18 -0800118#include "absl/numeric/bits.h"
Austin Schuh36244a12019-09-21 17:52:38 -0700119#include "absl/utility/utility.h"
120
121namespace absl {
Austin Schuhb4691e92020-12-31 12:37:18 -0800122ABSL_NAMESPACE_BEGIN
Austin Schuh36244a12019-09-21 17:52:38 -0700123namespace container_internal {
124
Austin Schuhb4691e92020-12-31 12:37:18 -0800125template <typename AllocType>
126void SwapAlloc(AllocType& lhs, AllocType& rhs,
127 std::true_type /* propagate_on_container_swap */) {
128 using std::swap;
129 swap(lhs, rhs);
130}
131template <typename AllocType>
132void SwapAlloc(AllocType& /*lhs*/, AllocType& /*rhs*/,
133 std::false_type /* propagate_on_container_swap */) {}
134
Austin Schuh36244a12019-09-21 17:52:38 -0700135template <size_t Width>
136class probe_seq {
137 public:
138 probe_seq(size_t hash, size_t mask) {
139 assert(((mask + 1) & mask) == 0 && "not a mask");
140 mask_ = mask;
141 offset_ = hash & mask_;
142 }
143 size_t offset() const { return offset_; }
144 size_t offset(size_t i) const { return (offset_ + i) & mask_; }
145
146 void next() {
147 index_ += Width;
148 offset_ += index_;
149 offset_ &= mask_;
150 }
151 // 0-based probe index. The i-th probe in the probe sequence.
152 size_t index() const { return index_; }
153
154 private:
155 size_t mask_;
156 size_t offset_;
157 size_t index_ = 0;
158};
159
160template <class ContainerKey, class Hash, class Eq>
161struct RequireUsableKey {
162 template <class PassedKey, class... Args>
163 std::pair<
164 decltype(std::declval<const Hash&>()(std::declval<const PassedKey&>())),
165 decltype(std::declval<const Eq&>()(std::declval<const ContainerKey&>(),
166 std::declval<const PassedKey&>()))>*
167 operator()(const PassedKey&, const Args&...) const;
168};
169
170template <class E, class Policy, class Hash, class Eq, class... Ts>
171struct IsDecomposable : std::false_type {};
172
173template <class Policy, class Hash, class Eq, class... Ts>
174struct IsDecomposable<
175 absl::void_t<decltype(
176 Policy::apply(RequireUsableKey<typename Policy::key_type, Hash, Eq>(),
177 std::declval<Ts>()...))>,
178 Policy, Hash, Eq, Ts...> : std::true_type {};
179
180// TODO(alkis): Switch to std::is_nothrow_swappable when gcc/clang supports it.
181template <class T>
Austin Schuhb4691e92020-12-31 12:37:18 -0800182constexpr bool IsNoThrowSwappable(std::true_type = {} /* is_swappable */) {
Austin Schuh36244a12019-09-21 17:52:38 -0700183 using std::swap;
184 return noexcept(swap(std::declval<T&>(), std::declval<T&>()));
185}
Austin Schuhb4691e92020-12-31 12:37:18 -0800186template <class T>
187constexpr bool IsNoThrowSwappable(std::false_type /* is_swappable */) {
188 return false;
Austin Schuh36244a12019-09-21 17:52:38 -0700189}
190
191template <typename T>
Austin Schuhb4691e92020-12-31 12:37:18 -0800192uint32_t TrailingZeros(T x) {
193 ABSL_INTERNAL_ASSUME(x != 0);
194 return countr_zero(x);
Austin Schuh36244a12019-09-21 17:52:38 -0700195}
196
197// An abstraction over a bitmask. It provides an easy way to iterate through the
198// indexes of the set bits of a bitmask. When Shift=0 (platforms with SSE),
199// this is a true bitmask. On non-SSE, platforms the arithematic used to
200// emulate the SSE behavior works in bytes (Shift=3) and leaves each bytes as
201// either 0x00 or 0x80.
202//
203// For example:
204// for (int i : BitMask<uint32_t, 16>(0x5)) -> yields 0, 2
205// for (int i : BitMask<uint64_t, 8, 3>(0x0000000080800000)) -> yields 2, 3
206template <class T, int SignificantBits, int Shift = 0>
207class BitMask {
208 static_assert(std::is_unsigned<T>::value, "");
209 static_assert(Shift == 0 || Shift == 3, "");
210
211 public:
212 // These are useful for unit tests (gunit).
213 using value_type = int;
214 using iterator = BitMask;
215 using const_iterator = BitMask;
216
217 explicit BitMask(T mask) : mask_(mask) {}
218 BitMask& operator++() {
219 mask_ &= (mask_ - 1);
220 return *this;
221 }
222 explicit operator bool() const { return mask_ != 0; }
223 int operator*() const { return LowestBitSet(); }
Austin Schuhb4691e92020-12-31 12:37:18 -0800224 uint32_t LowestBitSet() const {
Austin Schuh36244a12019-09-21 17:52:38 -0700225 return container_internal::TrailingZeros(mask_) >> Shift;
226 }
Austin Schuhb4691e92020-12-31 12:37:18 -0800227 uint32_t HighestBitSet() const {
228 return static_cast<uint32_t>((bit_width(mask_) - 1) >> Shift);
Austin Schuh36244a12019-09-21 17:52:38 -0700229 }
230
231 BitMask begin() const { return *this; }
232 BitMask end() const { return BitMask(0); }
233
Austin Schuhb4691e92020-12-31 12:37:18 -0800234 uint32_t TrailingZeros() const {
Austin Schuh36244a12019-09-21 17:52:38 -0700235 return container_internal::TrailingZeros(mask_) >> Shift;
236 }
237
Austin Schuhb4691e92020-12-31 12:37:18 -0800238 uint32_t LeadingZeros() const {
Austin Schuh36244a12019-09-21 17:52:38 -0700239 constexpr int total_significant_bits = SignificantBits << Shift;
240 constexpr int extra_bits = sizeof(T) * 8 - total_significant_bits;
Austin Schuhb4691e92020-12-31 12:37:18 -0800241 return countl_zero(mask_ << extra_bits) >> Shift;
Austin Schuh36244a12019-09-21 17:52:38 -0700242 }
243
244 private:
245 friend bool operator==(const BitMask& a, const BitMask& b) {
246 return a.mask_ == b.mask_;
247 }
248 friend bool operator!=(const BitMask& a, const BitMask& b) {
249 return a.mask_ != b.mask_;
250 }
251
252 T mask_;
253};
254
255using ctrl_t = signed char;
256using h2_t = uint8_t;
257
258// The values here are selected for maximum performance. See the static asserts
259// below for details.
260enum Ctrl : ctrl_t {
261 kEmpty = -128, // 0b10000000
262 kDeleted = -2, // 0b11111110
263 kSentinel = -1, // 0b11111111
264};
265static_assert(
266 kEmpty & kDeleted & kSentinel & 0x80,
267 "Special markers need to have the MSB to make checking for them efficient");
268static_assert(kEmpty < kSentinel && kDeleted < kSentinel,
269 "kEmpty and kDeleted must be smaller than kSentinel to make the "
270 "SIMD test of IsEmptyOrDeleted() efficient");
271static_assert(kSentinel == -1,
272 "kSentinel must be -1 to elide loading it from memory into SIMD "
273 "registers (pcmpeqd xmm, xmm)");
274static_assert(kEmpty == -128,
275 "kEmpty must be -128 to make the SIMD check for its "
276 "existence efficient (psignb xmm, xmm)");
277static_assert(~kEmpty & ~kDeleted & kSentinel & 0x7F,
278 "kEmpty and kDeleted must share an unset bit that is not shared "
279 "by kSentinel to make the scalar test for MatchEmptyOrDeleted() "
280 "efficient");
281static_assert(kDeleted == -2,
282 "kDeleted must be -2 to make the implementation of "
283 "ConvertSpecialToEmptyAndFullToDeleted efficient");
284
285// A single block of empty control bytes for tables without any slots allocated.
286// This enables removing a branch in the hot path of find().
287inline ctrl_t* EmptyGroup() {
288 alignas(16) static constexpr ctrl_t empty_group[] = {
289 kSentinel, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty,
290 kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty};
291 return const_cast<ctrl_t*>(empty_group);
292}
293
294// Mixes a randomly generated per-process seed with `hash` and `ctrl` to
295// randomize insertion order within groups.
296bool ShouldInsertBackwards(size_t hash, ctrl_t* ctrl);
297
298// Returns a hash seed.
299//
300// The seed consists of the ctrl_ pointer, which adds enough entropy to ensure
301// non-determinism of iteration order in most cases.
302inline size_t HashSeed(const ctrl_t* ctrl) {
303 // The low bits of the pointer have little or no entropy because of
304 // alignment. We shift the pointer to try to use higher entropy bits. A
305 // good number seems to be 12 bits, because that aligns with page size.
306 return reinterpret_cast<uintptr_t>(ctrl) >> 12;
307}
308
309inline size_t H1(size_t hash, const ctrl_t* ctrl) {
310 return (hash >> 7) ^ HashSeed(ctrl);
311}
312inline ctrl_t H2(size_t hash) { return hash & 0x7F; }
313
314inline bool IsEmpty(ctrl_t c) { return c == kEmpty; }
315inline bool IsFull(ctrl_t c) { return c >= 0; }
316inline bool IsDeleted(ctrl_t c) { return c == kDeleted; }
317inline bool IsEmptyOrDeleted(ctrl_t c) { return c < kSentinel; }
318
Austin Schuhb4691e92020-12-31 12:37:18 -0800319#if ABSL_INTERNAL_RAW_HASH_SET_HAVE_SSE2
Austin Schuh36244a12019-09-21 17:52:38 -0700320
321// https://github.com/abseil/abseil-cpp/issues/209
322// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=87853
323// _mm_cmpgt_epi8 is broken under GCC with -funsigned-char
324// Work around this by using the portable implementation of Group
325// when using -funsigned-char under GCC.
326inline __m128i _mm_cmpgt_epi8_fixed(__m128i a, __m128i b) {
327#if defined(__GNUC__) && !defined(__clang__)
328 if (std::is_unsigned<char>::value) {
329 const __m128i mask = _mm_set1_epi8(0x80);
330 const __m128i diff = _mm_subs_epi8(b, a);
331 return _mm_cmpeq_epi8(_mm_and_si128(diff, mask), mask);
332 }
333#endif
334 return _mm_cmpgt_epi8(a, b);
335}
336
337struct GroupSse2Impl {
338 static constexpr size_t kWidth = 16; // the number of slots per group
339
340 explicit GroupSse2Impl(const ctrl_t* pos) {
341 ctrl = _mm_loadu_si128(reinterpret_cast<const __m128i*>(pos));
342 }
343
344 // Returns a bitmask representing the positions of slots that match hash.
345 BitMask<uint32_t, kWidth> Match(h2_t hash) const {
346 auto match = _mm_set1_epi8(hash);
347 return BitMask<uint32_t, kWidth>(
348 _mm_movemask_epi8(_mm_cmpeq_epi8(match, ctrl)));
349 }
350
351 // Returns a bitmask representing the positions of empty slots.
352 BitMask<uint32_t, kWidth> MatchEmpty() const {
Austin Schuhb4691e92020-12-31 12:37:18 -0800353#if ABSL_INTERNAL_RAW_HASH_SET_HAVE_SSSE3
Austin Schuh36244a12019-09-21 17:52:38 -0700354 // This only works because kEmpty is -128.
355 return BitMask<uint32_t, kWidth>(
356 _mm_movemask_epi8(_mm_sign_epi8(ctrl, ctrl)));
357#else
358 return Match(static_cast<h2_t>(kEmpty));
359#endif
360 }
361
362 // Returns a bitmask representing the positions of empty or deleted slots.
363 BitMask<uint32_t, kWidth> MatchEmptyOrDeleted() const {
364 auto special = _mm_set1_epi8(kSentinel);
365 return BitMask<uint32_t, kWidth>(
366 _mm_movemask_epi8(_mm_cmpgt_epi8_fixed(special, ctrl)));
367 }
368
369 // Returns the number of trailing empty or deleted elements in the group.
370 uint32_t CountLeadingEmptyOrDeleted() const {
371 auto special = _mm_set1_epi8(kSentinel);
Austin Schuhb4691e92020-12-31 12:37:18 -0800372 return TrailingZeros(static_cast<uint32_t>(
373 _mm_movemask_epi8(_mm_cmpgt_epi8_fixed(special, ctrl)) + 1));
Austin Schuh36244a12019-09-21 17:52:38 -0700374 }
375
376 void ConvertSpecialToEmptyAndFullToDeleted(ctrl_t* dst) const {
377 auto msbs = _mm_set1_epi8(static_cast<char>(-128));
378 auto x126 = _mm_set1_epi8(126);
Austin Schuhb4691e92020-12-31 12:37:18 -0800379#if ABSL_INTERNAL_RAW_HASH_SET_HAVE_SSSE3
Austin Schuh36244a12019-09-21 17:52:38 -0700380 auto res = _mm_or_si128(_mm_shuffle_epi8(x126, ctrl), msbs);
381#else
382 auto zero = _mm_setzero_si128();
383 auto special_mask = _mm_cmpgt_epi8_fixed(zero, ctrl);
384 auto res = _mm_or_si128(msbs, _mm_andnot_si128(special_mask, x126));
385#endif
386 _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), res);
387 }
388
389 __m128i ctrl;
390};
Austin Schuhb4691e92020-12-31 12:37:18 -0800391#endif // ABSL_INTERNAL_RAW_HASH_SET_HAVE_SSE2
Austin Schuh36244a12019-09-21 17:52:38 -0700392
393struct GroupPortableImpl {
394 static constexpr size_t kWidth = 8;
395
396 explicit GroupPortableImpl(const ctrl_t* pos)
397 : ctrl(little_endian::Load64(pos)) {}
398
399 BitMask<uint64_t, kWidth, 3> Match(h2_t hash) const {
400 // For the technique, see:
401 // http://graphics.stanford.edu/~seander/bithacks.html##ValueInWord
402 // (Determine if a word has a byte equal to n).
403 //
404 // Caveat: there are false positives but:
405 // - they only occur if there is a real match
406 // - they never occur on kEmpty, kDeleted, kSentinel
407 // - they will be handled gracefully by subsequent checks in code
408 //
409 // Example:
410 // v = 0x1716151413121110
411 // hash = 0x12
412 // retval = (v - lsbs) & ~v & msbs = 0x0000000080800000
413 constexpr uint64_t msbs = 0x8080808080808080ULL;
414 constexpr uint64_t lsbs = 0x0101010101010101ULL;
415 auto x = ctrl ^ (lsbs * hash);
416 return BitMask<uint64_t, kWidth, 3>((x - lsbs) & ~x & msbs);
417 }
418
419 BitMask<uint64_t, kWidth, 3> MatchEmpty() const {
420 constexpr uint64_t msbs = 0x8080808080808080ULL;
421 return BitMask<uint64_t, kWidth, 3>((ctrl & (~ctrl << 6)) & msbs);
422 }
423
424 BitMask<uint64_t, kWidth, 3> MatchEmptyOrDeleted() const {
425 constexpr uint64_t msbs = 0x8080808080808080ULL;
426 return BitMask<uint64_t, kWidth, 3>((ctrl & (~ctrl << 7)) & msbs);
427 }
428
429 uint32_t CountLeadingEmptyOrDeleted() const {
430 constexpr uint64_t gaps = 0x00FEFEFEFEFEFEFEULL;
431 return (TrailingZeros(((~ctrl & (ctrl >> 7)) | gaps) + 1) + 7) >> 3;
432 }
433
434 void ConvertSpecialToEmptyAndFullToDeleted(ctrl_t* dst) const {
435 constexpr uint64_t msbs = 0x8080808080808080ULL;
436 constexpr uint64_t lsbs = 0x0101010101010101ULL;
437 auto x = ctrl & msbs;
438 auto res = (~x + (x >> 7)) & ~lsbs;
439 little_endian::Store64(dst, res);
440 }
441
442 uint64_t ctrl;
443};
444
Austin Schuhb4691e92020-12-31 12:37:18 -0800445#if ABSL_INTERNAL_RAW_HASH_SET_HAVE_SSE2
Austin Schuh36244a12019-09-21 17:52:38 -0700446using Group = GroupSse2Impl;
447#else
448using Group = GroupPortableImpl;
449#endif
450
451template <class Policy, class Hash, class Eq, class Alloc>
452class raw_hash_set;
453
454inline bool IsValidCapacity(size_t n) { return ((n + 1) & n) == 0 && n > 0; }
455
456// PRECONDITION:
457// IsValidCapacity(capacity)
458// ctrl[capacity] == kSentinel
459// ctrl[i] != kSentinel for all i < capacity
460// Applies mapping for every byte in ctrl:
461// DELETED -> EMPTY
462// EMPTY -> EMPTY
463// FULL -> DELETED
Austin Schuhb4691e92020-12-31 12:37:18 -0800464void ConvertDeletedToEmptyAndFullToDeleted(ctrl_t* ctrl, size_t capacity);
Austin Schuh36244a12019-09-21 17:52:38 -0700465
466// Rounds up the capacity to the next power of 2 minus 1, with a minimum of 1.
467inline size_t NormalizeCapacity(size_t n) {
Austin Schuhb4691e92020-12-31 12:37:18 -0800468 return n ? ~size_t{} >> countl_zero(n) : 1;
Austin Schuh36244a12019-09-21 17:52:38 -0700469}
470
471// We use 7/8th as maximum load factor.
472// For 16-wide groups, that gives an average of two empty slots per group.
473inline size_t CapacityToGrowth(size_t capacity) {
474 assert(IsValidCapacity(capacity));
475 // `capacity*7/8`
476 if (Group::kWidth == 8 && capacity == 7) {
477 // x-x/8 does not work when x==7.
478 return 6;
479 }
480 return capacity - capacity / 8;
481}
482// From desired "growth" to a lowerbound of the necessary capacity.
483// Might not be a valid one and required NormalizeCapacity().
484inline size_t GrowthToLowerboundCapacity(size_t growth) {
485 // `growth*8/7`
486 if (Group::kWidth == 8 && growth == 7) {
487 // x+(x-1)/7 does not work when x==7.
488 return 8;
489 }
490 return growth + static_cast<size_t>((static_cast<int64_t>(growth) - 1) / 7);
491}
492
Austin Schuhb4691e92020-12-31 12:37:18 -0800493inline void AssertIsFull(ctrl_t* ctrl) {
494 ABSL_HARDENING_ASSERT((ctrl != nullptr && IsFull(*ctrl)) &&
495 "Invalid operation on iterator. The element might have "
496 "been erased, or the table might have rehashed.");
497}
498
499inline void AssertIsValid(ctrl_t* ctrl) {
500 ABSL_HARDENING_ASSERT((ctrl == nullptr || IsFull(*ctrl)) &&
501 "Invalid operation on iterator. The element might have "
502 "been erased, or the table might have rehashed.");
503}
504
505struct FindInfo {
506 size_t offset;
507 size_t probe_length;
508};
509
510// The representation of the object has two modes:
511// - small: For capacities < kWidth-1
512// - large: For the rest.
513//
514// Differences:
515// - In small mode we are able to use the whole capacity. The extra control
516// bytes give us at least one "empty" control byte to stop the iteration.
517// This is important to make 1 a valid capacity.
518//
519// - In small mode only the first `capacity()` control bytes after the
520// sentinel are valid. The rest contain dummy kEmpty values that do not
521// represent a real slot. This is important to take into account on
522// find_first_non_full(), where we never try ShouldInsertBackwards() for
523// small tables.
524inline bool is_small(size_t capacity) { return capacity < Group::kWidth - 1; }
525
526inline probe_seq<Group::kWidth> probe(ctrl_t* ctrl, size_t hash,
527 size_t capacity) {
528 return probe_seq<Group::kWidth>(H1(hash, ctrl), capacity);
529}
530
531// Probes the raw_hash_set with the probe sequence for hash and returns the
532// pointer to the first empty or deleted slot.
533// NOTE: this function must work with tables having both kEmpty and kDelete
534// in one group. Such tables appears during drop_deletes_without_resize.
535//
536// This function is very useful when insertions happen and:
537// - the input is already a set
538// - there are enough slots
539// - the element with the hash is not in the table
540inline FindInfo find_first_non_full(ctrl_t* ctrl, size_t hash,
541 size_t capacity) {
542 auto seq = probe(ctrl, hash, capacity);
543 while (true) {
544 Group g{ctrl + seq.offset()};
545 auto mask = g.MatchEmptyOrDeleted();
546 if (mask) {
547#if !defined(NDEBUG)
548 // We want to add entropy even when ASLR is not enabled.
549 // In debug build we will randomly insert in either the front or back of
550 // the group.
551 // TODO(kfm,sbenza): revisit after we do unconditional mixing
552 if (!is_small(capacity) && ShouldInsertBackwards(hash, ctrl)) {
553 return {seq.offset(mask.HighestBitSet()), seq.index()};
554 }
555#endif
556 return {seq.offset(mask.LowestBitSet()), seq.index()};
557 }
558 seq.next();
559 assert(seq.index() < capacity && "full table!");
560 }
561}
562
Austin Schuh36244a12019-09-21 17:52:38 -0700563// Policy: a policy defines how to perform different operations on
564// the slots of the hashtable (see hash_policy_traits.h for the full interface
565// of policy).
566//
567// Hash: a (possibly polymorphic) functor that hashes keys of the hashtable. The
568// functor should accept a key and return size_t as hash. For best performance
569// it is important that the hash function provides high entropy across all bits
570// of the hash.
571//
572// Eq: a (possibly polymorphic) functor that compares two keys for equality. It
573// should accept two (of possibly different type) keys and return a bool: true
574// if they are equal, false if they are not. If two keys compare equal, then
575// their hash values as defined by Hash MUST be equal.
576//
Austin Schuhb4691e92020-12-31 12:37:18 -0800577// Allocator: an Allocator
578// [https://en.cppreference.com/w/cpp/named_req/Allocator] with which
Austin Schuh36244a12019-09-21 17:52:38 -0700579// the storage of the hashtable will be allocated and the elements will be
580// constructed and destroyed.
581template <class Policy, class Hash, class Eq, class Alloc>
582class raw_hash_set {
583 using PolicyTraits = hash_policy_traits<Policy>;
584 using KeyArgImpl =
585 KeyArg<IsTransparent<Eq>::value && IsTransparent<Hash>::value>;
586
587 public:
588 using init_type = typename PolicyTraits::init_type;
589 using key_type = typename PolicyTraits::key_type;
590 // TODO(sbenza): Hide slot_type as it is an implementation detail. Needs user
591 // code fixes!
592 using slot_type = typename PolicyTraits::slot_type;
593 using allocator_type = Alloc;
594 using size_type = size_t;
595 using difference_type = ptrdiff_t;
596 using hasher = Hash;
597 using key_equal = Eq;
598 using policy_type = Policy;
599 using value_type = typename PolicyTraits::value_type;
600 using reference = value_type&;
601 using const_reference = const value_type&;
602 using pointer = typename absl::allocator_traits<
603 allocator_type>::template rebind_traits<value_type>::pointer;
604 using const_pointer = typename absl::allocator_traits<
605 allocator_type>::template rebind_traits<value_type>::const_pointer;
606
607 // Alias used for heterogeneous lookup functions.
608 // `key_arg<K>` evaluates to `K` when the functors are transparent and to
609 // `key_type` otherwise. It permits template argument deduction on `K` for the
610 // transparent case.
611 template <class K>
612 using key_arg = typename KeyArgImpl::template type<K, key_type>;
613
614 private:
615 // Give an early error when key_type is not hashable/eq.
616 auto KeyTypeCanBeHashed(const Hash& h, const key_type& k) -> decltype(h(k));
617 auto KeyTypeCanBeEq(const Eq& eq, const key_type& k) -> decltype(eq(k, k));
618
619 using Layout = absl::container_internal::Layout<ctrl_t, slot_type>;
620
621 static Layout MakeLayout(size_t capacity) {
622 assert(IsValidCapacity(capacity));
623 return Layout(capacity + Group::kWidth + 1, capacity);
624 }
625
626 using AllocTraits = absl::allocator_traits<allocator_type>;
627 using SlotAlloc = typename absl::allocator_traits<
628 allocator_type>::template rebind_alloc<slot_type>;
629 using SlotAllocTraits = typename absl::allocator_traits<
630 allocator_type>::template rebind_traits<slot_type>;
631
632 static_assert(std::is_lvalue_reference<reference>::value,
633 "Policy::element() must return a reference");
634
635 template <typename T>
636 struct SameAsElementReference
637 : std::is_same<typename std::remove_cv<
638 typename std::remove_reference<reference>::type>::type,
639 typename std::remove_cv<
640 typename std::remove_reference<T>::type>::type> {};
641
642 // An enabler for insert(T&&): T must be convertible to init_type or be the
643 // same as [cv] value_type [ref].
644 // Note: we separate SameAsElementReference into its own type to avoid using
645 // reference unless we need to. MSVC doesn't seem to like it in some
646 // cases.
647 template <class T>
648 using RequiresInsertable = typename std::enable_if<
649 absl::disjunction<std::is_convertible<T, init_type>,
650 SameAsElementReference<T>>::value,
651 int>::type;
652
653 // RequiresNotInit is a workaround for gcc prior to 7.1.
654 // See https://godbolt.org/g/Y4xsUh.
655 template <class T>
656 using RequiresNotInit =
657 typename std::enable_if<!std::is_same<T, init_type>::value, int>::type;
658
659 template <class... Ts>
660 using IsDecomposable = IsDecomposable<void, PolicyTraits, Hash, Eq, Ts...>;
661
662 public:
663 static_assert(std::is_same<pointer, value_type*>::value,
664 "Allocators with custom pointer types are not supported");
665 static_assert(std::is_same<const_pointer, const value_type*>::value,
666 "Allocators with custom pointer types are not supported");
667
668 class iterator {
669 friend class raw_hash_set;
670
671 public:
672 using iterator_category = std::forward_iterator_tag;
673 using value_type = typename raw_hash_set::value_type;
674 using reference =
675 absl::conditional_t<PolicyTraits::constant_iterators::value,
676 const value_type&, value_type&>;
677 using pointer = absl::remove_reference_t<reference>*;
678 using difference_type = typename raw_hash_set::difference_type;
679
680 iterator() {}
681
682 // PRECONDITION: not an end() iterator.
Austin Schuhb4691e92020-12-31 12:37:18 -0800683 reference operator*() const {
684 AssertIsFull(ctrl_);
685 return PolicyTraits::element(slot_);
686 }
Austin Schuh36244a12019-09-21 17:52:38 -0700687
688 // PRECONDITION: not an end() iterator.
689 pointer operator->() const { return &operator*(); }
690
691 // PRECONDITION: not an end() iterator.
692 iterator& operator++() {
Austin Schuhb4691e92020-12-31 12:37:18 -0800693 AssertIsFull(ctrl_);
Austin Schuh36244a12019-09-21 17:52:38 -0700694 ++ctrl_;
695 ++slot_;
696 skip_empty_or_deleted();
697 return *this;
698 }
699 // PRECONDITION: not an end() iterator.
700 iterator operator++(int) {
701 auto tmp = *this;
702 ++*this;
703 return tmp;
704 }
705
706 friend bool operator==(const iterator& a, const iterator& b) {
Austin Schuhb4691e92020-12-31 12:37:18 -0800707 AssertIsValid(a.ctrl_);
708 AssertIsValid(b.ctrl_);
Austin Schuh36244a12019-09-21 17:52:38 -0700709 return a.ctrl_ == b.ctrl_;
710 }
711 friend bool operator!=(const iterator& a, const iterator& b) {
712 return !(a == b);
713 }
714
715 private:
Austin Schuhb4691e92020-12-31 12:37:18 -0800716 iterator(ctrl_t* ctrl, slot_type* slot) : ctrl_(ctrl), slot_(slot) {
717 // This assumption helps the compiler know that any non-end iterator is
718 // not equal to any end iterator.
719 ABSL_INTERNAL_ASSUME(ctrl != nullptr);
720 }
Austin Schuh36244a12019-09-21 17:52:38 -0700721
722 void skip_empty_or_deleted() {
723 while (IsEmptyOrDeleted(*ctrl_)) {
Austin Schuh36244a12019-09-21 17:52:38 -0700724 uint32_t shift = Group{ctrl_}.CountLeadingEmptyOrDeleted();
725 ctrl_ += shift;
726 slot_ += shift;
727 }
Austin Schuhb4691e92020-12-31 12:37:18 -0800728 if (ABSL_PREDICT_FALSE(*ctrl_ == kSentinel)) ctrl_ = nullptr;
Austin Schuh36244a12019-09-21 17:52:38 -0700729 }
730
731 ctrl_t* ctrl_ = nullptr;
Austin Schuhb4691e92020-12-31 12:37:18 -0800732 // To avoid uninitialized member warnings, put slot_ in an anonymous union.
Austin Schuh36244a12019-09-21 17:52:38 -0700733 // The member is not initialized on singleton and end iterators.
734 union {
735 slot_type* slot_;
736 };
737 };
738
739 class const_iterator {
740 friend class raw_hash_set;
741
742 public:
743 using iterator_category = typename iterator::iterator_category;
744 using value_type = typename raw_hash_set::value_type;
745 using reference = typename raw_hash_set::const_reference;
746 using pointer = typename raw_hash_set::const_pointer;
747 using difference_type = typename raw_hash_set::difference_type;
748
749 const_iterator() {}
750 // Implicit construction from iterator.
751 const_iterator(iterator i) : inner_(std::move(i)) {}
752
753 reference operator*() const { return *inner_; }
754 pointer operator->() const { return inner_.operator->(); }
755
756 const_iterator& operator++() {
757 ++inner_;
758 return *this;
759 }
760 const_iterator operator++(int) { return inner_++; }
761
762 friend bool operator==(const const_iterator& a, const const_iterator& b) {
763 return a.inner_ == b.inner_;
764 }
765 friend bool operator!=(const const_iterator& a, const const_iterator& b) {
766 return !(a == b);
767 }
768
769 private:
770 const_iterator(const ctrl_t* ctrl, const slot_type* slot)
771 : inner_(const_cast<ctrl_t*>(ctrl), const_cast<slot_type*>(slot)) {}
772
773 iterator inner_;
774 };
775
776 using node_type = node_handle<Policy, hash_policy_traits<Policy>, Alloc>;
777 using insert_return_type = InsertReturnType<iterator, node_type>;
778
779 raw_hash_set() noexcept(
780 std::is_nothrow_default_constructible<hasher>::value&&
781 std::is_nothrow_default_constructible<key_equal>::value&&
782 std::is_nothrow_default_constructible<allocator_type>::value) {}
783
784 explicit raw_hash_set(size_t bucket_count, const hasher& hash = hasher(),
785 const key_equal& eq = key_equal(),
786 const allocator_type& alloc = allocator_type())
787 : ctrl_(EmptyGroup()), settings_(0, hash, eq, alloc) {
788 if (bucket_count) {
789 capacity_ = NormalizeCapacity(bucket_count);
Austin Schuh36244a12019-09-21 17:52:38 -0700790 initialize_slots();
791 }
792 }
793
794 raw_hash_set(size_t bucket_count, const hasher& hash,
795 const allocator_type& alloc)
796 : raw_hash_set(bucket_count, hash, key_equal(), alloc) {}
797
798 raw_hash_set(size_t bucket_count, const allocator_type& alloc)
799 : raw_hash_set(bucket_count, hasher(), key_equal(), alloc) {}
800
801 explicit raw_hash_set(const allocator_type& alloc)
802 : raw_hash_set(0, hasher(), key_equal(), alloc) {}
803
804 template <class InputIter>
805 raw_hash_set(InputIter first, InputIter last, size_t bucket_count = 0,
806 const hasher& hash = hasher(), const key_equal& eq = key_equal(),
807 const allocator_type& alloc = allocator_type())
808 : raw_hash_set(bucket_count, hash, eq, alloc) {
809 insert(first, last);
810 }
811
812 template <class InputIter>
813 raw_hash_set(InputIter first, InputIter last, size_t bucket_count,
814 const hasher& hash, const allocator_type& alloc)
815 : raw_hash_set(first, last, bucket_count, hash, key_equal(), alloc) {}
816
817 template <class InputIter>
818 raw_hash_set(InputIter first, InputIter last, size_t bucket_count,
819 const allocator_type& alloc)
820 : raw_hash_set(first, last, bucket_count, hasher(), key_equal(), alloc) {}
821
822 template <class InputIter>
823 raw_hash_set(InputIter first, InputIter last, const allocator_type& alloc)
824 : raw_hash_set(first, last, 0, hasher(), key_equal(), alloc) {}
825
826 // Instead of accepting std::initializer_list<value_type> as the first
827 // argument like std::unordered_set<value_type> does, we have two overloads
828 // that accept std::initializer_list<T> and std::initializer_list<init_type>.
829 // This is advantageous for performance.
830 //
831 // // Turns {"abc", "def"} into std::initializer_list<std::string>, then
832 // // copies the strings into the set.
833 // std::unordered_set<std::string> s = {"abc", "def"};
834 //
835 // // Turns {"abc", "def"} into std::initializer_list<const char*>, then
836 // // copies the strings into the set.
837 // absl::flat_hash_set<std::string> s = {"abc", "def"};
838 //
839 // The same trick is used in insert().
840 //
841 // The enabler is necessary to prevent this constructor from triggering where
842 // the copy constructor is meant to be called.
843 //
844 // absl::flat_hash_set<int> a, b{a};
845 //
846 // RequiresNotInit<T> is a workaround for gcc prior to 7.1.
847 template <class T, RequiresNotInit<T> = 0, RequiresInsertable<T> = 0>
848 raw_hash_set(std::initializer_list<T> init, size_t bucket_count = 0,
849 const hasher& hash = hasher(), const key_equal& eq = key_equal(),
850 const allocator_type& alloc = allocator_type())
851 : raw_hash_set(init.begin(), init.end(), bucket_count, hash, eq, alloc) {}
852
853 raw_hash_set(std::initializer_list<init_type> init, size_t bucket_count = 0,
854 const hasher& hash = hasher(), const key_equal& eq = key_equal(),
855 const allocator_type& alloc = allocator_type())
856 : raw_hash_set(init.begin(), init.end(), bucket_count, hash, eq, alloc) {}
857
858 template <class T, RequiresNotInit<T> = 0, RequiresInsertable<T> = 0>
859 raw_hash_set(std::initializer_list<T> init, size_t bucket_count,
860 const hasher& hash, const allocator_type& alloc)
861 : raw_hash_set(init, bucket_count, hash, key_equal(), alloc) {}
862
863 raw_hash_set(std::initializer_list<init_type> init, size_t bucket_count,
864 const hasher& hash, const allocator_type& alloc)
865 : raw_hash_set(init, bucket_count, hash, key_equal(), alloc) {}
866
867 template <class T, RequiresNotInit<T> = 0, RequiresInsertable<T> = 0>
868 raw_hash_set(std::initializer_list<T> init, size_t bucket_count,
869 const allocator_type& alloc)
870 : raw_hash_set(init, bucket_count, hasher(), key_equal(), alloc) {}
871
872 raw_hash_set(std::initializer_list<init_type> init, size_t bucket_count,
873 const allocator_type& alloc)
874 : raw_hash_set(init, bucket_count, hasher(), key_equal(), alloc) {}
875
876 template <class T, RequiresNotInit<T> = 0, RequiresInsertable<T> = 0>
877 raw_hash_set(std::initializer_list<T> init, const allocator_type& alloc)
878 : raw_hash_set(init, 0, hasher(), key_equal(), alloc) {}
879
880 raw_hash_set(std::initializer_list<init_type> init,
881 const allocator_type& alloc)
882 : raw_hash_set(init, 0, hasher(), key_equal(), alloc) {}
883
884 raw_hash_set(const raw_hash_set& that)
885 : raw_hash_set(that, AllocTraits::select_on_container_copy_construction(
886 that.alloc_ref())) {}
887
888 raw_hash_set(const raw_hash_set& that, const allocator_type& a)
889 : raw_hash_set(0, that.hash_ref(), that.eq_ref(), a) {
890 reserve(that.size());
891 // Because the table is guaranteed to be empty, we can do something faster
892 // than a full `insert`.
893 for (const auto& v : that) {
894 const size_t hash = PolicyTraits::apply(HashElement{hash_ref()}, v);
Austin Schuhb4691e92020-12-31 12:37:18 -0800895 auto target = find_first_non_full(ctrl_, hash, capacity_);
Austin Schuh36244a12019-09-21 17:52:38 -0700896 set_ctrl(target.offset, H2(hash));
897 emplace_at(target.offset, v);
898 infoz_.RecordInsert(hash, target.probe_length);
899 }
900 size_ = that.size();
901 growth_left() -= that.size();
902 }
903
904 raw_hash_set(raw_hash_set&& that) noexcept(
905 std::is_nothrow_copy_constructible<hasher>::value&&
906 std::is_nothrow_copy_constructible<key_equal>::value&&
907 std::is_nothrow_copy_constructible<allocator_type>::value)
908 : ctrl_(absl::exchange(that.ctrl_, EmptyGroup())),
909 slots_(absl::exchange(that.slots_, nullptr)),
910 size_(absl::exchange(that.size_, 0)),
911 capacity_(absl::exchange(that.capacity_, 0)),
912 infoz_(absl::exchange(that.infoz_, HashtablezInfoHandle())),
913 // Hash, equality and allocator are copied instead of moved because
914 // `that` must be left valid. If Hash is std::function<Key>, moving it
915 // would create a nullptr functor that cannot be called.
916 settings_(that.settings_) {
917 // growth_left was copied above, reset the one from `that`.
918 that.growth_left() = 0;
919 }
920
921 raw_hash_set(raw_hash_set&& that, const allocator_type& a)
922 : ctrl_(EmptyGroup()),
923 slots_(nullptr),
924 size_(0),
925 capacity_(0),
926 settings_(0, that.hash_ref(), that.eq_ref(), a) {
927 if (a == that.alloc_ref()) {
928 std::swap(ctrl_, that.ctrl_);
929 std::swap(slots_, that.slots_);
930 std::swap(size_, that.size_);
931 std::swap(capacity_, that.capacity_);
932 std::swap(growth_left(), that.growth_left());
933 std::swap(infoz_, that.infoz_);
934 } else {
935 reserve(that.size());
936 // Note: this will copy elements of dense_set and unordered_set instead of
937 // moving them. This can be fixed if it ever becomes an issue.
938 for (auto& elem : that) insert(std::move(elem));
939 }
940 }
941
942 raw_hash_set& operator=(const raw_hash_set& that) {
943 raw_hash_set tmp(that,
944 AllocTraits::propagate_on_container_copy_assignment::value
945 ? that.alloc_ref()
946 : alloc_ref());
947 swap(tmp);
948 return *this;
949 }
950
951 raw_hash_set& operator=(raw_hash_set&& that) noexcept(
952 absl::allocator_traits<allocator_type>::is_always_equal::value&&
953 std::is_nothrow_move_assignable<hasher>::value&&
954 std::is_nothrow_move_assignable<key_equal>::value) {
955 // TODO(sbenza): We should only use the operations from the noexcept clause
956 // to make sure we actually adhere to that contract.
957 return move_assign(
958 std::move(that),
959 typename AllocTraits::propagate_on_container_move_assignment());
960 }
961
962 ~raw_hash_set() { destroy_slots(); }
963
964 iterator begin() {
965 auto it = iterator_at(0);
966 it.skip_empty_or_deleted();
967 return it;
968 }
Austin Schuhb4691e92020-12-31 12:37:18 -0800969 iterator end() { return {}; }
Austin Schuh36244a12019-09-21 17:52:38 -0700970
971 const_iterator begin() const {
972 return const_cast<raw_hash_set*>(this)->begin();
973 }
Austin Schuhb4691e92020-12-31 12:37:18 -0800974 const_iterator end() const { return {}; }
Austin Schuh36244a12019-09-21 17:52:38 -0700975 const_iterator cbegin() const { return begin(); }
976 const_iterator cend() const { return end(); }
977
978 bool empty() const { return !size(); }
979 size_t size() const { return size_; }
980 size_t capacity() const { return capacity_; }
981 size_t max_size() const { return (std::numeric_limits<size_t>::max)(); }
982
983 ABSL_ATTRIBUTE_REINITIALIZES void clear() {
984 // Iterating over this container is O(bucket_count()). When bucket_count()
985 // is much greater than size(), iteration becomes prohibitively expensive.
986 // For clear() it is more important to reuse the allocated array when the
987 // container is small because allocation takes comparatively long time
988 // compared to destruction of the elements of the container. So we pick the
989 // largest bucket_count() threshold for which iteration is still fast and
990 // past that we simply deallocate the array.
991 if (capacity_ > 127) {
992 destroy_slots();
993 } else if (capacity_) {
994 for (size_t i = 0; i != capacity_; ++i) {
995 if (IsFull(ctrl_[i])) {
996 PolicyTraits::destroy(&alloc_ref(), slots_ + i);
997 }
998 }
999 size_ = 0;
1000 reset_ctrl();
1001 reset_growth_left();
1002 }
1003 assert(empty());
1004 infoz_.RecordStorageChanged(0, capacity_);
1005 }
1006
1007 // This overload kicks in when the argument is an rvalue of insertable and
1008 // decomposable type other than init_type.
1009 //
1010 // flat_hash_map<std::string, int> m;
1011 // m.insert(std::make_pair("abc", 42));
Austin Schuhb4691e92020-12-31 12:37:18 -08001012 // TODO(cheshire): A type alias T2 is introduced as a workaround for the nvcc
1013 // bug.
Austin Schuh36244a12019-09-21 17:52:38 -07001014 template <class T, RequiresInsertable<T> = 0,
Austin Schuhb4691e92020-12-31 12:37:18 -08001015 class T2 = T,
1016 typename std::enable_if<IsDecomposable<T2>::value, int>::type = 0,
Austin Schuh36244a12019-09-21 17:52:38 -07001017 T* = nullptr>
1018 std::pair<iterator, bool> insert(T&& value) {
1019 return emplace(std::forward<T>(value));
1020 }
1021
1022 // This overload kicks in when the argument is a bitfield or an lvalue of
1023 // insertable and decomposable type.
1024 //
1025 // union { int n : 1; };
1026 // flat_hash_set<int> s;
1027 // s.insert(n);
1028 //
1029 // flat_hash_set<std::string> s;
1030 // const char* p = "hello";
1031 // s.insert(p);
1032 //
1033 // TODO(romanp): Once we stop supporting gcc 5.1 and below, replace
1034 // RequiresInsertable<T> with RequiresInsertable<const T&>.
1035 // We are hitting this bug: https://godbolt.org/g/1Vht4f.
1036 template <
1037 class T, RequiresInsertable<T> = 0,
1038 typename std::enable_if<IsDecomposable<const T&>::value, int>::type = 0>
1039 std::pair<iterator, bool> insert(const T& value) {
1040 return emplace(value);
1041 }
1042
1043 // This overload kicks in when the argument is an rvalue of init_type. Its
1044 // purpose is to handle brace-init-list arguments.
1045 //
1046 // flat_hash_map<std::string, int> s;
1047 // s.insert({"abc", 42});
1048 std::pair<iterator, bool> insert(init_type&& value) {
1049 return emplace(std::move(value));
1050 }
1051
Austin Schuhb4691e92020-12-31 12:37:18 -08001052 // TODO(cheshire): A type alias T2 is introduced as a workaround for the nvcc
1053 // bug.
1054 template <class T, RequiresInsertable<T> = 0, class T2 = T,
1055 typename std::enable_if<IsDecomposable<T2>::value, int>::type = 0,
Austin Schuh36244a12019-09-21 17:52:38 -07001056 T* = nullptr>
1057 iterator insert(const_iterator, T&& value) {
1058 return insert(std::forward<T>(value)).first;
1059 }
1060
1061 // TODO(romanp): Once we stop supporting gcc 5.1 and below, replace
1062 // RequiresInsertable<T> with RequiresInsertable<const T&>.
1063 // We are hitting this bug: https://godbolt.org/g/1Vht4f.
1064 template <
1065 class T, RequiresInsertable<T> = 0,
1066 typename std::enable_if<IsDecomposable<const T&>::value, int>::type = 0>
1067 iterator insert(const_iterator, const T& value) {
1068 return insert(value).first;
1069 }
1070
1071 iterator insert(const_iterator, init_type&& value) {
1072 return insert(std::move(value)).first;
1073 }
1074
1075 template <class InputIt>
1076 void insert(InputIt first, InputIt last) {
Austin Schuhb4691e92020-12-31 12:37:18 -08001077 for (; first != last; ++first) emplace(*first);
Austin Schuh36244a12019-09-21 17:52:38 -07001078 }
1079
1080 template <class T, RequiresNotInit<T> = 0, RequiresInsertable<const T&> = 0>
1081 void insert(std::initializer_list<T> ilist) {
1082 insert(ilist.begin(), ilist.end());
1083 }
1084
1085 void insert(std::initializer_list<init_type> ilist) {
1086 insert(ilist.begin(), ilist.end());
1087 }
1088
1089 insert_return_type insert(node_type&& node) {
1090 if (!node) return {end(), false, node_type()};
1091 const auto& elem = PolicyTraits::element(CommonAccess::GetSlot(node));
1092 auto res = PolicyTraits::apply(
1093 InsertSlot<false>{*this, std::move(*CommonAccess::GetSlot(node))},
1094 elem);
1095 if (res.second) {
1096 CommonAccess::Reset(&node);
1097 return {res.first, true, node_type()};
1098 } else {
1099 return {res.first, false, std::move(node)};
1100 }
1101 }
1102
1103 iterator insert(const_iterator, node_type&& node) {
Austin Schuhb4691e92020-12-31 12:37:18 -08001104 auto res = insert(std::move(node));
1105 node = std::move(res.node);
1106 return res.position;
Austin Schuh36244a12019-09-21 17:52:38 -07001107 }
1108
1109 // This overload kicks in if we can deduce the key from args. This enables us
1110 // to avoid constructing value_type if an entry with the same key already
1111 // exists.
1112 //
1113 // For example:
1114 //
1115 // flat_hash_map<std::string, std::string> m = {{"abc", "def"}};
1116 // // Creates no std::string copies and makes no heap allocations.
1117 // m.emplace("abc", "xyz");
1118 template <class... Args, typename std::enable_if<
1119 IsDecomposable<Args...>::value, int>::type = 0>
1120 std::pair<iterator, bool> emplace(Args&&... args) {
1121 return PolicyTraits::apply(EmplaceDecomposable{*this},
1122 std::forward<Args>(args)...);
1123 }
1124
1125 // This overload kicks in if we cannot deduce the key from args. It constructs
1126 // value_type unconditionally and then either moves it into the table or
1127 // destroys.
1128 template <class... Args, typename std::enable_if<
1129 !IsDecomposable<Args...>::value, int>::type = 0>
1130 std::pair<iterator, bool> emplace(Args&&... args) {
Austin Schuhb4691e92020-12-31 12:37:18 -08001131 alignas(slot_type) unsigned char raw[sizeof(slot_type)];
Austin Schuh36244a12019-09-21 17:52:38 -07001132 slot_type* slot = reinterpret_cast<slot_type*>(&raw);
1133
1134 PolicyTraits::construct(&alloc_ref(), slot, std::forward<Args>(args)...);
1135 const auto& elem = PolicyTraits::element(slot);
1136 return PolicyTraits::apply(InsertSlot<true>{*this, std::move(*slot)}, elem);
1137 }
1138
1139 template <class... Args>
1140 iterator emplace_hint(const_iterator, Args&&... args) {
1141 return emplace(std::forward<Args>(args)...).first;
1142 }
1143
1144 // Extension API: support for lazy emplace.
1145 //
1146 // Looks up key in the table. If found, returns the iterator to the element.
Austin Schuhb4691e92020-12-31 12:37:18 -08001147 // Otherwise calls `f` with one argument of type `raw_hash_set::constructor`.
1148 //
1149 // `f` must abide by several restrictions:
1150 // - it MUST call `raw_hash_set::constructor` with arguments as if a
1151 // `raw_hash_set::value_type` is constructed,
1152 // - it MUST NOT access the container before the call to
1153 // `raw_hash_set::constructor`, and
1154 // - it MUST NOT erase the lazily emplaced element.
1155 // Doing any of these is undefined behavior.
Austin Schuh36244a12019-09-21 17:52:38 -07001156 //
1157 // For example:
1158 //
1159 // std::unordered_set<ArenaString> s;
1160 // // Makes ArenaStr even if "abc" is in the map.
1161 // s.insert(ArenaString(&arena, "abc"));
1162 //
1163 // flat_hash_set<ArenaStr> s;
1164 // // Makes ArenaStr only if "abc" is not in the map.
1165 // s.lazy_emplace("abc", [&](const constructor& ctor) {
1166 // ctor(&arena, "abc");
1167 // });
1168 //
1169 // WARNING: This API is currently experimental. If there is a way to implement
1170 // the same thing with the rest of the API, prefer that.
1171 class constructor {
1172 friend class raw_hash_set;
1173
1174 public:
1175 template <class... Args>
1176 void operator()(Args&&... args) const {
1177 assert(*slot_);
1178 PolicyTraits::construct(alloc_, *slot_, std::forward<Args>(args)...);
1179 *slot_ = nullptr;
1180 }
1181
1182 private:
1183 constructor(allocator_type* a, slot_type** slot) : alloc_(a), slot_(slot) {}
1184
1185 allocator_type* alloc_;
1186 slot_type** slot_;
1187 };
1188
1189 template <class K = key_type, class F>
1190 iterator lazy_emplace(const key_arg<K>& key, F&& f) {
1191 auto res = find_or_prepare_insert(key);
1192 if (res.second) {
1193 slot_type* slot = slots_ + res.first;
1194 std::forward<F>(f)(constructor(&alloc_ref(), &slot));
1195 assert(!slot);
1196 }
1197 return iterator_at(res.first);
1198 }
1199
1200 // Extension API: support for heterogeneous keys.
1201 //
1202 // std::unordered_set<std::string> s;
1203 // // Turns "abc" into std::string.
1204 // s.erase("abc");
1205 //
1206 // flat_hash_set<std::string> s;
1207 // // Uses "abc" directly without copying it into std::string.
1208 // s.erase("abc");
1209 template <class K = key_type>
1210 size_type erase(const key_arg<K>& key) {
1211 auto it = find(key);
1212 if (it == end()) return 0;
1213 erase(it);
1214 return 1;
1215 }
1216
1217 // Erases the element pointed to by `it`. Unlike `std::unordered_set::erase`,
1218 // this method returns void to reduce algorithmic complexity to O(1). The
1219 // iterator is invalidated, so any increment should be done before calling
1220 // erase. In order to erase while iterating across a map, use the following
1221 // idiom (which also works for standard containers):
1222 //
1223 // for (auto it = m.begin(), end = m.end(); it != end;) {
1224 // // `erase()` will invalidate `it`, so advance `it` first.
1225 // auto copy_it = it++;
1226 // if (<pred>) {
1227 // m.erase(copy_it);
1228 // }
1229 // }
1230 void erase(const_iterator cit) { erase(cit.inner_); }
1231
1232 // This overload is necessary because otherwise erase<K>(const K&) would be
1233 // a better match if non-const iterator is passed as an argument.
1234 void erase(iterator it) {
Austin Schuhb4691e92020-12-31 12:37:18 -08001235 AssertIsFull(it.ctrl_);
Austin Schuh36244a12019-09-21 17:52:38 -07001236 PolicyTraits::destroy(&alloc_ref(), it.slot_);
1237 erase_meta_only(it);
1238 }
1239
1240 iterator erase(const_iterator first, const_iterator last) {
1241 while (first != last) {
1242 erase(first++);
1243 }
1244 return last.inner_;
1245 }
1246
1247 // Moves elements from `src` into `this`.
1248 // If the element already exists in `this`, it is left unmodified in `src`.
1249 template <typename H, typename E>
1250 void merge(raw_hash_set<Policy, H, E, Alloc>& src) { // NOLINT
1251 assert(this != &src);
Austin Schuhb4691e92020-12-31 12:37:18 -08001252 for (auto it = src.begin(), e = src.end(); it != e;) {
1253 auto next = std::next(it);
Austin Schuh36244a12019-09-21 17:52:38 -07001254 if (PolicyTraits::apply(InsertSlot<false>{*this, std::move(*it.slot_)},
1255 PolicyTraits::element(it.slot_))
1256 .second) {
1257 src.erase_meta_only(it);
1258 }
Austin Schuhb4691e92020-12-31 12:37:18 -08001259 it = next;
Austin Schuh36244a12019-09-21 17:52:38 -07001260 }
1261 }
1262
1263 template <typename H, typename E>
1264 void merge(raw_hash_set<Policy, H, E, Alloc>&& src) {
1265 merge(src);
1266 }
1267
1268 node_type extract(const_iterator position) {
Austin Schuhb4691e92020-12-31 12:37:18 -08001269 AssertIsFull(position.inner_.ctrl_);
Austin Schuh36244a12019-09-21 17:52:38 -07001270 auto node =
1271 CommonAccess::Transfer<node_type>(alloc_ref(), position.inner_.slot_);
1272 erase_meta_only(position);
1273 return node;
1274 }
1275
1276 template <
1277 class K = key_type,
1278 typename std::enable_if<!std::is_same<K, iterator>::value, int>::type = 0>
1279 node_type extract(const key_arg<K>& key) {
1280 auto it = find(key);
1281 return it == end() ? node_type() : extract(const_iterator{it});
1282 }
1283
1284 void swap(raw_hash_set& that) noexcept(
1285 IsNoThrowSwappable<hasher>() && IsNoThrowSwappable<key_equal>() &&
Austin Schuhb4691e92020-12-31 12:37:18 -08001286 IsNoThrowSwappable<allocator_type>(
1287 typename AllocTraits::propagate_on_container_swap{})) {
Austin Schuh36244a12019-09-21 17:52:38 -07001288 using std::swap;
1289 swap(ctrl_, that.ctrl_);
1290 swap(slots_, that.slots_);
1291 swap(size_, that.size_);
1292 swap(capacity_, that.capacity_);
1293 swap(growth_left(), that.growth_left());
1294 swap(hash_ref(), that.hash_ref());
1295 swap(eq_ref(), that.eq_ref());
1296 swap(infoz_, that.infoz_);
Austin Schuhb4691e92020-12-31 12:37:18 -08001297 SwapAlloc(alloc_ref(), that.alloc_ref(),
1298 typename AllocTraits::propagate_on_container_swap{});
Austin Schuh36244a12019-09-21 17:52:38 -07001299 }
1300
1301 void rehash(size_t n) {
1302 if (n == 0 && capacity_ == 0) return;
1303 if (n == 0 && size_ == 0) {
1304 destroy_slots();
1305 infoz_.RecordStorageChanged(0, 0);
1306 return;
1307 }
1308 // bitor is a faster way of doing `max` here. We will round up to the next
1309 // power-of-2-minus-1, so bitor is good enough.
1310 auto m = NormalizeCapacity(n | GrowthToLowerboundCapacity(size()));
1311 // n == 0 unconditionally rehashes as per the standard.
1312 if (n == 0 || m > capacity_) {
1313 resize(m);
1314 }
1315 }
1316
Austin Schuhb4691e92020-12-31 12:37:18 -08001317 void reserve(size_t n) {
1318 size_t m = GrowthToLowerboundCapacity(n);
1319 if (m > capacity_) {
1320 resize(NormalizeCapacity(m));
1321 }
1322 }
Austin Schuh36244a12019-09-21 17:52:38 -07001323
1324 // Extension API: support for heterogeneous keys.
1325 //
1326 // std::unordered_set<std::string> s;
1327 // // Turns "abc" into std::string.
1328 // s.count("abc");
1329 //
1330 // ch_set<std::string> s;
1331 // // Uses "abc" directly without copying it into std::string.
1332 // s.count("abc");
1333 template <class K = key_type>
1334 size_t count(const key_arg<K>& key) const {
1335 return find(key) == end() ? 0 : 1;
1336 }
1337
1338 // Issues CPU prefetch instructions for the memory needed to find or insert
1339 // a key. Like all lookup functions, this support heterogeneous keys.
1340 //
1341 // NOTE: This is a very low level operation and should not be used without
1342 // specific benchmarks indicating its importance.
1343 template <class K = key_type>
1344 void prefetch(const key_arg<K>& key) const {
1345 (void)key;
1346#if defined(__GNUC__)
Austin Schuhb4691e92020-12-31 12:37:18 -08001347 auto seq = probe(ctrl_, hash_ref()(key), capacity_);
Austin Schuh36244a12019-09-21 17:52:38 -07001348 __builtin_prefetch(static_cast<const void*>(ctrl_ + seq.offset()));
1349 __builtin_prefetch(static_cast<const void*>(slots_ + seq.offset()));
1350#endif // __GNUC__
1351 }
1352
1353 // The API of find() has two extensions.
1354 //
1355 // 1. The hash can be passed by the user. It must be equal to the hash of the
1356 // key.
1357 //
1358 // 2. The type of the key argument doesn't have to be key_type. This is so
1359 // called heterogeneous key support.
1360 template <class K = key_type>
1361 iterator find(const key_arg<K>& key, size_t hash) {
Austin Schuhb4691e92020-12-31 12:37:18 -08001362 auto seq = probe(ctrl_, hash, capacity_);
Austin Schuh36244a12019-09-21 17:52:38 -07001363 while (true) {
1364 Group g{ctrl_ + seq.offset()};
1365 for (int i : g.Match(H2(hash))) {
1366 if (ABSL_PREDICT_TRUE(PolicyTraits::apply(
1367 EqualElement<K>{key, eq_ref()},
1368 PolicyTraits::element(slots_ + seq.offset(i)))))
1369 return iterator_at(seq.offset(i));
1370 }
1371 if (ABSL_PREDICT_TRUE(g.MatchEmpty())) return end();
1372 seq.next();
Austin Schuhb4691e92020-12-31 12:37:18 -08001373 assert(seq.index() < capacity_ && "full table!");
Austin Schuh36244a12019-09-21 17:52:38 -07001374 }
1375 }
1376 template <class K = key_type>
1377 iterator find(const key_arg<K>& key) {
1378 return find(key, hash_ref()(key));
1379 }
1380
1381 template <class K = key_type>
1382 const_iterator find(const key_arg<K>& key, size_t hash) const {
1383 return const_cast<raw_hash_set*>(this)->find(key, hash);
1384 }
1385 template <class K = key_type>
1386 const_iterator find(const key_arg<K>& key) const {
1387 return find(key, hash_ref()(key));
1388 }
1389
1390 template <class K = key_type>
1391 bool contains(const key_arg<K>& key) const {
1392 return find(key) != end();
1393 }
1394
1395 template <class K = key_type>
1396 std::pair<iterator, iterator> equal_range(const key_arg<K>& key) {
1397 auto it = find(key);
1398 if (it != end()) return {it, std::next(it)};
1399 return {it, it};
1400 }
1401 template <class K = key_type>
1402 std::pair<const_iterator, const_iterator> equal_range(
1403 const key_arg<K>& key) const {
1404 auto it = find(key);
1405 if (it != end()) return {it, std::next(it)};
1406 return {it, it};
1407 }
1408
1409 size_t bucket_count() const { return capacity_; }
1410 float load_factor() const {
1411 return capacity_ ? static_cast<double>(size()) / capacity_ : 0.0;
1412 }
1413 float max_load_factor() const { return 1.0f; }
1414 void max_load_factor(float) {
1415 // Does nothing.
1416 }
1417
1418 hasher hash_function() const { return hash_ref(); }
1419 key_equal key_eq() const { return eq_ref(); }
1420 allocator_type get_allocator() const { return alloc_ref(); }
1421
1422 friend bool operator==(const raw_hash_set& a, const raw_hash_set& b) {
1423 if (a.size() != b.size()) return false;
1424 const raw_hash_set* outer = &a;
1425 const raw_hash_set* inner = &b;
1426 if (outer->capacity() > inner->capacity()) std::swap(outer, inner);
1427 for (const value_type& elem : *outer)
1428 if (!inner->has_element(elem)) return false;
1429 return true;
1430 }
1431
1432 friend bool operator!=(const raw_hash_set& a, const raw_hash_set& b) {
1433 return !(a == b);
1434 }
1435
1436 friend void swap(raw_hash_set& a,
1437 raw_hash_set& b) noexcept(noexcept(a.swap(b))) {
1438 a.swap(b);
1439 }
1440
1441 private:
1442 template <class Container, typename Enabler>
1443 friend struct absl::container_internal::hashtable_debug_internal::
1444 HashtableDebugAccess;
1445
1446 struct FindElement {
1447 template <class K, class... Args>
1448 const_iterator operator()(const K& key, Args&&...) const {
1449 return s.find(key);
1450 }
1451 const raw_hash_set& s;
1452 };
1453
1454 struct HashElement {
1455 template <class K, class... Args>
1456 size_t operator()(const K& key, Args&&...) const {
1457 return h(key);
1458 }
1459 const hasher& h;
1460 };
1461
1462 template <class K1>
1463 struct EqualElement {
1464 template <class K2, class... Args>
1465 bool operator()(const K2& lhs, Args&&...) const {
1466 return eq(lhs, rhs);
1467 }
1468 const K1& rhs;
1469 const key_equal& eq;
1470 };
1471
1472 struct EmplaceDecomposable {
1473 template <class K, class... Args>
1474 std::pair<iterator, bool> operator()(const K& key, Args&&... args) const {
1475 auto res = s.find_or_prepare_insert(key);
1476 if (res.second) {
1477 s.emplace_at(res.first, std::forward<Args>(args)...);
1478 }
1479 return {s.iterator_at(res.first), res.second};
1480 }
1481 raw_hash_set& s;
1482 };
1483
1484 template <bool do_destroy>
1485 struct InsertSlot {
1486 template <class K, class... Args>
1487 std::pair<iterator, bool> operator()(const K& key, Args&&...) && {
1488 auto res = s.find_or_prepare_insert(key);
1489 if (res.second) {
1490 PolicyTraits::transfer(&s.alloc_ref(), s.slots_ + res.first, &slot);
1491 } else if (do_destroy) {
1492 PolicyTraits::destroy(&s.alloc_ref(), &slot);
1493 }
1494 return {s.iterator_at(res.first), res.second};
1495 }
1496 raw_hash_set& s;
1497 // Constructed slot. Either moved into place or destroyed.
1498 slot_type&& slot;
1499 };
1500
1501 // "erases" the object from the container, except that it doesn't actually
1502 // destroy the object. It only updates all the metadata of the class.
1503 // This can be used in conjunction with Policy::transfer to move the object to
1504 // another place.
1505 void erase_meta_only(const_iterator it) {
1506 assert(IsFull(*it.inner_.ctrl_) && "erasing a dangling iterator");
1507 --size_;
1508 const size_t index = it.inner_.ctrl_ - ctrl_;
1509 const size_t index_before = (index - Group::kWidth) & capacity_;
1510 const auto empty_after = Group(it.inner_.ctrl_).MatchEmpty();
1511 const auto empty_before = Group(ctrl_ + index_before).MatchEmpty();
1512
1513 // We count how many consecutive non empties we have to the right and to the
1514 // left of `it`. If the sum is >= kWidth then there is at least one probe
1515 // window that might have seen a full group.
1516 bool was_never_full =
1517 empty_before && empty_after &&
1518 static_cast<size_t>(empty_after.TrailingZeros() +
1519 empty_before.LeadingZeros()) < Group::kWidth;
1520
1521 set_ctrl(index, was_never_full ? kEmpty : kDeleted);
1522 growth_left() += was_never_full;
1523 infoz_.RecordErase();
1524 }
1525
1526 void initialize_slots() {
1527 assert(capacity_);
1528 // Folks with custom allocators often make unwarranted assumptions about the
1529 // behavior of their classes vis-a-vis trivial destructability and what
1530 // calls they will or wont make. Avoid sampling for people with custom
1531 // allocators to get us out of this mess. This is not a hard guarantee but
1532 // a workaround while we plan the exact guarantee we want to provide.
1533 //
1534 // People are often sloppy with the exact type of their allocator (sometimes
1535 // it has an extra const or is missing the pair, but rebinds made it work
1536 // anyway). To avoid the ambiguity, we work off SlotAlloc which we have
1537 // bound more carefully.
1538 if (std::is_same<SlotAlloc, std::allocator<slot_type>>::value &&
1539 slots_ == nullptr) {
1540 infoz_ = Sample();
1541 }
1542
1543 auto layout = MakeLayout(capacity_);
1544 char* mem = static_cast<char*>(
1545 Allocate<Layout::Alignment()>(&alloc_ref(), layout.AllocSize()));
1546 ctrl_ = reinterpret_cast<ctrl_t*>(layout.template Pointer<0>(mem));
1547 slots_ = layout.template Pointer<1>(mem);
1548 reset_ctrl();
1549 reset_growth_left();
1550 infoz_.RecordStorageChanged(size_, capacity_);
1551 }
1552
1553 void destroy_slots() {
1554 if (!capacity_) return;
1555 for (size_t i = 0; i != capacity_; ++i) {
1556 if (IsFull(ctrl_[i])) {
1557 PolicyTraits::destroy(&alloc_ref(), slots_ + i);
1558 }
1559 }
1560 auto layout = MakeLayout(capacity_);
1561 // Unpoison before returning the memory to the allocator.
1562 SanitizerUnpoisonMemoryRegion(slots_, sizeof(slot_type) * capacity_);
1563 Deallocate<Layout::Alignment()>(&alloc_ref(), ctrl_, layout.AllocSize());
1564 ctrl_ = EmptyGroup();
1565 slots_ = nullptr;
1566 size_ = 0;
1567 capacity_ = 0;
1568 growth_left() = 0;
1569 }
1570
1571 void resize(size_t new_capacity) {
1572 assert(IsValidCapacity(new_capacity));
1573 auto* old_ctrl = ctrl_;
1574 auto* old_slots = slots_;
1575 const size_t old_capacity = capacity_;
1576 capacity_ = new_capacity;
1577 initialize_slots();
1578
1579 size_t total_probe_length = 0;
1580 for (size_t i = 0; i != old_capacity; ++i) {
1581 if (IsFull(old_ctrl[i])) {
1582 size_t hash = PolicyTraits::apply(HashElement{hash_ref()},
1583 PolicyTraits::element(old_slots + i));
Austin Schuhb4691e92020-12-31 12:37:18 -08001584 auto target = find_first_non_full(ctrl_, hash, capacity_);
Austin Schuh36244a12019-09-21 17:52:38 -07001585 size_t new_i = target.offset;
1586 total_probe_length += target.probe_length;
1587 set_ctrl(new_i, H2(hash));
1588 PolicyTraits::transfer(&alloc_ref(), slots_ + new_i, old_slots + i);
1589 }
1590 }
1591 if (old_capacity) {
1592 SanitizerUnpoisonMemoryRegion(old_slots,
1593 sizeof(slot_type) * old_capacity);
1594 auto layout = MakeLayout(old_capacity);
1595 Deallocate<Layout::Alignment()>(&alloc_ref(), old_ctrl,
1596 layout.AllocSize());
1597 }
1598 infoz_.RecordRehash(total_probe_length);
1599 }
1600
1601 void drop_deletes_without_resize() ABSL_ATTRIBUTE_NOINLINE {
1602 assert(IsValidCapacity(capacity_));
Austin Schuhb4691e92020-12-31 12:37:18 -08001603 assert(!is_small(capacity_));
Austin Schuh36244a12019-09-21 17:52:38 -07001604 // Algorithm:
1605 // - mark all DELETED slots as EMPTY
1606 // - mark all FULL slots as DELETED
1607 // - for each slot marked as DELETED
1608 // hash = Hash(element)
1609 // target = find_first_non_full(hash)
1610 // if target is in the same group
1611 // mark slot as FULL
1612 // else if target is EMPTY
1613 // transfer element to target
1614 // mark slot as EMPTY
1615 // mark target as FULL
1616 // else if target is DELETED
1617 // swap current element with target element
1618 // mark target as FULL
1619 // repeat procedure for current slot with moved from element (target)
1620 ConvertDeletedToEmptyAndFullToDeleted(ctrl_, capacity_);
Austin Schuhb4691e92020-12-31 12:37:18 -08001621 alignas(slot_type) unsigned char raw[sizeof(slot_type)];
Austin Schuh36244a12019-09-21 17:52:38 -07001622 size_t total_probe_length = 0;
1623 slot_type* slot = reinterpret_cast<slot_type*>(&raw);
1624 for (size_t i = 0; i != capacity_; ++i) {
1625 if (!IsDeleted(ctrl_[i])) continue;
1626 size_t hash = PolicyTraits::apply(HashElement{hash_ref()},
1627 PolicyTraits::element(slots_ + i));
Austin Schuhb4691e92020-12-31 12:37:18 -08001628 auto target = find_first_non_full(ctrl_, hash, capacity_);
Austin Schuh36244a12019-09-21 17:52:38 -07001629 size_t new_i = target.offset;
1630 total_probe_length += target.probe_length;
1631
1632 // Verify if the old and new i fall within the same group wrt the hash.
1633 // If they do, we don't need to move the object as it falls already in the
1634 // best probe we can.
1635 const auto probe_index = [&](size_t pos) {
Austin Schuhb4691e92020-12-31 12:37:18 -08001636 return ((pos - probe(ctrl_, hash, capacity_).offset()) & capacity_) /
1637 Group::kWidth;
Austin Schuh36244a12019-09-21 17:52:38 -07001638 };
1639
1640 // Element doesn't move.
1641 if (ABSL_PREDICT_TRUE(probe_index(new_i) == probe_index(i))) {
1642 set_ctrl(i, H2(hash));
1643 continue;
1644 }
1645 if (IsEmpty(ctrl_[new_i])) {
1646 // Transfer element to the empty spot.
1647 // set_ctrl poisons/unpoisons the slots so we have to call it at the
1648 // right time.
1649 set_ctrl(new_i, H2(hash));
1650 PolicyTraits::transfer(&alloc_ref(), slots_ + new_i, slots_ + i);
1651 set_ctrl(i, kEmpty);
1652 } else {
1653 assert(IsDeleted(ctrl_[new_i]));
1654 set_ctrl(new_i, H2(hash));
1655 // Until we are done rehashing, DELETED marks previously FULL slots.
1656 // Swap i and new_i elements.
1657 PolicyTraits::transfer(&alloc_ref(), slot, slots_ + i);
1658 PolicyTraits::transfer(&alloc_ref(), slots_ + i, slots_ + new_i);
1659 PolicyTraits::transfer(&alloc_ref(), slots_ + new_i, slot);
1660 --i; // repeat
1661 }
1662 }
1663 reset_growth_left();
1664 infoz_.RecordRehash(total_probe_length);
1665 }
1666
1667 void rehash_and_grow_if_necessary() {
1668 if (capacity_ == 0) {
1669 resize(1);
1670 } else if (size() <= CapacityToGrowth(capacity()) / 2) {
1671 // Squash DELETED without growing if there is enough capacity.
1672 drop_deletes_without_resize();
1673 } else {
1674 // Otherwise grow the container.
1675 resize(capacity_ * 2 + 1);
1676 }
1677 }
1678
1679 bool has_element(const value_type& elem) const {
1680 size_t hash = PolicyTraits::apply(HashElement{hash_ref()}, elem);
Austin Schuhb4691e92020-12-31 12:37:18 -08001681 auto seq = probe(ctrl_, hash, capacity_);
Austin Schuh36244a12019-09-21 17:52:38 -07001682 while (true) {
1683 Group g{ctrl_ + seq.offset()};
1684 for (int i : g.Match(H2(hash))) {
1685 if (ABSL_PREDICT_TRUE(PolicyTraits::element(slots_ + seq.offset(i)) ==
1686 elem))
1687 return true;
1688 }
1689 if (ABSL_PREDICT_TRUE(g.MatchEmpty())) return false;
1690 seq.next();
1691 assert(seq.index() < capacity_ && "full table!");
1692 }
1693 return false;
1694 }
1695
Austin Schuh36244a12019-09-21 17:52:38 -07001696 // TODO(alkis): Optimize this assuming *this and that don't overlap.
1697 raw_hash_set& move_assign(raw_hash_set&& that, std::true_type) {
1698 raw_hash_set tmp(std::move(that));
1699 swap(tmp);
1700 return *this;
1701 }
1702 raw_hash_set& move_assign(raw_hash_set&& that, std::false_type) {
1703 raw_hash_set tmp(std::move(that), alloc_ref());
1704 swap(tmp);
1705 return *this;
1706 }
1707
1708 protected:
1709 template <class K>
1710 std::pair<size_t, bool> find_or_prepare_insert(const K& key) {
1711 auto hash = hash_ref()(key);
Austin Schuhb4691e92020-12-31 12:37:18 -08001712 auto seq = probe(ctrl_, hash, capacity_);
Austin Schuh36244a12019-09-21 17:52:38 -07001713 while (true) {
1714 Group g{ctrl_ + seq.offset()};
1715 for (int i : g.Match(H2(hash))) {
1716 if (ABSL_PREDICT_TRUE(PolicyTraits::apply(
1717 EqualElement<K>{key, eq_ref()},
1718 PolicyTraits::element(slots_ + seq.offset(i)))))
1719 return {seq.offset(i), false};
1720 }
1721 if (ABSL_PREDICT_TRUE(g.MatchEmpty())) break;
1722 seq.next();
Austin Schuhb4691e92020-12-31 12:37:18 -08001723 assert(seq.index() < capacity_ && "full table!");
Austin Schuh36244a12019-09-21 17:52:38 -07001724 }
1725 return {prepare_insert(hash), true};
1726 }
1727
1728 size_t prepare_insert(size_t hash) ABSL_ATTRIBUTE_NOINLINE {
Austin Schuhb4691e92020-12-31 12:37:18 -08001729 auto target = find_first_non_full(ctrl_, hash, capacity_);
Austin Schuh36244a12019-09-21 17:52:38 -07001730 if (ABSL_PREDICT_FALSE(growth_left() == 0 &&
1731 !IsDeleted(ctrl_[target.offset]))) {
1732 rehash_and_grow_if_necessary();
Austin Schuhb4691e92020-12-31 12:37:18 -08001733 target = find_first_non_full(ctrl_, hash, capacity_);
Austin Schuh36244a12019-09-21 17:52:38 -07001734 }
1735 ++size_;
1736 growth_left() -= IsEmpty(ctrl_[target.offset]);
1737 set_ctrl(target.offset, H2(hash));
1738 infoz_.RecordInsert(hash, target.probe_length);
1739 return target.offset;
1740 }
1741
1742 // Constructs the value in the space pointed by the iterator. This only works
1743 // after an unsuccessful find_or_prepare_insert() and before any other
1744 // modifications happen in the raw_hash_set.
1745 //
1746 // PRECONDITION: i is an index returned from find_or_prepare_insert(k), where
1747 // k is the key decomposed from `forward<Args>(args)...`, and the bool
1748 // returned by find_or_prepare_insert(k) was true.
1749 // POSTCONDITION: *m.iterator_at(i) == value_type(forward<Args>(args)...).
1750 template <class... Args>
1751 void emplace_at(size_t i, Args&&... args) {
1752 PolicyTraits::construct(&alloc_ref(), slots_ + i,
1753 std::forward<Args>(args)...);
1754
1755 assert(PolicyTraits::apply(FindElement{*this}, *iterator_at(i)) ==
1756 iterator_at(i) &&
1757 "constructed value does not match the lookup key");
1758 }
1759
1760 iterator iterator_at(size_t i) { return {ctrl_ + i, slots_ + i}; }
1761 const_iterator iterator_at(size_t i) const { return {ctrl_ + i, slots_ + i}; }
1762
1763 private:
1764 friend struct RawHashSetTestOnlyAccess;
1765
Austin Schuh36244a12019-09-21 17:52:38 -07001766 // Reset all ctrl bytes back to kEmpty, except the sentinel.
1767 void reset_ctrl() {
1768 std::memset(ctrl_, kEmpty, capacity_ + Group::kWidth);
1769 ctrl_[capacity_] = kSentinel;
1770 SanitizerPoisonMemoryRegion(slots_, sizeof(slot_type) * capacity_);
1771 }
1772
1773 void reset_growth_left() {
1774 growth_left() = CapacityToGrowth(capacity()) - size_;
1775 }
1776
1777 // Sets the control byte, and if `i < Group::kWidth`, set the cloned byte at
1778 // the end too.
1779 void set_ctrl(size_t i, ctrl_t h) {
1780 assert(i < capacity_);
1781
1782 if (IsFull(h)) {
1783 SanitizerUnpoisonObject(slots_ + i);
1784 } else {
1785 SanitizerPoisonObject(slots_ + i);
1786 }
1787
1788 ctrl_[i] = h;
1789 ctrl_[((i - Group::kWidth) & capacity_) + 1 +
1790 ((Group::kWidth - 1) & capacity_)] = h;
1791 }
1792
1793 size_t& growth_left() { return settings_.template get<0>(); }
1794
Austin Schuh36244a12019-09-21 17:52:38 -07001795 hasher& hash_ref() { return settings_.template get<1>(); }
1796 const hasher& hash_ref() const { return settings_.template get<1>(); }
1797 key_equal& eq_ref() { return settings_.template get<2>(); }
1798 const key_equal& eq_ref() const { return settings_.template get<2>(); }
1799 allocator_type& alloc_ref() { return settings_.template get<3>(); }
1800 const allocator_type& alloc_ref() const {
1801 return settings_.template get<3>();
1802 }
1803
1804 // TODO(alkis): Investigate removing some of these fields:
1805 // - ctrl/slots can be derived from each other
1806 // - size can be moved into the slot array
1807 ctrl_t* ctrl_ = EmptyGroup(); // [(capacity + 1) * ctrl_t]
1808 slot_type* slots_ = nullptr; // [capacity * slot_type]
1809 size_t size_ = 0; // number of full slots
1810 size_t capacity_ = 0; // total number of slots
1811 HashtablezInfoHandle infoz_;
1812 absl::container_internal::CompressedTuple<size_t /* growth_left */, hasher,
1813 key_equal, allocator_type>
1814 settings_{0, hasher{}, key_equal{}, allocator_type{}};
1815};
1816
Austin Schuhb4691e92020-12-31 12:37:18 -08001817// Erases all elements that satisfy the predicate `pred` from the container `c`.
1818template <typename P, typename H, typename E, typename A, typename Predicate>
1819void EraseIf(Predicate pred, raw_hash_set<P, H, E, A>* c) {
1820 for (auto it = c->begin(), last = c->end(); it != last;) {
1821 auto copy_it = it++;
1822 if (pred(*copy_it)) {
1823 c->erase(copy_it);
1824 }
1825 }
1826}
1827
Austin Schuh36244a12019-09-21 17:52:38 -07001828namespace hashtable_debug_internal {
1829template <typename Set>
1830struct HashtableDebugAccess<Set, absl::void_t<typename Set::raw_hash_set>> {
1831 using Traits = typename Set::PolicyTraits;
1832 using Slot = typename Traits::slot_type;
1833
1834 static size_t GetNumProbes(const Set& set,
1835 const typename Set::key_type& key) {
1836 size_t num_probes = 0;
1837 size_t hash = set.hash_ref()(key);
Austin Schuhb4691e92020-12-31 12:37:18 -08001838 auto seq = probe(set.ctrl_, hash, set.capacity_);
Austin Schuh36244a12019-09-21 17:52:38 -07001839 while (true) {
1840 container_internal::Group g{set.ctrl_ + seq.offset()};
1841 for (int i : g.Match(container_internal::H2(hash))) {
1842 if (Traits::apply(
1843 typename Set::template EqualElement<typename Set::key_type>{
1844 key, set.eq_ref()},
1845 Traits::element(set.slots_ + seq.offset(i))))
1846 return num_probes;
1847 ++num_probes;
1848 }
1849 if (g.MatchEmpty()) return num_probes;
1850 seq.next();
1851 ++num_probes;
1852 }
1853 }
1854
1855 static size_t AllocatedByteSize(const Set& c) {
1856 size_t capacity = c.capacity_;
1857 if (capacity == 0) return 0;
1858 auto layout = Set::MakeLayout(capacity);
1859 size_t m = layout.AllocSize();
1860
1861 size_t per_slot = Traits::space_used(static_cast<const Slot*>(nullptr));
1862 if (per_slot != ~size_t{}) {
1863 m += per_slot * c.size();
1864 } else {
1865 for (size_t i = 0; i != capacity; ++i) {
1866 if (container_internal::IsFull(c.ctrl_[i])) {
1867 m += Traits::space_used(c.slots_ + i);
1868 }
1869 }
1870 }
1871 return m;
1872 }
1873
1874 static size_t LowerBoundAllocatedByteSize(size_t size) {
1875 size_t capacity = GrowthToLowerboundCapacity(size);
1876 if (capacity == 0) return 0;
1877 auto layout = Set::MakeLayout(NormalizeCapacity(capacity));
1878 size_t m = layout.AllocSize();
1879 size_t per_slot = Traits::space_used(static_cast<const Slot*>(nullptr));
1880 if (per_slot != ~size_t{}) {
1881 m += per_slot * size;
1882 }
1883 return m;
1884 }
1885};
1886
1887} // namespace hashtable_debug_internal
1888} // namespace container_internal
Austin Schuhb4691e92020-12-31 12:37:18 -08001889ABSL_NAMESPACE_END
Austin Schuh36244a12019-09-21 17:52:38 -07001890} // namespace absl
1891
1892#endif // ABSL_CONTAINER_INTERNAL_RAW_HASH_SET_H_