Coverage Report

Created: 2026-12-01 06:15

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/parallel-hashmap/parallel_hashmap/phmap.h
Line
Count
Source
1
#if !defined(phmap_h_guard_)
2
#define phmap_h_guard_
3
4
// ---------------------------------------------------------------------------
5
// Copyright (c) 2019, Gregory Popovitch - greg7mdp@gmail.com
6
//
7
// Licensed under the Apache License, Version 2.0 (the "License");
8
// you may not use this file except in compliance with the License.
9
// You may obtain a copy of the License at
10
//
11
//      https://www.apache.org/licenses/LICENSE-2.0
12
//
13
// Unless required by applicable law or agreed to in writing, software
14
// distributed under the License is distributed on an "AS IS" BASIS,
15
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
// See the License for the specific language governing permissions and
17
// limitations under the License.
18
//
19
// Includes work from abseil-cpp (https://github.com/abseil/abseil-cpp)
20
// with modifications.
21
// 
22
// Copyright 2018 The Abseil Authors.
23
//
24
// Licensed under the Apache License, Version 2.0 (the "License");
25
// you may not use this file except in compliance with the License.
26
// You may obtain a copy of the License at
27
//
28
//      https://www.apache.org/licenses/LICENSE-2.0
29
//
30
// Unless required by applicable law or agreed to in writing, software
31
// distributed under the License is distributed on an "AS IS" BASIS,
32
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33
// See the License for the specific language governing permissions and
34
// limitations under the License.
35
// ---------------------------------------------------------------------------
36
37
// ---------------------------------------------------------------------------
38
// IMPLEMENTATION DETAILS
39
//
40
// The table stores elements inline in a slot array. In addition to the slot
41
// array the table maintains some control state per slot. The extra state is one
42
// byte per slot and stores empty or deleted marks, or alternatively 7 bits from
43
// the hash of an occupied slot. The table is split into logical groups of
44
// slots, like so:
45
//
46
//      Group 1         Group 2        Group 3
47
// +---------------+---------------+---------------+
48
// | | | | | | | | | | | | | | | | | | | | | | | | |
49
// +---------------+---------------+---------------+
50
//
51
// On lookup the hash is split into two parts:
52
// - H2: 7 bits (those stored in the control bytes)
53
// - H1: the rest of the bits
54
// The groups are probed using H1. For each group the slots are matched to H2 in
55
// parallel. Because H2 is 7 bits (128 states) and the number of slots per group
56
// is low (8 or 16) in almost all cases a match in H2 is also a lookup hit.
57
//
58
// On insert, once the right group is found (as in lookup), its slots are
59
// filled in order.
60
//
61
// On erase a slot is cleared. In case the group did not have any empty slots
62
// before the erase, the erased slot is marked as deleted.
63
//
64
// Groups without empty slots (but maybe with deleted slots) extend the probe
65
// sequence. The probing algorithm is quadratic. Given N the number of groups,
66
// the probing function for the i'th probe is:
67
//
68
//   P(0) = H1 % N
69
//
70
//   P(i) = (P(i - 1) + i) % N
71
//
72
// This probing function guarantees that after N probes, all the groups of the
73
// table will be probed exactly once.
74
//
75
// The control state and slot array are stored contiguously in a shared heap
76
// allocation. The layout of this allocation is: `capacity()` control bytes,
77
// one sentinel control byte, `Group::kWidth - 1` cloned control bytes,
78
// <possible padding>, `capacity()` slots. The sentinel control byte is used in
79
// iteration so we know when we reach the end of the table. The cloned control
80
// bytes at the end of the table are cloned from the beginning of the table so
81
// groups that begin near the end of the table can see a full group. In cases in
82
// which there are more than `capacity()` cloned control bytes, the extra bytes
83
// are `kEmpty`, and these ensure that we always see at least one empty slot and
84
// can stop an unsuccessful search.
85
// ---------------------------------------------------------------------------
86
87
88
89
#ifdef _MSC_VER
90
    #pragma warning(push)  
91
92
    #pragma warning(disable : 4127) // conditional expression is constant
93
    #pragma warning(disable : 4324) // structure was padded due to alignment specifier
94
    #pragma warning(disable : 4514) // unreferenced inline function has been removed
95
    #pragma warning(disable : 4623) // default constructor was implicitly defined as deleted
96
    #pragma warning(disable : 4625) // copy constructor was implicitly defined as deleted
97
    #pragma warning(disable : 4626) // assignment operator was implicitly defined as deleted
98
    #pragma warning(disable : 4710) // function not inlined
99
    #pragma warning(disable : 4711) // selected for automatic inline expansion
100
    #pragma warning(disable : 4820) // '6' bytes padding added after data member
101
    #pragma warning(disable : 4868) // compiler may not enforce left-to-right evaluation order in braced initializer list
102
    #pragma warning(disable : 5027) // move assignment operator was implicitly defined as deleted
103
    #pragma warning(disable : 5045) // Compiler will insert Spectre mitigation for memory load if /Qspectre switch specified
104
#endif
105
106
#include <algorithm>
107
#include <cmath>
108
#include <cstring>
109
#include <iterator>
110
#include <limits>
111
#include <memory>
112
#include <tuple>
113
#include <type_traits>
114
#include <utility>
115
#include <array>
116
#include <cassert>
117
#include <atomic>
118
119
#include "phmap_fwd_decl.h"
120
#include "phmap_utils.h"
121
#include "phmap_base.h"
122
123
#if PHMAP_HAVE_STD_STRING_VIEW
124
    #include <string_view>
125
#endif
126
127
namespace phmap {
128
129
namespace priv {
130
131
// --------------------------------------------------------------------------
132
template <typename AllocType>
133
void SwapAlloc(AllocType& lhs, AllocType& rhs,
134
               std::true_type /* propagate_on_container_swap */) {
135
  using std::swap;
136
  swap(lhs, rhs);
137
}
138
139
template <typename AllocType>
140
void SwapAlloc(AllocType& /*lhs*/, AllocType& /*rhs*/,
141
601
               std::false_type /* propagate_on_container_swap */) {}
142
143
// --------------------------------------------------------------------------
144
template <size_t Width>
145
class probe_seq 
146
{
147
public:
148
14.2M
    probe_seq(size_t hashval, size_t mask) {
149
14.2M
        assert(((mask + 1) & mask) == 0 && "not a mask");
150
14.2M
        mask_ = mask;
151
14.2M
        offset_ = hashval & mask_;
152
14.2M
    }
153
15.5M
    size_t offset() const { return offset_; }
154
27.0M
    size_t offset(size_t i) const { return (offset_ + i) & mask_; }
155
156
1.24M
    void next() {
157
1.24M
        index_ += Width;
158
1.24M
        offset_ += index_;
159
1.24M
        offset_ &= mask_;
160
1.24M
    }
161
    // 0-based probe index. The i-th probe in the probe sequence.
162
2.07M
    size_t getindex() const { return index_; }
163
164
private:
165
    size_t mask_;
166
    size_t offset_;
167
    size_t index_ = 0;
168
};
169
170
// --------------------------------------------------------------------------
171
template <class ContainerKey, class Hash, class Eq>
172
struct RequireUsableKey 
173
{
174
    template <class PassedKey, class... Args>
175
    std::pair<
176
        decltype(std::declval<const Hash&>()(std::declval<const PassedKey&>())),
177
        decltype(std::declval<const Eq&>()(std::declval<const ContainerKey&>(),
178
                                           std::declval<const PassedKey&>()))>*
179
    operator()(const PassedKey&, const Args&...) const;
180
};
181
182
// --------------------------------------------------------------------------
183
template <class E, class Policy, class Hash, class Eq, class... Ts>
184
struct IsDecomposable : std::false_type {};
185
186
template <class Policy, class Hash, class Eq, class... Ts>
187
struct IsDecomposable<
188
    phmap::void_t<decltype(
189
        Policy::apply(RequireUsableKey<typename Policy::key_type, Hash, Eq>(),
190
                      std::declval<Ts>()...))>,
191
    Policy, Hash, Eq, Ts...> : std::true_type {};
192
193
// TODO(alkis): Switch to std::is_nothrow_swappable when gcc/clang supports it.
194
// --------------------------------------------------------------------------
195
template <class T>
196
0
constexpr bool IsNoThrowSwappable(std::true_type = {} /* is_swappable */) {
197
0
    using std::swap;
198
0
    return noexcept(swap(std::declval<T&>(), std::declval<T&>()));
199
0
}
Unexecuted instantiation: bool phmap::priv::IsNoThrowSwappable<phmap::Hash<unsigned int> >(std::__1::integral_constant<bool, true>)
Unexecuted instantiation: bool phmap::priv::IsNoThrowSwappable<phmap::EqualTo<unsigned int> >(std::__1::integral_constant<bool, true>)
200
201
template <class T>
202
0
constexpr bool IsNoThrowSwappable(std::false_type /* is_swappable */) {
203
0
  return false;
204
0
}
205
206
// --------------------------------------------------------------------------
207
template <typename T>
208
16.3M
uint32_t TrailingZeros(T x) {
209
16.3M
    uint32_t res;
210
16.3M
    PHMAP_IF_CONSTEXPR(sizeof(T) == 8)
211
        res = base_internal::CountTrailingZerosNonZero64(static_cast<uint64_t>(x));
212
    else
213
16.3M
        res = base_internal::CountTrailingZerosNonZero32(static_cast<uint32_t>(x));
214
16.3M
    return res;
215
16.3M
}
unsigned int phmap::priv::TrailingZeros<unsigned int>(unsigned int)
Line
Count
Source
208
16.3M
uint32_t TrailingZeros(T x) {
209
16.3M
    uint32_t res;
210
16.3M
    PHMAP_IF_CONSTEXPR(sizeof(T) == 8)
211
        res = base_internal::CountTrailingZerosNonZero64(static_cast<uint64_t>(x));
212
    else
213
16.3M
        res = base_internal::CountTrailingZerosNonZero32(static_cast<uint32_t>(x));
214
16.3M
    return res;
215
16.3M
}
Unexecuted instantiation: unsigned int phmap::priv::TrailingZeros<unsigned long>(unsigned long)
216
217
// --------------------------------------------------------------------------
218
template <typename T>
219
0
uint32_t LeadingZeros(T x) {
220
0
    uint32_t res;
221
0
    PHMAP_IF_CONSTEXPR(sizeof(T) == 8)
222
0
        res = base_internal::CountLeadingZeros64(static_cast<uint64_t>(x));
223
0
    else
224
0
        res = base_internal::CountLeadingZeros32(static_cast<uint32_t>(x));
225
0
    return res;
226
0
}
227
228
// --------------------------------------------------------------------------
229
// An abstraction over a bitmask. It provides an easy way to iterate through the
230
// indexes of the set bits of a bitmask.  When Shift=0 (platforms with SSE),
231
// this is a true bitmask.  On non-SSE, platforms the arithematic used to
232
// emulate the SSE behavior works in bytes (Shift=3) and leaves each bytes as
233
// either 0x00 or 0x80.
234
//
235
// For example:
236
//   for (int i : BitMask<uint32_t, 16>(0x5)) -> yields 0, 2
237
//   for (int i : BitMask<uint64_t, 8, 3>(0x0000000080800000)) -> yields 2, 3
238
// --------------------------------------------------------------------------
239
template <class T, int SignificantBits, int Shift = 0>
240
class BitMask 
241
{
242
    static_assert(std::is_unsigned<T>::value, "");
243
    static_assert(Shift == 0 || Shift == 3, "");
244
245
public:
246
    // These are useful for unit tests (gunit).
247
    using value_type = int;
248
    using iterator = BitMask;
249
    using const_iterator = BitMask;
250
251
30.8M
    explicit BitMask(T mask) : mask_(mask) {}
252
253
2.53M
    BitMask& operator++() {    // ++iterator
254
2.53M
        mask_ &= (mask_ - 1);  // clear the least significant bit set
255
2.53M
        return *this;
256
2.53M
    }
257
258
3.91M
    explicit operator bool() const { return mask_ != 0; }
259
14.1M
    uint32_t operator*() const { return LowestBitSet(); }
260
261
16.1M
    uint32_t LowestBitSet() const {
262
16.1M
        return priv::TrailingZeros(mask_) >> Shift;
263
16.1M
    }
264
265
    uint32_t HighestBitSet() const {
266
        return (sizeof(T) * CHAR_BIT - priv::LeadingZeros(mask_) - 1) >> Shift;
267
    }
268
269
13.4M
    BitMask begin() const { return *this; }
270
13.4M
    BitMask end() const { return BitMask(0); }
271
272
    uint32_t TrailingZeros() const {
273
        return priv::TrailingZeros(mask_) >> Shift;
274
    }
275
276
    uint32_t LeadingZeros() const {
277
        constexpr uint32_t total_significant_bits = SignificantBits << Shift;
278
        constexpr uint32_t extra_bits = sizeof(T) * 8 - total_significant_bits;
279
        return priv::LeadingZeros(mask_ << extra_bits) >> Shift;
280
    }
281
282
private:
283
    friend bool operator==(const BitMask& a, const BitMask& b) {
284
        return a.mask_ == b.mask_;
285
    }
286
15.9M
    friend bool operator!=(const BitMask& a, const BitMask& b) {
287
15.9M
        return a.mask_ != b.mask_;
288
15.9M
    }
289
290
    T mask_;
291
};
292
293
// --------------------------------------------------------------------------
294
using ctrl_t = signed char;
295
using h2_t = uint8_t;
296
297
// --------------------------------------------------------------------------
298
// The values here are selected for maximum performance. See the static asserts
299
// below for details.
300
// --------------------------------------------------------------------------
301
enum Ctrl : ctrl_t 
302
{
303
    kEmpty = -128,   // 0b10000000 or 0x80
304
    kDeleted = -2,   // 0b11111110 or 0xfe
305
    kSentinel = -1,  // 0b11111111 or 0xff
306
};
307
308
static_assert(
309
    kEmpty & kDeleted & kSentinel & 0x80,
310
    "Special markers need to have the MSB to make checking for them efficient");
311
static_assert(kEmpty < kSentinel && kDeleted < kSentinel,
312
              "kEmpty and kDeleted must be smaller than kSentinel to make the "
313
              "SIMD test of IsEmptyOrDeleted() efficient");
314
static_assert(kSentinel == -1,
315
              "kSentinel must be -1 to elide loading it from memory into SIMD "
316
              "registers (pcmpeqd xmm, xmm)");
317
static_assert(kEmpty == -128,
318
              "kEmpty must be -128 to make the SIMD check for its "
319
              "existence efficient (psignb xmm, xmm)");
320
static_assert(~kEmpty & ~kDeleted & kSentinel & 0x7F,
321
              "kEmpty and kDeleted must share an unset bit that is not shared "
322
              "by kSentinel to make the scalar test for MatchEmptyOrDeleted() "
323
              "efficient");
324
static_assert(kDeleted == -2,
325
              "kDeleted must be -2 to make the implementation of "
326
              "ConvertSpecialToEmptyAndFullToDeleted efficient");
327
328
// --------------------------------------------------------------------------
329
// A single block of empty control bytes for tables without any slots allocated.
330
// This enables removing a branch in the hot path of find().
331
// --------------------------------------------------------------------------
332
template <class std_alloc_t>
333
3.11k
inline ctrl_t* EmptyGroup() {
334
3.11k
  PHMAP_IF_CONSTEXPR (std_alloc_t::value) {
335
3.11k
      alignas(16) static constexpr ctrl_t empty_group[] = {
336
3.11k
          kSentinel, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty,
337
3.11k
          kEmpty,    kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty};
338
339
3.11k
      return const_cast<ctrl_t*>(empty_group);
340
  } else {
341
       return nullptr;
342
  }
343
3.11k
}
signed char* phmap::priv::EmptyGroup<std::__1::is_same<std::__1::allocator<std::__1::pair<unsigned int const, int> >, std::__1::allocator<std::__1::pair<unsigned int const, int> > > >()
Line
Count
Source
333
2.50k
inline ctrl_t* EmptyGroup() {
334
2.50k
  PHMAP_IF_CONSTEXPR (std_alloc_t::value) {
335
2.50k
      alignas(16) static constexpr ctrl_t empty_group[] = {
336
2.50k
          kSentinel, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty,
337
2.50k
          kEmpty,    kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty};
338
339
2.50k
      return const_cast<ctrl_t*>(empty_group);
340
  } else {
341
       return nullptr;
342
  }
343
2.50k
}
signed char* phmap::priv::EmptyGroup<std::__1::is_same<std::__1::allocator<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > >, std::__1::allocator<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > > >()
Line
Count
Source
333
601
inline ctrl_t* EmptyGroup() {
334
601
  PHMAP_IF_CONSTEXPR (std_alloc_t::value) {
335
601
      alignas(16) static constexpr ctrl_t empty_group[] = {
336
601
          kSentinel, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty,
337
601
          kEmpty,    kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty};
338
339
601
      return const_cast<ctrl_t*>(empty_group);
340
  } else {
341
       return nullptr;
342
  }
343
601
}
344
345
// --------------------------------------------------------------------------
346
0
inline size_t HashSeed(const ctrl_t* ctrl) {
347
0
  // The low bits of the pointer have little or no entropy because of
348
0
  // alignment. We shift the pointer to try to use higher entropy bits. A
349
0
  // good number seems to be 12 bits, because that aligns with page size.
350
0
  return reinterpret_cast<uintptr_t>(ctrl) >> 12;
351
0
}
352
353
#ifdef PHMAP_NON_DETERMINISTIC
354
355
inline size_t H1(size_t hashval, const ctrl_t* ctrl) {
356
    // use ctrl_ pointer to add entropy to ensure
357
    // non-deterministic iteration order.
358
    return (hashval >> 7) ^ HashSeed(ctrl);
359
}
360
361
#else
362
363
14.2M
inline size_t H1(size_t hashval, const ctrl_t* ) {
364
14.2M
    return (hashval >> 7);
365
14.2M
}
366
367
#endif
368
369
370
15.4M
inline ctrl_t H2(size_t hashval)       { return (ctrl_t)(hashval & 0x7F); }
371
372
711k
inline bool IsEmpty(ctrl_t c)          { return c == kEmpty; }
373
3.39M
inline bool IsFull(ctrl_t c)           { return c >= static_cast<ctrl_t>(0); }
374
3.25k
inline bool IsDeleted(ctrl_t c)        { return c == kDeleted; }
375
963k
inline bool IsEmptyOrDeleted(ctrl_t c) { return c < kSentinel; }
376
377
#if PHMAP_HAVE_SSE2
378
379
#ifdef _MSC_VER
380
    #pragma warning(push)  
381
    #pragma warning(disable : 4365) // conversion from 'int' to 'T', signed/unsigned mismatch
382
#endif
383
384
// --------------------------------------------------------------------------
385
// https://github.com/abseil/abseil-cpp/issues/209
386
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=87853
387
// _mm_cmpgt_epi8 is broken under GCC with -funsigned-char
388
// Work around this by using the portable implementation of Group
389
// when using -funsigned-char under GCC.
390
// --------------------------------------------------------------------------
391
2.34M
inline __m128i _mm_cmpgt_epi8_fixed(__m128i a, __m128i b) {
392
#if defined(__GNUC__) && !defined(__clang__)
393
  #pragma GCC diagnostic push
394
  #pragma GCC diagnostic ignored "-Woverflow"
395
396
  if (std::is_unsigned<char>::value) {
397
    const __m128i mask = _mm_set1_epi8(static_cast<char>(0x80));
398
    const __m128i diff = _mm_subs_epi8(b, a);
399
    return _mm_cmpeq_epi8(_mm_and_si128(diff, mask), mask);
400
  }
401
402
  #pragma GCC diagnostic pop
403
#endif
404
2.34M
  return _mm_cmpgt_epi8(a, b);
405
2.34M
}
406
407
// --------------------------------------------------------------------------
408
// --------------------------------------------------------------------------
409
struct GroupSse2Impl 
410
{
411
    enum { kWidth = 16 };  // the number of slots per group
412
413
15.8M
    explicit GroupSse2Impl(const ctrl_t* pos) {
414
15.8M
        ctrl = _mm_loadu_si128(reinterpret_cast<const __m128i*>(pos));
415
15.8M
    }
416
417
    // Returns a bitmask representing the positions of slots that match hash.
418
    // ----------------------------------------------------------------------
419
15.3M
    BitMask<uint32_t, kWidth> Match(h2_t hash) const {
420
15.3M
        auto match = _mm_set1_epi8((char)hash);
421
15.3M
        return BitMask<uint32_t, kWidth>(
422
15.3M
            static_cast<uint32_t>(_mm_movemask_epi8(_mm_cmpeq_epi8(match, ctrl))));
423
15.3M
    }
424
425
    // Returns a bitmask representing the positions of empty slots.
426
    // ------------------------------------------------------------
427
1.84M
    BitMask<uint32_t, kWidth> MatchEmpty() const {
428
#if PHMAP_HAVE_SSSE3
429
        // This only works because kEmpty is -128.
430
        return BitMask<uint32_t, kWidth>(
431
            static_cast<uint32_t>(_mm_movemask_epi8(_mm_sign_epi8(ctrl, ctrl))));
432
#else
433
1.84M
        return Match(static_cast<h2_t>(kEmpty));
434
1.84M
#endif
435
1.84M
    }
436
437
    // Returns a bitmask representing the positions of empty or deleted slots.
438
    // -----------------------------------------------------------------------
439
2.07M
    BitMask<uint32_t, kWidth> MatchEmptyOrDeleted() const {
440
2.07M
        auto special = _mm_set1_epi8(static_cast<char>(kSentinel));
441
2.07M
        return BitMask<uint32_t, kWidth>(
442
2.07M
            static_cast<uint32_t>(_mm_movemask_epi8(_mm_cmpgt_epi8_fixed(special, ctrl))));
443
2.07M
    }
444
445
    // Returns the number of trailing empty or deleted elements in the group.
446
    // ----------------------------------------------------------------------
447
268k
    uint32_t CountLeadingEmptyOrDeleted() const {
448
268k
        auto special = _mm_set1_epi8(static_cast<char>(kSentinel));
449
268k
        return TrailingZeros(
450
268k
            static_cast<uint32_t>(_mm_movemask_epi8(_mm_cmpgt_epi8_fixed(special, ctrl)) + 1));
451
268k
    }
452
453
    // ----------------------------------------------------------------------
454
0
    void ConvertSpecialToEmptyAndFullToDeleted(ctrl_t* dst) const {
455
0
        auto msbs = _mm_set1_epi8(static_cast<char>(-128));
456
0
        auto x126 = _mm_set1_epi8(126);
457
#if PHMAP_HAVE_SSSE3
458
        auto res = _mm_or_si128(_mm_shuffle_epi8(x126, ctrl), msbs);
459
#else
460
0
        auto zero = _mm_setzero_si128();
461
0
        auto special_mask = _mm_cmpgt_epi8_fixed(zero, ctrl);
462
0
        auto res = _mm_or_si128(msbs, _mm_andnot_si128(special_mask, x126));
463
0
#endif
464
0
        _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), res);
465
0
    }
466
467
    __m128i ctrl;
468
};
469
470
#ifdef _MSC_VER
471
     #pragma warning(pop)  
472
#endif
473
474
#endif  // PHMAP_HAVE_SSE2
475
476
// --------------------------------------------------------------------------
477
// --------------------------------------------------------------------------
478
struct GroupPortableImpl 
479
{
480
    enum { kWidth = 8 };
481
482
    explicit GroupPortableImpl(const ctrl_t* pos)
483
0
        : ctrl(little_endian::Load64(pos)) {}
484
485
0
    BitMask<uint64_t, kWidth, 3> Match(h2_t hash) const {
486
0
        // For the technique, see:
487
0
        // http://graphics.stanford.edu/~seander/bithacks.html##ValueInWord
488
0
        // (Determine if a word has a byte equal to n).
489
0
        //
490
0
        // Caveat: there are false positives but:
491
0
        // - they only occur if there is a real match
492
0
        // - they never occur on kEmpty, kDeleted, kSentinel
493
0
        // - they will be handled gracefully by subsequent checks in code
494
0
        //
495
0
        // Example:
496
0
        //   v = 0x1716151413121110
497
0
        //   hash = 0x12
498
0
        //   retval = (v - lsbs) & ~v & msbs = 0x0000000080800000
499
0
        constexpr uint64_t msbs = 0x8080808080808080ULL;
500
0
        constexpr uint64_t lsbs = 0x0101010101010101ULL;
501
0
        auto x = ctrl ^ (lsbs * hash);
502
0
        return BitMask<uint64_t, kWidth, 3>((x - lsbs) & ~x & msbs);
503
0
    }
504
505
0
    BitMask<uint64_t, kWidth, 3> MatchEmpty() const {          // bit 1 of each byte is 0 for empty (but not for deleted)
506
0
        constexpr uint64_t msbs = 0x8080808080808080ULL;
507
0
        return BitMask<uint64_t, kWidth, 3>((ctrl & (~ctrl << 6)) & msbs);
508
0
    }
509
510
0
    BitMask<uint64_t, kWidth, 3> MatchEmptyOrDeleted() const { // lsb of each byte is 0 for empty or deleted
511
0
        constexpr uint64_t msbs = 0x8080808080808080ULL;
512
0
        return BitMask<uint64_t, kWidth, 3>((ctrl & (~ctrl << 7)) & msbs);
513
0
    }
514
515
0
    uint32_t CountLeadingEmptyOrDeleted() const {
516
0
        constexpr uint64_t gaps = 0x00FEFEFEFEFEFEFEULL;
517
0
        return (uint32_t)((TrailingZeros(((~ctrl & (ctrl >> 7)) | gaps) + 1) + 7) >> 3);
518
0
    }
519
520
0
    void ConvertSpecialToEmptyAndFullToDeleted(ctrl_t* dst) const {
521
0
        constexpr uint64_t msbs = 0x8080808080808080ULL;
522
0
        constexpr uint64_t lsbs = 0x0101010101010101ULL;
523
0
        auto x = ctrl & msbs;
524
0
        auto res = (~x + (x >> 7)) & ~lsbs;
525
0
        little_endian::Store64(dst, res);
526
0
    }
527
528
    uint64_t ctrl;
529
};
530
531
#if PHMAP_HAVE_SSE2  
532
    using Group = GroupSse2Impl;
533
#else
534
    using Group = GroupPortableImpl;
535
#endif
536
537
// The number of cloned control bytes that we copy from the beginning to the
538
// end of the control bytes array.
539
// -------------------------------------------------------------------------
540
0
constexpr size_t NumClonedBytes() { return Group::kWidth - 1; }
541
542
template <class Policy, class Hash, class Eq, class Alloc>
543
class raw_hash_set;
544
545
16.4k
inline bool IsValidCapacity(size_t n) { return ((n + 1) & n) == 0 && n > 0; }
546
547
// --------------------------------------------------------------------------
548
// PRECONDITION:
549
//   IsValidCapacity(capacity)
550
//   ctrl[capacity] == kSentinel
551
//   ctrl[i] != kSentinel for all i < capacity
552
// Applies mapping for every byte in ctrl:
553
//   DELETED -> EMPTY
554
//   EMPTY -> EMPTY
555
//   FULL -> DELETED
556
// --------------------------------------------------------------------------
557
inline void ConvertDeletedToEmptyAndFullToDeleted(
558
    ctrl_t* PHMAP_RESTRICT ctrl, size_t capacity) 
559
0
{
560
0
    assert(ctrl[capacity] == kSentinel);
561
0
    assert(IsValidCapacity(capacity));
562
0
    for (ctrl_t* pos = ctrl; pos != ctrl + capacity + 1; pos += Group::kWidth) {
563
0
        Group{pos}.ConvertSpecialToEmptyAndFullToDeleted(pos);
564
0
    }
565
    // Copy the cloned ctrl bytes.
566
0
    std::memcpy(ctrl + capacity + 1, ctrl, Group::kWidth);
567
0
    ctrl[capacity] = kSentinel;
568
0
}
569
570
// --------------------------------------------------------------------------
571
// Rounds up the capacity to the next power of 2 minus 1, with a minimum of 1.
572
// --------------------------------------------------------------------------
573
inline size_t NormalizeCapacity(size_t n) 
574
0
{
575
0
    return n ? ~size_t{} >> LeadingZeros(n) : 1;
576
0
}
577
578
// --------------------------------------------------------------------------
579
// We use 7/8th as maximum load factor.
580
// For 16-wide groups, that gives an average of two empty slots per group.
581
// --------------------------------------------------------------------------
582
inline size_t CapacityToGrowth(size_t capacity) 
583
6.22k
{
584
6.22k
    assert(IsValidCapacity(capacity));
585
    // `capacity*7/8`
586
6.22k
    PHMAP_IF_CONSTEXPR (Group::kWidth == 8) {
587
6.22k
        if (capacity == 7) {
588
            // x-x/8 does not work when x==7.
589
            return 6;
590
        }
591
    }
592
6.22k
    return capacity - capacity / 8;
593
6.22k
}
594
595
// --------------------------------------------------------------------------
596
// From desired "growth" to a lowerbound of the necessary capacity.
597
// Might not be a valid one and required NormalizeCapacity().
598
// --------------------------------------------------------------------------
599
inline size_t GrowthToLowerboundCapacity(size_t growth) 
600
0
{
601
0
    // `growth*8/7`
602
0
    PHMAP_IF_CONSTEXPR (Group::kWidth == 8) {
603
0
        if (growth == 7) {
604
0
            // x+(x-1)/7 does not work when x==7.
605
0
            return 8;
606
0
        }
607
0
    }
608
0
    return growth + static_cast<size_t>((static_cast<int64_t>(growth) - 1) / 7);
609
0
}
610
611
namespace hashtable_debug_internal {
612
613
// If it is a map, call get<0>().
614
using std::get;
615
template <typename T, typename = typename T::mapped_type>
616
auto GetKey(const typename T::value_type& pair, int) -> decltype(get<0>(pair)) {
617
    return get<0>(pair);
618
}
619
620
// If it is not a map, return the value directly.
621
template <typename T>
622
const typename T::key_type& GetKey(const typename T::key_type& key, char) {
623
    return key;
624
}
625
626
// --------------------------------------------------------------------------
627
// Containers should specialize this to provide debug information for that
628
// container.
629
// --------------------------------------------------------------------------
630
template <class Container, typename Enabler = void>
631
struct HashtableDebugAccess
632
{
633
    // Returns the number of probes required to find `key` in `c`.  The "number of
634
    // probes" is a concept that can vary by container.  Implementations should
635
    // return 0 when `key` was found in the minimum number of operations and
636
    // should increment the result for each non-trivial operation required to find
637
    // `key`.
638
    //
639
    // The default implementation uses the bucket api from the standard and thus
640
    // works for `std::unordered_*` containers.
641
    // --------------------------------------------------------------------------
642
    static size_t GetNumProbes(const Container& c,
643
                               const typename Container::key_type& key) {
644
        if (!c.bucket_count()) return {};
645
        size_t num_probes = 0;
646
        size_t bucket = c.bucket(key);
647
        for (auto it = c.begin(bucket), e = c.end(bucket);; ++it, ++num_probes) {
648
            if (it == e) return num_probes;
649
            if (c.key_eq()(key, GetKey<Container>(*it, 0))) return num_probes;
650
        }
651
    }
652
};
653
654
}  // namespace hashtable_debug_internal
655
656
// ----------------------------------------------------------------------------
657
//                    I N F O Z   S T U B S
658
// ----------------------------------------------------------------------------
659
struct HashtablezInfo 
660
{
661
0
    void PrepareForSampling() {}
662
};
663
664
0
inline void RecordRehashSlow(HashtablezInfo*, size_t ) {}
665
666
0
static inline void RecordInsertSlow(HashtablezInfo* , size_t, size_t ) {}
667
668
0
static inline void RecordEraseSlow(HashtablezInfo*) {}
669
670
0
static inline HashtablezInfo* SampleSlow(int64_t*) { return nullptr; }
671
0
static inline void UnsampleSlow(HashtablezInfo* ) {}
672
673
class HashtablezInfoHandle 
674
{
675
public:
676
3.39k
    inline void RecordStorageChanged(size_t , size_t ) {}
677
0
    inline void RecordRehash(size_t ) {}
678
711k
    inline void RecordInsert(size_t , size_t ) {}
679
0
    inline void RecordErase() {}
680
    friend inline void swap(HashtablezInfoHandle& ,
681
601
                            HashtablezInfoHandle& ) noexcept {}
682
};
683
684
706
static inline HashtablezInfoHandle Sample() { return HashtablezInfoHandle(); }
685
686
class HashtablezSampler 
687
{
688
public:
689
    // Returns a global Sampler.
690
0
    static HashtablezSampler& Global() {  static HashtablezSampler hzs; return hzs; }
691
0
    HashtablezInfo* Register() {  static HashtablezInfo info; return &info; }
692
0
    void Unregister(HashtablezInfo* ) {}
693
694
    using DisposeCallback = void (*)(const HashtablezInfo&);
695
0
    DisposeCallback SetDisposeCallback(DisposeCallback ) { return nullptr; }
696
0
    int64_t Iterate(const std::function<void(const HashtablezInfo& stack)>& ) { return 0; }
697
};
698
699
0
static inline void SetHashtablezEnabled(bool ) {}
700
0
static inline void SetHashtablezSampleParameter(int32_t ) {}
701
0
static inline void SetHashtablezMaxSamples(int32_t ) {}
702
703
704
namespace memory_internal {
705
706
// Constructs T into uninitialized storage pointed by `ptr` using the args
707
// specified in the tuple.
708
// ----------------------------------------------------------------------------
709
template <class Alloc, class T, class Tuple, size_t... I>
710
void ConstructFromTupleImpl(Alloc* alloc, T* ptr, Tuple&& t,
711
                            phmap::index_sequence<I...>) {
712
    phmap::allocator_traits<Alloc>::construct(
713
        *alloc, ptr, std::get<I>(std::forward<Tuple>(t))...);
714
}
715
716
template <class T, class F>
717
struct WithConstructedImplF {
718
    template <class... Args>
719
    decltype(std::declval<F>()(std::declval<T>())) operator()(
720
        Args&&... args) const {
721
        return std::forward<F>(f)(T(std::forward<Args>(args)...));
722
    }
723
    F&& f;
724
};
725
726
template <class T, class Tuple, size_t... Is, class F>
727
decltype(std::declval<F>()(std::declval<T>())) WithConstructedImpl(
728
    Tuple&& t, phmap::index_sequence<Is...>, F&& f) {
729
    return WithConstructedImplF<T, F>{std::forward<F>(f)}(
730
        std::get<Is>(std::forward<Tuple>(t))...);
731
}
732
733
template <class T, size_t... Is>
734
auto TupleRefImpl(T&& t, phmap::index_sequence<Is...>)
735
    -> decltype(std::forward_as_tuple(std::get<Is>(std::forward<T>(t))...)) {
736
  return std::forward_as_tuple(std::get<Is>(std::forward<T>(t))...);
737
}
738
739
// Returns a tuple of references to the elements of the input tuple. T must be a
740
// tuple.
741
// ----------------------------------------------------------------------------
742
template <class T>
743
auto TupleRef(T&& t) -> decltype(
744
    TupleRefImpl(std::forward<T>(t),
745
                 phmap::make_index_sequence<
746
                     std::tuple_size<typename std::decay<T>::type>::value>())) {
747
  return TupleRefImpl(
748
      std::forward<T>(t),
749
      phmap::make_index_sequence<
750
          std::tuple_size<typename std::decay<T>::type>::value>());
751
}
752
753
template <class F, class K, class V>
754
decltype(std::declval<F>()(std::declval<const K&>(), std::piecewise_construct,
755
                           std::declval<std::tuple<K>>(), std::declval<V>()))
756
27.0M
DecomposePairImpl(F&& f, std::pair<std::tuple<K>, V> p) {
757
27.0M
    const auto& key = std::get<0>(p.first);
758
27.0M
    return std::forward<F>(f)(key, std::piecewise_construct, std::move(p.first),
759
27.0M
                              std::move(p.second));
760
27.0M
}
decltype (((std::declval<phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::EmplaceDecomposable>)())((std::declval<unsigned int const&& const&>)(), std::__1::piecewise_construct, (std::declval<std::__1::tuple<unsigned int const&&> >)(), (std::declval<std::__1::tuple<int&&> >)())) phmap::priv::memory_internal::DecomposePairImpl<phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::EmplaceDecomposable, unsigned int const&&, std::__1::tuple<int&&> >(phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::EmplaceDecomposable&&, std::__1::pair<std::__1::tuple<unsigned int const&&>, std::__1::tuple<int&&> >)
Line
Count
Source
756
11.6M
DecomposePairImpl(F&& f, std::pair<std::tuple<K>, V> p) {
757
11.6M
    const auto& key = std::get<0>(p.first);
758
11.6M
    return std::forward<F>(f)(key, std::piecewise_construct, std::move(p.first),
759
11.6M
                              std::move(p.second));
760
11.6M
}
decltype (((std::declval<phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::EqualElement<unsigned int> >)())((std::declval<unsigned int const& const&>)(), std::__1::piecewise_construct, (std::declval<std::__1::tuple<unsigned int const&> >)(), (std::declval<std::__1::tuple<int const&> >)())) phmap::priv::memory_internal::DecomposePairImpl<phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::EqualElement<unsigned int>, unsigned int const&, std::__1::tuple<int const&> >(phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::EqualElement<unsigned int>&&, std::__1::pair<std::__1::tuple<unsigned int const&>, std::__1::tuple<int const&> >)
Line
Count
Source
756
13.4M
DecomposePairImpl(F&& f, std::pair<std::tuple<K>, V> p) {
757
13.4M
    const auto& key = std::get<0>(p.first);
758
13.4M
    return std::forward<F>(f)(key, std::piecewise_construct, std::move(p.first),
759
13.4M
                              std::move(p.second));
760
13.4M
}
decltype (((std::declval<phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::HashElement>)())((std::declval<unsigned int const& const&>)(), std::__1::piecewise_construct, (std::declval<std::__1::tuple<unsigned int const&> >)(), (std::declval<std::__1::tuple<int const&> >)())) phmap::priv::memory_internal::DecomposePairImpl<phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::HashElement, unsigned int const&, std::__1::tuple<int const&> >(phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::HashElement&&, std::__1::pair<std::__1::tuple<unsigned int const&>, std::__1::tuple<int const&> >)
Line
Count
Source
756
1.94M
DecomposePairImpl(F&& f, std::pair<std::tuple<K>, V> p) {
757
1.94M
    const auto& key = std::get<0>(p.first);
758
1.94M
    return std::forward<F>(f)(key, std::piecewise_construct, std::move(p.first),
759
1.94M
                              std::move(p.second));
760
1.94M
}
761
762
}  // namespace memory_internal
763
764
765
// ----------------------------------------------------------------------------
766
//                     R A W _ H A S H _ S E T
767
// ----------------------------------------------------------------------------
768
// An open-addressing
769
// hashtable with quadratic probing.
770
//
771
// This is a low level hashtable on top of which different interfaces can be
772
// implemented, like flat_hash_set, node_hash_set, string_hash_set, etc.
773
//
774
// The table interface is similar to that of std::unordered_set. Notable
775
// differences are that most member functions support heterogeneous keys when
776
// BOTH the hash and eq functions are marked as transparent. They do so by
777
// providing a typedef called `is_transparent`.
778
//
779
// When heterogeneous lookup is enabled, functions that take key_type act as if
780
// they have an overload set like:
781
//
782
//   iterator find(const key_type& key);
783
//   template <class K>
784
//   iterator find(const K& key);
785
//
786
//   size_type erase(const key_type& key);
787
//   template <class K>
788
//   size_type erase(const K& key);
789
//
790
//   std::pair<iterator, iterator> equal_range(const key_type& key);
791
//   template <class K>
792
//   std::pair<iterator, iterator> equal_range(const K& key);
793
//
794
// When heterogeneous lookup is disabled, only the explicit `key_type` overloads
795
// exist.
796
//
797
// find() also supports passing the hash explicitly:
798
//
799
//   iterator find(const key_type& key, size_t hash);
800
//   template <class U>
801
//   iterator find(const U& key, size_t hash);
802
//
803
// In addition the pointer to element and iterator stability guarantees are
804
// weaker: all iterators and pointers are invalidated after a new element is
805
// inserted.
806
//
807
// IMPLEMENTATION DETAILS
808
//
809
// The table stores elements inline in a slot array. In addition to the slot
810
// array the table maintains some control state per slot. The extra state is one
811
// byte per slot and stores empty or deleted marks, or alternatively 7 bits from
812
// the hash of an occupied slot. The table is split into logical groups of
813
// slots, like so:
814
//
815
//      Group 1         Group 2        Group 3
816
// +---------------+---------------+---------------+
817
// | | | | | | | | | | | | | | | | | | | | | | | | |
818
// +---------------+---------------+---------------+
819
//
820
// On lookup the hash is split into two parts:
821
// - H2: 7 bits (those stored in the control bytes)
822
// - H1: the rest of the bits
823
// The groups are probed using H1. For each group the slots are matched to H2 in
824
// parallel. Because H2 is 7 bits (128 states) and the number of slots per group
825
// is low (8 or 16) in almost all cases a match in H2 is also a lookup hit.
826
//
827
// On insert, once the right group is found (as in lookup), its slots are
828
// filled in order.
829
//
830
// On erase a slot is cleared. In case the group did not have any empty slots
831
// before the erase, the erased slot is marked as deleted.
832
//
833
// Groups without empty slots (but maybe with deleted slots) extend the probe
834
// sequence. The probing algorithm is quadratic. Given N the number of groups,
835
// the probing function for the i'th probe is:
836
//
837
//   P(0) = H1 % N
838
//
839
//   P(i) = (P(i - 1) + i) % N
840
//
841
// This probing function guarantees that after N probes, all the groups of the
842
// table will be probed exactly once.
843
// ----------------------------------------------------------------------------
844
template <class Policy, class Hash, class Eq, class Alloc>
845
class raw_hash_set 
846
{
847
    using PolicyTraits = hash_policy_traits<Policy>;
848
    using KeyArgImpl =
849
        KeyArg<IsTransparent<Eq>::value && IsTransparent<Hash>::value>;
850
851
public:
852
    using init_type = typename PolicyTraits::init_type;
853
    using key_type = typename PolicyTraits::key_type;
854
    // TODO(sbenza): Hide slot_type as it is an implementation detail. Needs user
855
    // code fixes!
856
    using slot_type = typename PolicyTraits::slot_type;
857
    using allocator_type = Alloc;
858
    using size_type = size_t;
859
    using difference_type = ptrdiff_t;
860
    using hasher = Hash;
861
    using key_equal = Eq;
862
    using policy_type = Policy;
863
    using value_type = typename PolicyTraits::value_type;
864
    using reference = value_type&;
865
    using const_reference = const value_type&;
866
    using pointer = typename phmap::allocator_traits<
867
        allocator_type>::template rebind_traits<value_type>::pointer;
868
    using const_pointer = typename phmap::allocator_traits<
869
        allocator_type>::template rebind_traits<value_type>::const_pointer;
870
871
    // Alias used for heterogeneous lookup functions.
872
    // `key_arg<K>` evaluates to `K` when the functors are transparent and to
873
    // `key_type` otherwise. It permits template argument deduction on `K` for the
874
    // transparent case.
875
    template <class K>
876
    using key_arg = typename KeyArgImpl::template type<K, key_type>;
877
878
    using std_alloc_t = std::is_same<typename std::decay<Alloc>::type, phmap::priv::Allocator<value_type>>;
879
880
private:
881
    // Give an early error when key_type is not hashable/eq.
882
    auto KeyTypeCanBeHashed(const Hash& h, const key_type& k) -> decltype(h(k));
883
    auto KeyTypeCanBeEq(const Eq& eq, const key_type& k) -> decltype(eq(k, k));
884
885
    using Layout = phmap::priv::Layout<ctrl_t, slot_type>;
886
887
6.79k
    static Layout MakeLayout(size_t capacity) {
888
6.79k
        assert(IsValidCapacity(capacity));
889
6.79k
        return Layout(capacity + Group::kWidth + 1, capacity);
890
6.79k
    }
phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::MakeLayout(unsigned long)
Line
Count
Source
887
6.79k
    static Layout MakeLayout(size_t capacity) {
888
6.79k
        assert(IsValidCapacity(capacity));
889
6.79k
        return Layout(capacity + Group::kWidth + 1, capacity);
890
6.79k
    }
Unexecuted instantiation: phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, phmap::priv::StringHashEqT<char>::Hash, phmap::priv::StringHashEqT<char>::Eq, std::__1::allocator<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > >::MakeLayout(unsigned long)
891
892
    using AllocTraits = phmap::allocator_traits<allocator_type>;
893
    using SlotAlloc = typename phmap::allocator_traits<
894
        allocator_type>::template rebind_alloc<slot_type>;
895
    using SlotAllocTraits = typename phmap::allocator_traits<
896
        allocator_type>::template rebind_traits<slot_type>;
897
898
    static_assert(std::is_lvalue_reference<reference>::value,
899
                  "Policy::element() must return a reference");
900
901
    template <typename T>
902
    struct SameAsElementReference
903
        : std::is_same<typename std::remove_cv<
904
                           typename std::remove_reference<reference>::type>::type,
905
                       typename std::remove_cv<
906
                           typename std::remove_reference<T>::type>::type> {};
907
908
    // An enabler for insert(T&&): T must be convertible to init_type or be the
909
    // same as [cv] value_type [ref].
910
    // Note: we separate SameAsElementReference into its own type to avoid using
911
    // reference unless we need to. MSVC doesn't seem to like it in some
912
    // cases.
913
    template <class T>
914
    using RequiresInsertable = typename std::enable_if<
915
        phmap::disjunction<std::is_convertible<T, init_type>,
916
                           SameAsElementReference<T>>::value,
917
        int>::type;
918
919
    // RequiresNotInit is a workaround for gcc prior to 7.1.
920
    // See https://godbolt.org/g/Y4xsUh.
921
    template <class T>
922
    using RequiresNotInit =
923
        typename std::enable_if<!std::is_same<T, init_type>::value, int>::type;
924
925
    template <class... Ts>
926
    using IsDecomposable = IsDecomposable<void, PolicyTraits, Hash, Eq, Ts...>;
927
928
public:
929
    class iterator
930
    {
931
        friend class raw_hash_set;
932
933
    public:
934
        using iterator_category = std::forward_iterator_tag;
935
        using value_type = typename raw_hash_set::value_type;
936
        using reference =
937
            phmap::conditional_t<PolicyTraits::constant_iterators::value,
938
                                 const value_type&, value_type&>;
939
        using pointer = phmap::remove_reference_t<reference>*;
940
        using difference_type = typename raw_hash_set::difference_type;
941
942
        iterator() {}
943
944
        // PRECONDITION: not an end() iterator.
945
694k
        reference operator*() const { return PolicyTraits::element(slot_); }
phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::iterator::operator*() const
Line
Count
Source
945
694k
        reference operator*() const { return PolicyTraits::element(slot_); }
Unexecuted instantiation: phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, phmap::priv::StringHashEqT<char>::Hash, phmap::priv::StringHashEqT<char>::Eq, std::__1::allocator<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > >::iterator::operator*() const
946
947
        // PRECONDITION: not an end() iterator.
948
        pointer operator->() const { return &operator*(); }
949
950
        // PRECONDITION: not an end() iterator.
951
694k
        iterator& operator++() {
952
694k
            ++ctrl_;
953
694k
            ++slot_;
954
694k
            skip_empty_or_deleted();
955
694k
            return *this;
956
694k
        }
phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::iterator::operator++()
Line
Count
Source
951
694k
        iterator& operator++() {
952
694k
            ++ctrl_;
953
694k
            ++slot_;
954
694k
            skip_empty_or_deleted();
955
694k
            return *this;
956
694k
        }
Unexecuted instantiation: phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, phmap::priv::StringHashEqT<char>::Hash, phmap::priv::StringHashEqT<char>::Eq, std::__1::allocator<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > >::iterator::operator++()
957
        // PRECONDITION: not an end() iterator.
958
        iterator operator++(int) {
959
            auto tmp = *this;
960
            ++*this;
961
            return tmp;
962
        }
963
964
#if 0 // PHMAP_BIDIRECTIONAL
965
        // PRECONDITION: not a begin() iterator.
966
        iterator& operator--() {
967
            assert(ctrl_);
968
            do {
969
                --ctrl_;
970
                --slot_;
971
            } while (IsEmptyOrDeleted(*ctrl_));
972
            return *this;
973
        }
974
975
        // PRECONDITION: not a begin() iterator.
976
        iterator operator--(int) {
977
            auto tmp = *this;
978
            --*this;
979
            return tmp;
980
        }
981
#endif
982
983
695k
        friend bool operator==(const iterator& a, const iterator& b) {
984
695k
            return a.ctrl_ == b.ctrl_;
985
695k
        }
phmap::priv::operator==(phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::iterator const&, phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::iterator const&)
Line
Count
Source
983
694k
        friend bool operator==(const iterator& a, const iterator& b) {
984
694k
            return a.ctrl_ == b.ctrl_;
985
694k
        }
phmap::priv::operator==(phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, phmap::priv::StringHashEqT<char>::Hash, phmap::priv::StringHashEqT<char>::Eq, std::__1::allocator<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > >::iterator const&, phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, phmap::priv::StringHashEqT<char>::Hash, phmap::priv::StringHashEqT<char>::Eq, std::__1::allocator<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > >::iterator const&)
Line
Count
Source
983
601
        friend bool operator==(const iterator& a, const iterator& b) {
984
601
            return a.ctrl_ == b.ctrl_;
985
601
        }
986
601
        friend bool operator!=(const iterator& a, const iterator& b) {
987
601
            return !(a == b);
988
601
        }
989
990
    private:
991
1.40k
        iterator(ctrl_t* ctrl) : ctrl_(ctrl) {}  // for end()
phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::iterator::iterator(signed char*)
Line
Count
Source
991
207
        iterator(ctrl_t* ctrl) : ctrl_(ctrl) {}  // for end()
phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, phmap::priv::StringHashEqT<char>::Hash, phmap::priv::StringHashEqT<char>::Eq, std::__1::allocator<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > >::iterator::iterator(signed char*)
Line
Count
Source
991
1.20k
        iterator(ctrl_t* ctrl) : ctrl_(ctrl) {}  // for end()
992
11.6M
        iterator(ctrl_t* ctrl, slot_type* slot) : ctrl_(ctrl), slot_(slot) {}
phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::iterator::iterator(signed char*, phmap::priv::map_slot_type<unsigned int, int>*)
Line
Count
Source
992
11.6M
        iterator(ctrl_t* ctrl, slot_type* slot) : ctrl_(ctrl), slot_(slot) {}
Unexecuted instantiation: phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, phmap::priv::StringHashEqT<char>::Hash, phmap::priv::StringHashEqT<char>::Eq, std::__1::allocator<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > >::iterator::iterator(signed char*, phmap::priv::map_slot_type<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >*)
993
994
694k
        void skip_empty_or_deleted() {
995
694k
            PHMAP_IF_CONSTEXPR (!std_alloc_t::value) {
996
                // ctrl_ could be nullptr
997
                if (!ctrl_)
998
                    return;
999
            }
1000
963k
            while (IsEmptyOrDeleted(*ctrl_)) {
1001
                // ctrl is not necessarily aligned to Group::kWidth. It is also likely
1002
                // to read past the space for ctrl bytes and into slots. This is ok
1003
                // because ctrl has sizeof() == 1 and slot has sizeof() >= 1 so there
1004
                // is no way to read outside the combined slot array.
1005
268k
                uint32_t shift = Group{ctrl_}.CountLeadingEmptyOrDeleted();
1006
268k
                ctrl_ += shift;
1007
268k
                slot_ += shift;
1008
268k
            }
1009
694k
        }
phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::iterator::skip_empty_or_deleted()
Line
Count
Source
994
694k
        void skip_empty_or_deleted() {
995
694k
            PHMAP_IF_CONSTEXPR (!std_alloc_t::value) {
996
                // ctrl_ could be nullptr
997
                if (!ctrl_)
998
                    return;
999
            }
1000
963k
            while (IsEmptyOrDeleted(*ctrl_)) {
1001
                // ctrl is not necessarily aligned to Group::kWidth. It is also likely
1002
                // to read past the space for ctrl bytes and into slots. This is ok
1003
                // because ctrl has sizeof() == 1 and slot has sizeof() >= 1 so there
1004
                // is no way to read outside the combined slot array.
1005
268k
                uint32_t shift = Group{ctrl_}.CountLeadingEmptyOrDeleted();
1006
268k
                ctrl_ += shift;
1007
268k
                slot_ += shift;
1008
268k
            }
1009
694k
        }
Unexecuted instantiation: phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, phmap::priv::StringHashEqT<char>::Hash, phmap::priv::StringHashEqT<char>::Eq, std::__1::allocator<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > >::iterator::skip_empty_or_deleted()
1010
1011
        ctrl_t* ctrl_ = nullptr;
1012
        // To avoid uninitialized member warnings, put slot_ in an anonymous union.
1013
        // The member is not initialized on singleton and end iterators.
1014
        union {
1015
            slot_type* slot_;
1016
        };
1017
    };
1018
1019
    class const_iterator 
1020
    {
1021
        friend class raw_hash_set;
1022
1023
    public:
1024
        using iterator_category = typename iterator::iterator_category;
1025
        using value_type = typename raw_hash_set::value_type;
1026
        using reference = typename raw_hash_set::const_reference;
1027
        using pointer = typename raw_hash_set::const_pointer;
1028
        using difference_type = typename raw_hash_set::difference_type;
1029
1030
        const_iterator() {}
1031
        // Implicit construction from iterator.
1032
346
        const_iterator(iterator i) : inner_(std::move(i)) {}
1033
1034
694k
        reference operator*() const { return *inner_; }
1035
        pointer operator->() const { return inner_.operator->(); }
1036
1037
694k
        const_iterator& operator++() {
1038
694k
            ++inner_;
1039
694k
            return *this;
1040
694k
        }
1041
        const_iterator operator++(int) { return inner_++; }
1042
1043
694k
        friend bool operator==(const const_iterator& a, const const_iterator& b) {
1044
694k
            return a.inner_ == b.inner_;
1045
694k
        }
1046
694k
        friend bool operator!=(const const_iterator& a, const const_iterator& b) {
1047
694k
            return !(a == b);
1048
694k
        }
1049
1050
    private:
1051
        const_iterator(const ctrl_t* ctrl, const slot_type* slot)
1052
            : inner_(const_cast<ctrl_t*>(ctrl), const_cast<slot_type*>(slot)) {}
1053
1054
        iterator inner_;
1055
    };
1056
1057
    using node_type = node_handle<Policy, hash_policy_traits<Policy>, Alloc>;
1058
    using insert_return_type = InsertReturnType<iterator, node_type>;
1059
1060
    raw_hash_set() noexcept(
1061
        std::is_nothrow_default_constructible<hasher>::value&&
1062
        std::is_nothrow_default_constructible<key_equal>::value&&
1063
2.40k
        std::is_nothrow_default_constructible<allocator_type>::value) {}
phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::raw_hash_set()
Line
Count
Source
1063
1.80k
        std::is_nothrow_default_constructible<allocator_type>::value) {}
phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, phmap::priv::StringHashEqT<char>::Hash, phmap::priv::StringHashEqT<char>::Eq, std::__1::allocator<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > >::raw_hash_set()
Line
Count
Source
1063
601
        std::is_nothrow_default_constructible<allocator_type>::value) {}
1064
1065
    explicit raw_hash_set(size_t bucket_cnt, const hasher& hashfn = hasher(),
1066
                          const key_equal& eq = key_equal(),
1067
                          const allocator_type& alloc = allocator_type())
1068
        : ctrl_(EmptyGroup<std_alloc_t>()), settings_(0, hashfn, eq, alloc) {
1069
        if (bucket_cnt) {
1070
            size_t new_capacity = NormalizeCapacity(bucket_cnt);
1071
            reset_growth_left(new_capacity);
1072
            initialize_slots(new_capacity);
1073
            capacity_ = new_capacity;
1074
        }
1075
    }
1076
1077
    raw_hash_set(size_t bucket_cnt, const hasher& hashfn,
1078
                 const allocator_type& alloc)
1079
        : raw_hash_set(bucket_cnt, hashfn, key_equal(), alloc) {}
1080
1081
    raw_hash_set(size_t bucket_cnt, const allocator_type& alloc)
1082
        : raw_hash_set(bucket_cnt, hasher(), key_equal(), alloc) {}
1083
1084
    explicit raw_hash_set(const allocator_type& alloc)
1085
        : raw_hash_set(0, hasher(), key_equal(), alloc) {}
1086
1087
    template <class InputIter>
1088
    raw_hash_set(InputIter first, InputIter last, size_t bucket_cnt = 0,
1089
                 const hasher& hashfn = hasher(), const key_equal& eq = key_equal(),
1090
                 const allocator_type& alloc = allocator_type())
1091
        : raw_hash_set(bucket_cnt, hashfn, eq, alloc) {
1092
        insert(first, last);
1093
    }
1094
1095
    template <class InputIter>
1096
    raw_hash_set(InputIter first, InputIter last, size_t bucket_cnt,
1097
                 const hasher& hashfn, const allocator_type& alloc)
1098
        : raw_hash_set(first, last, bucket_cnt, hashfn, key_equal(), alloc) {}
1099
1100
    template <class InputIter>
1101
    raw_hash_set(InputIter first, InputIter last, size_t bucket_cnt,
1102
                 const allocator_type& alloc)
1103
        : raw_hash_set(first, last, bucket_cnt, hasher(), key_equal(), alloc) {}
1104
1105
    template <class InputIter>
1106
    raw_hash_set(InputIter first, InputIter last, const allocator_type& alloc)
1107
        : raw_hash_set(first, last, 0, hasher(), key_equal(), alloc) {}
1108
1109
    // Instead of accepting std::initializer_list<value_type> as the first
1110
    // argument like std::unordered_set<value_type> does, we have two overloads
1111
    // that accept std::initializer_list<T> and std::initializer_list<init_type>.
1112
    // This is advantageous for performance.
1113
    //
1114
    //   // Turns {"abc", "def"} into std::initializer_list<std::string>, then
1115
    //   // copies the strings into the set.
1116
    //   std::unordered_set<std::string> s = {"abc", "def"};
1117
    //
1118
    //   // Turns {"abc", "def"} into std::initializer_list<const char*>, then
1119
    //   // copies the strings into the set.
1120
    //   phmap::flat_hash_set<std::string> s = {"abc", "def"};
1121
    //
1122
    // The same trick is used in insert().
1123
    //
1124
    // The enabler is necessary to prevent this constructor from triggering where
1125
    // the copy constructor is meant to be called.
1126
    //
1127
    //   phmap::flat_hash_set<int> a, b{a};
1128
    //
1129
    // RequiresNotInit<T> is a workaround for gcc prior to 7.1.
1130
    template <class T, RequiresNotInit<T> = 0, RequiresInsertable<T> = 0>
1131
    raw_hash_set(std::initializer_list<T> init, size_t bucket_cnt = 0,
1132
                 const hasher& hashfn = hasher(), const key_equal& eq = key_equal(),
1133
                 const allocator_type& alloc = allocator_type())
1134
        : raw_hash_set(init.begin(), init.end(), bucket_cnt, hashfn, eq, alloc) {}
1135
1136
    raw_hash_set(std::initializer_list<init_type> init, size_t bucket_cnt = 0,
1137
                 const hasher& hashfn = hasher(), const key_equal& eq = key_equal(),
1138
                 const allocator_type& alloc = allocator_type())
1139
        : raw_hash_set(init.begin(), init.end(), bucket_cnt, hashfn, eq, alloc) {}
1140
1141
    template <class T, RequiresNotInit<T> = 0, RequiresInsertable<T> = 0>
1142
    raw_hash_set(std::initializer_list<T> init, size_t bucket_cnt,
1143
                 const hasher& hashfn, const allocator_type& alloc)
1144
        : raw_hash_set(init, bucket_cnt, hashfn, key_equal(), alloc) {}
1145
1146
    raw_hash_set(std::initializer_list<init_type> init, size_t bucket_cnt,
1147
                 const hasher& hashfn, const allocator_type& alloc)
1148
        : raw_hash_set(init, bucket_cnt, hashfn, key_equal(), alloc) {}
1149
1150
    template <class T, RequiresNotInit<T> = 0, RequiresInsertable<T> = 0>
1151
    raw_hash_set(std::initializer_list<T> init, size_t bucket_cnt,
1152
                 const allocator_type& alloc)
1153
        : raw_hash_set(init, bucket_cnt, hasher(), key_equal(), alloc) {}
1154
1155
    raw_hash_set(std::initializer_list<init_type> init, size_t bucket_cnt,
1156
                 const allocator_type& alloc)
1157
        : raw_hash_set(init, bucket_cnt, hasher(), key_equal(), alloc) {}
1158
1159
    template <class T, RequiresNotInit<T> = 0, RequiresInsertable<T> = 0>
1160
    raw_hash_set(std::initializer_list<T> init, const allocator_type& alloc)
1161
        : raw_hash_set(init, 0, hasher(), key_equal(), alloc) {}
1162
1163
    raw_hash_set(std::initializer_list<init_type> init,
1164
                 const allocator_type& alloc)
1165
        : raw_hash_set(init, 0, hasher(), key_equal(), alloc) {}
1166
1167
    raw_hash_set(const raw_hash_set& that)
1168
        : raw_hash_set(that, AllocTraits::select_on_container_copy_construction(
1169
                           that.alloc_ref())) {}
1170
1171
    raw_hash_set(const raw_hash_set& that, const allocator_type& a)
1172
        : raw_hash_set(0, that.hash_ref(), that.eq_ref(), a) {
1173
        rehash(that.capacity());   // operator=() should preserve load_factor
1174
        // Because the table is guaranteed to be empty, we can do something faster
1175
        // than a full `insert`.
1176
        for (const auto& v : that) {
1177
            const size_t hashval = PolicyTraits::apply(HashElement{hash_ref()}, v);
1178
            auto target = find_first_non_full(hashval);
1179
            set_ctrl(target.offset, H2(hashval));
1180
            emplace_at(target.offset, v);
1181
            infoz_.RecordInsert(hashval, target.probe_length);
1182
        }
1183
        size_ = that.size();
1184
        growth_left() -= that.size();
1185
    }
1186
1187
    raw_hash_set(raw_hash_set&& that) noexcept(
1188
        std::is_nothrow_copy_constructible<hasher>::value&&
1189
        std::is_nothrow_copy_constructible<key_equal>::value&&
1190
        std::is_nothrow_copy_constructible<allocator_type>::value)
1191
        : ctrl_(phmap::exchange(that.ctrl_, EmptyGroup<std_alloc_t>())),
1192
        slots_(phmap::exchange(that.slots_, nullptr)),
1193
        size_(phmap::exchange(that.size_, 0)),
1194
        capacity_(phmap::exchange(that.capacity_, 0)),
1195
        infoz_(phmap::exchange(that.infoz_, HashtablezInfoHandle())),
1196
        // Hash, equality and allocator are copied instead of moved because
1197
        // `that` must be left valid. If Hash is std::function<Key>, moving it
1198
        // would create a nullptr functor that cannot be called.
1199
        settings_(std::move(that.settings_)) {
1200
        // growth_left was copied above, reset the one from `that`.
1201
        that.growth_left() = 0;
1202
    }
1203
1204
    raw_hash_set(raw_hash_set&& that, const allocator_type& a)
1205
        : ctrl_(EmptyGroup<std_alloc_t>()),
1206
          slots_(nullptr),
1207
          size_(0),
1208
          capacity_(0),
1209
          settings_(0, that.hash_ref(), that.eq_ref(), a) {
1210
        if (a == that.alloc_ref()) {
1211
            std::swap(ctrl_, that.ctrl_);
1212
            std::swap(slots_, that.slots_);
1213
            std::swap(size_, that.size_);
1214
            std::swap(capacity_, that.capacity_);
1215
            std::swap(growth_left(), that.growth_left());
1216
            std::swap(infoz_, that.infoz_);
1217
        } else {
1218
            reserve(that.size());
1219
            // Note: this will copy elements of dense_set and unordered_set instead of
1220
            // moving them. This can be fixed if it ever becomes an issue.
1221
            for (auto& elem : that) insert(std::move(elem));
1222
        }
1223
    }
1224
1225
    raw_hash_set& operator=(const raw_hash_set& that) {
1226
        raw_hash_set tmp(that,
1227
                         AllocTraits::propagate_on_container_copy_assignment::value
1228
                         ? that.alloc_ref()
1229
                         : alloc_ref());
1230
        swap(tmp);
1231
        return *this;
1232
    }
1233
1234
    raw_hash_set& operator=(raw_hash_set&& that) noexcept(
1235
        phmap::allocator_traits<allocator_type>::is_always_equal::value&&
1236
        std::is_nothrow_move_assignable<hasher>::value&&
1237
        std::is_nothrow_move_assignable<key_equal>::value) {
1238
        // TODO(sbenza): We should only use the operations from the noexcept clause
1239
        // to make sure we actually adhere to that contract.
1240
        return move_assign(
1241
            std::move(that),
1242
            typename AllocTraits::propagate_on_container_move_assignment());
1243
    }
1244
1245
2.40k
    ~raw_hash_set() { destroy_slots(); }
phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::~raw_hash_set()
Line
Count
Source
1245
1.80k
    ~raw_hash_set() { destroy_slots(); }
phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, phmap::priv::StringHashEqT<char>::Hash, phmap::priv::StringHashEqT<char>::Eq, std::__1::allocator<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > >::~raw_hash_set()
Line
Count
Source
1245
601
    ~raw_hash_set() { destroy_slots(); }
1246
1247
774
    iterator begin() {
1248
774
        if (empty()) return end();
1249
139
        auto it = iterator_at(0);
1250
139
        it.skip_empty_or_deleted();
1251
139
        return it;
1252
774
    }
phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::begin()
Line
Count
Source
1247
173
    iterator begin() {
1248
173
        if (empty()) return end();
1249
139
        auto it = iterator_at(0);
1250
139
        it.skip_empty_or_deleted();
1251
139
        return it;
1252
173
    }
phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, phmap::priv::StringHashEqT<char>::Hash, phmap::priv::StringHashEqT<char>::Eq, std::__1::allocator<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > >::begin()
Line
Count
Source
1247
601
    iterator begin() {
1248
601
        if (empty()) return end();
1249
0
        auto it = iterator_at(0);
1250
0
        it.skip_empty_or_deleted();
1251
0
        return it;
1252
601
    }
1253
    iterator end() 
1254
1.40k
    {
1255
#if 0 // PHMAP_BIDIRECTIONAL
1256
        return iterator_at(capacity_); 
1257
#else
1258
1.40k
        return {ctrl_ + capacity_};
1259
1.40k
#endif
1260
1.40k
    }
phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::end()
Line
Count
Source
1254
207
    {
1255
#if 0 // PHMAP_BIDIRECTIONAL
1256
        return iterator_at(capacity_); 
1257
#else
1258
207
        return {ctrl_ + capacity_};
1259
207
#endif
1260
207
    }
phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, phmap::priv::StringHashEqT<char>::Hash, phmap::priv::StringHashEqT<char>::Eq, std::__1::allocator<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > >::end()
Line
Count
Source
1254
1.20k
    {
1255
#if 0 // PHMAP_BIDIRECTIONAL
1256
        return iterator_at(capacity_); 
1257
#else
1258
1.20k
        return {ctrl_ + capacity_};
1259
1.20k
#endif
1260
1.20k
    }
1261
1262
173
    const_iterator begin() const {
1263
173
        return const_cast<raw_hash_set*>(this)->begin();
1264
173
    }
1265
173
    const_iterator end() const { return const_cast<raw_hash_set*>(this)->end(); }
1266
    const_iterator cbegin() const { return begin(); }
1267
    const_iterator cend() const { return end(); }
1268
1269
774
    bool empty() const { return !size(); }
phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::empty() const
Line
Count
Source
1269
173
    bool empty() const { return !size(); }
phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, phmap::priv::StringHashEqT<char>::Hash, phmap::priv::StringHashEqT<char>::Eq, std::__1::allocator<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > >::empty() const
Line
Count
Source
1269
601
    bool empty() const { return !size(); }
1270
4.66k
    size_t size() const { return size_; }
phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::size() const
Line
Count
Source
1270
4.06k
    size_t size() const { return size_; }
phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, phmap::priv::StringHashEqT<char>::Hash, phmap::priv::StringHashEqT<char>::Eq, std::__1::allocator<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > >::size() const
Line
Count
Source
1270
601
    size_t size() const { return size_; }
1271
3.03k
    size_t capacity() const { return capacity_; }
1272
    size_t max_size() const { return (std::numeric_limits<size_t>::max)(); }
1273
1274
    PHMAP_ATTRIBUTE_REINITIALIZES void clear() {
1275
        if (empty())
1276
            return;
1277
        if (capacity_) {
1278
           PHMAP_IF_CONSTEXPR((!std::is_trivially_destructible<typename PolicyTraits::value_type>::value ||
1279
                               std::is_same<typename Policy::is_flat, std::false_type>::value)) {
1280
                // node map or not trivially destructible... we  need to iterate and destroy values one by one
1281
                for (size_t i = 0; i != capacity_; ++i) {
1282
                    if (IsFull(ctrl_[i])) {
1283
                        PolicyTraits::destroy(&alloc_ref(), slots_ + i);
1284
                    }
1285
                }
1286
            }
1287
            size_ = 0;
1288
            reset_ctrl(capacity_);
1289
            reset_growth_left(capacity_);
1290
        }
1291
        assert(empty());
1292
        infoz_.RecordStorageChanged(0, capacity_);
1293
    }
1294
1295
    // This overload kicks in when the argument is an rvalue of insertable and
1296
    // decomposable type other than init_type.
1297
    //
1298
    //   flat_hash_map<std::string, int> m;
1299
    //   m.insert(std::make_pair("abc", 42));
1300
    template <class T, RequiresInsertable<T> = 0,
1301
              typename std::enable_if<IsDecomposable<T>::value, int>::type = 0,
1302
              T* = nullptr>
1303
11.6M
    std::pair<iterator, bool> insert(T&& value) {
1304
11.6M
        return emplace(std::forward<T>(value));
1305
11.6M
    }
1306
1307
    // This overload kicks in when the argument is a bitfield or an lvalue of
1308
    // insertable and decomposable type.
1309
    //
1310
    //   union { int n : 1; };
1311
    //   flat_hash_set<int> s;
1312
    //   s.insert(n);
1313
    //
1314
    //   flat_hash_set<std::string> s;
1315
    //   const char* p = "hello";
1316
    //   s.insert(p);
1317
    //
1318
    // TODO(romanp): Once we stop supporting gcc 5.1 and below, replace
1319
    // RequiresInsertable<T> with RequiresInsertable<const T&>.
1320
    // We are hitting this bug: https://godbolt.org/g/1Vht4f.
1321
    template <class T, RequiresInsertable<T> = 0,
1322
              typename std::enable_if<IsDecomposable<const T&>::value, int>::type = 0>
1323
    std::pair<iterator, bool> insert(const T& value) {
1324
        return emplace(value);
1325
    }
1326
1327
    // This overload kicks in when the argument is an rvalue of init_type. Its
1328
    // purpose is to handle brace-init-list arguments.
1329
    //
1330
    //   flat_hash_set<std::string, int> s;
1331
    //   s.insert({"abc", 42});
1332
    std::pair<iterator, bool> insert(init_type&& value) {
1333
        return emplace(std::move(value));
1334
    }
1335
1336
    template <class T, RequiresInsertable<T> = 0,
1337
              typename std::enable_if<IsDecomposable<T>::value, int>::type = 0,
1338
              T* = nullptr>
1339
    iterator insert(const_iterator, T&& value) {
1340
        return insert(std::forward<T>(value)).first;
1341
    }
1342
1343
    // TODO(romanp): Once we stop supporting gcc 5.1 and below, replace
1344
    // RequiresInsertable<T> with RequiresInsertable<const T&>.
1345
    // We are hitting this bug: https://godbolt.org/g/1Vht4f.
1346
    template <class T, RequiresInsertable<T> = 0,
1347
              typename std::enable_if<IsDecomposable<const T&>::value, int>::type = 0>
1348
    iterator insert(const_iterator, const T& value) {
1349
        return insert(value).first;
1350
    }
1351
1352
    iterator insert(const_iterator, init_type&& value) {
1353
        return insert(std::move(value)).first;
1354
    }
1355
1356
    template <typename It>
1357
    using IsRandomAccess = std::is_same<typename std::iterator_traits<It>::iterator_category,
1358
                                        std::random_access_iterator_tag>;
1359
1360
1361
    template<typename T>
1362
    struct has_difference_operator
1363
    {
1364
    private:
1365
        using yes = std::true_type;
1366
        using no  = std::false_type;
1367
 
1368
        template<typename U> static auto test(int) -> decltype(std::declval<U>() - std::declval<U>() == 1, yes());
1369
        template<typename>   static no   test(...);
1370
 
1371
    public:
1372
        static constexpr bool value = std::is_same<decltype(test<T>(0)), yes>::value;
1373
    };
1374
1375
    template <class InputIt, typename phmap::enable_if_t<has_difference_operator<InputIt>::value, int> = 0>
1376
    void insert(InputIt first, InputIt last) {
1377
        this->reserve(this->size() + (last - first));
1378
        for (; first != last; ++first) 
1379
            emplace(*first);
1380
    }
1381
1382
    template <class InputIt, typename phmap::enable_if_t<!has_difference_operator<InputIt>::value, int> = 0>
1383
    void insert(InputIt first, InputIt last) {
1384
        for (; first != last; ++first) 
1385
            emplace(*first);
1386
    }
1387
1388
    template <class T, RequiresNotInit<T> = 0, RequiresInsertable<const T&> = 0>
1389
    void insert(std::initializer_list<T> ilist) {
1390
        insert(ilist.begin(), ilist.end());
1391
    }
1392
1393
    void insert(std::initializer_list<init_type> ilist) {
1394
        insert(ilist.begin(), ilist.end());
1395
    }
1396
1397
    insert_return_type insert(node_type&& node) {
1398
        if (!node) return {end(), false, node_type()};
1399
        const auto& elem = PolicyTraits::element(CommonAccess::GetSlot(node));
1400
        auto res = PolicyTraits::apply(
1401
            InsertSlot<false>{*this, std::move(*CommonAccess::GetSlot(node))},
1402
            elem);
1403
        if (res.second) {
1404
            CommonAccess::Reset(&node);
1405
            return {res.first, true, node_type()};
1406
        } else {
1407
            return {res.first, false, std::move(node)};
1408
        }
1409
    }
1410
1411
    insert_return_type insert(node_type&& node, size_t hashval) {
1412
        if (!node) return {end(), false, node_type()};
1413
        const auto& elem = PolicyTraits::element(CommonAccess::GetSlot(node));
1414
        auto res = PolicyTraits::apply(
1415
            InsertSlotWithHash<false>{*this, std::move(*CommonAccess::GetSlot(node)), hashval},
1416
            elem);
1417
        if (res.second) {
1418
            CommonAccess::Reset(&node);
1419
            return {res.first, true, node_type()};
1420
        } else {
1421
            return {res.first, false, std::move(node)};
1422
        }
1423
    }
1424
1425
    iterator insert(const_iterator, node_type&& node) {
1426
        auto res = insert(std::move(node));
1427
        node = std::move(res.node);
1428
        return res.position;
1429
    }
1430
1431
    // This overload kicks in if we can deduce the key from args. This enables us
1432
    // to avoid constructing value_type if an entry with the same key already
1433
    // exists.
1434
    //
1435
    // For example:
1436
    //
1437
    //   flat_hash_map<std::string, std::string> m = {{"abc", "def"}};
1438
    //   // Creates no std::string copies and makes no heap allocations.
1439
    //   m.emplace("abc", "xyz");
1440
    template <class... Args, typename std::enable_if<
1441
                                 IsDecomposable<Args...>::value, int>::type = 0>
1442
11.6M
    std::pair<iterator, bool> emplace(Args&&... args) {
1443
11.6M
        return PolicyTraits::apply(EmplaceDecomposable{*this},
1444
11.6M
                                   std::forward<Args>(args)...);
1445
11.6M
    }
1446
1447
    template <class... Args, typename std::enable_if<IsDecomposable<Args...>::value, int>::type = 0>
1448
    std::pair<iterator, bool> emplace_with_hash(size_t hashval, Args&&... args) {
1449
        return PolicyTraits::apply(EmplaceDecomposableHashval{*this, hashval}, std::forward<Args>(args)...);
1450
    }
1451
1452
    // This overload kicks in if we cannot deduce the key from args. It constructs
1453
    // value_type unconditionally and then either moves it into the table or
1454
    // destroys.
1455
    template <class... Args, typename std::enable_if<!IsDecomposable<Args...>::value, int>::type = 0>
1456
    std::pair<iterator, bool> emplace(Args&&... args) {
1457
        typename phmap::aligned_storage<sizeof(slot_type), alignof(slot_type)>::type
1458
            raw;
1459
        slot_type* slot = reinterpret_cast<slot_type*>(&raw);
1460
1461
        PolicyTraits::construct(&alloc_ref(), slot, std::forward<Args>(args)...);
1462
        const auto& elem = PolicyTraits::element(slot);
1463
        return PolicyTraits::apply(InsertSlot<true>{*this, std::move(*slot)}, elem);
1464
    }
1465
1466
    template <class... Args, typename std::enable_if<!IsDecomposable<Args...>::value, int>::type = 0>
1467
    std::pair<iterator, bool> emplace_with_hash(size_t hashval, Args&&... args) {
1468
        typename phmap::aligned_storage<sizeof(slot_type), alignof(slot_type)>::type raw;
1469
        slot_type* slot = reinterpret_cast<slot_type*>(&raw);
1470
1471
        PolicyTraits::construct(&alloc_ref(), slot, std::forward<Args>(args)...);
1472
        const auto& elem = PolicyTraits::element(slot);
1473
        return PolicyTraits::apply(InsertSlotWithHash<true>{*this, std::move(*slot), hashval}, elem);
1474
    }
1475
1476
    template <class... Args>
1477
    iterator emplace_hint(const_iterator, Args&&... args) {
1478
        return emplace(std::forward<Args>(args)...).first;
1479
    }
1480
1481
    template <class... Args>
1482
    iterator emplace_hint_with_hash(size_t hashval, const_iterator, Args&&... args) {
1483
        return emplace_with_hash(hashval, std::forward<Args>(args)...).first;
1484
    }
1485
1486
    // Extension API: support for lazy emplace.
1487
    //
1488
    // Looks up key in the table. If found, returns the iterator to the element.
1489
    // Otherwise calls f with one argument of type raw_hash_set::constructor. f
1490
    // MUST call raw_hash_set::constructor with arguments as if a
1491
    // raw_hash_set::value_type is constructed, otherwise the behavior is
1492
    // undefined.
1493
    //
1494
    // For example:
1495
    //
1496
    //   std::unordered_set<ArenaString> s;
1497
    //   // Makes ArenaStr even if "abc" is in the map.
1498
    //   s.insert(ArenaString(&arena, "abc"));
1499
    //
1500
    //   flat_hash_set<ArenaStr> s;
1501
    //   // Makes ArenaStr only if "abc" is not in the map.
1502
    //   s.lazy_emplace("abc", [&](const constructor& ctor) {
1503
    //     ctor(&arena, "abc");
1504
    //   });
1505
    //
1506
    // WARNING: This API is currently experimental. If there is a way to implement
1507
    // the same thing with the rest of the API, prefer that.
1508
    class constructor 
1509
    {
1510
        friend class raw_hash_set;
1511
1512
    public:
1513
        slot_type* slot() const {
1514
            return *slot_;
1515
        }
1516
1517
        template <class... Args>
1518
        void operator()(Args&&... args) const {
1519
            assert(*slot_);
1520
            PolicyTraits::construct(alloc_, *slot_, std::forward<Args>(args)...);
1521
            *slot_ = nullptr;
1522
        }
1523
1524
    private:
1525
        constructor(allocator_type* a, slot_type** slot) : alloc_(a), slot_(slot) {}
1526
1527
        allocator_type* alloc_;
1528
        slot_type** slot_;
1529
    };
1530
1531
    // Extension API: support for lazy emplace.
1532
    // Looks up key in the table. If found, returns the iterator to the element.
1533
    // Otherwise calls f with one argument of type raw_hash_set::constructor. f
1534
    // MUST call raw_hash_set::constructor with arguments as if a
1535
    // raw_hash_set::value_type is constructed, otherwise the behavior is
1536
    // undefined.
1537
    //
1538
    // For example:
1539
    //
1540
    //   std::unordered_set<ArenaString> s;
1541
    //   // Makes ArenaStr even if "abc" is in the map.
1542
    //   s.insert(ArenaString(&arena, "abc"));
1543
    //
1544
    //   flat_hash_set<ArenaStr> s;
1545
    //   // Makes ArenaStr only if "abc" is not in the map.
1546
    //   s.lazy_emplace("abc", [&](const constructor& ctor) {
1547
    //                         ctor(&arena, "abc");
1548
    //   });
1549
    // -----------------------------------------------------
1550
    template <class K = key_type, class F>
1551
    iterator lazy_emplace(const key_arg<K>& key, F&& f) {
1552
        return lazy_emplace_with_hash(key, this->hash(key), std::forward<F>(f));
1553
    }
1554
1555
    template <class K = key_type, class F>
1556
    iterator lazy_emplace_with_hash(const key_arg<K>& key, size_t hashval, F&& f) {
1557
        size_t offset = _find_key(key, hashval);
1558
        if (offset == (size_t)-1) {
1559
            offset = prepare_insert(hashval);
1560
            lazy_emplace_at(offset, std::forward<F>(f));
1561
            this->set_ctrl(offset, H2(hashval));
1562
        }
1563
        return iterator_at(offset);
1564
    }
1565
1566
    template <class K = key_type, class F>
1567
    void lazy_emplace_at(size_t& idx, F&& f) {
1568
        slot_type* slot = slots_ + idx;
1569
        std::forward<F>(f)(constructor(&alloc_ref(), &slot));
1570
        assert(!slot);
1571
    }
1572
1573
    template <class K = key_type, class F>
1574
    void emplace_single_with_hash(const key_arg<K>& key, size_t hashval, F&& f) {
1575
        size_t offset = _find_key(key, hashval);
1576
        if (offset == (size_t)-1) {
1577
            offset = prepare_insert(hashval);
1578
            lazy_emplace_at(offset, std::forward<F>(f));
1579
            this->set_ctrl(offset, H2(hashval));
1580
        } else
1581
            _erase(iterator_at(offset));
1582
    }
1583
1584
1585
    // Extension API: support for heterogeneous keys.
1586
    //
1587
    //   std::unordered_set<std::string> s;
1588
    //   // Turns "abc" into std::string.
1589
    //   s.erase("abc");
1590
    //
1591
    //   flat_hash_set<std::string> s;
1592
    //   // Uses "abc" directly without copying it into std::string.
1593
    //   s.erase("abc");
1594
    template <class K = key_type>
1595
    size_type erase(const key_arg<K>& key) {
1596
        auto it = find(key);
1597
        if (it == end()) return 0;
1598
        _erase(it);
1599
        return 1;
1600
    }
1601
1602
1603
    iterator erase(const_iterator cit) { return erase(cit.inner_); }
1604
    
1605
    // Erases the element pointed to by `it`.  Unlike `std::unordered_set::erase`,
1606
    // this method returns void to reduce algorithmic complexity to O(1).  In
1607
    // order to erase while iterating across a map, use the following idiom (which
1608
    // also works for standard containers):
1609
    //
1610
    // for (auto it = m.begin(), end = m.end(); it != end;) {
1611
    //   if (<pred>) {
1612
    //     m._erase(it++);
1613
    //   } else {
1614
    //     ++it;
1615
    //   }
1616
    // }
1617
    void _erase(iterator it) {
1618
        assert(it != end());
1619
        PolicyTraits::destroy(&alloc_ref(), it.slot_);
1620
        erase_meta_only(it);
1621
    }
1622
    void _erase(const_iterator cit) { _erase(cit.inner_); }
1623
1624
    // This overload is necessary because otherwise erase<K>(const K&) would be
1625
    // a better match if non-const iterator is passed as an argument.
1626
    iterator erase(iterator it) {
1627
        assert(it != end());
1628
        auto res = it;
1629
        ++res;
1630
        _erase(it);
1631
        return res;
1632
    }
1633
1634
    iterator erase(const_iterator first, const_iterator last) {
1635
        while (first != last) {
1636
            _erase(first++);
1637
        }
1638
        return last.inner_;
1639
    }
1640
1641
    // Moves elements from `src` into `this`.
1642
    // If the element already exists in `this`, it is left unmodified in `src`.
1643
    template <typename H, typename E>
1644
    void merge(raw_hash_set<Policy, H, E, Alloc>& src) {  // NOLINT
1645
        assert(this != &src);
1646
        for (auto it = src.begin(), e = src.end(); it != e; ++it) {
1647
            if (PolicyTraits::apply(InsertSlot<false>{*this, std::move(*it.slot_)},
1648
                                    PolicyTraits::element(it.slot_))
1649
                .second) {
1650
                src.erase_meta_only(it);
1651
            }
1652
        }
1653
    }
1654
1655
    template <typename H, typename E>
1656
    void merge(raw_hash_set<Policy, H, E, Alloc>&& src) {
1657
        merge(src);
1658
    }
1659
1660
    node_type extract(const_iterator position) {
1661
        auto node =
1662
            CommonAccess::Make<node_type>(alloc_ref(), position.inner_.slot_);
1663
        erase_meta_only(position);
1664
        return node;
1665
    }
1666
1667
    template <
1668
        class K = key_type,
1669
        typename std::enable_if<!std::is_same<K, iterator>::value, int>::type = 0>
1670
    node_type extract(const key_arg<K>& key) {
1671
        auto it = find(key);
1672
        return it == end() ? node_type() : extract(const_iterator{it});
1673
    }
1674
1675
    void swap(raw_hash_set& that) noexcept(
1676
        IsNoThrowSwappable<hasher>() && IsNoThrowSwappable<key_equal>() &&
1677
        (!AllocTraits::propagate_on_container_swap::value ||
1678
601
         IsNoThrowSwappable<allocator_type>(typename AllocTraits::propagate_on_container_swap{}))) {
1679
601
        using std::swap;
1680
601
        swap(ctrl_, that.ctrl_);
1681
601
        swap(slots_, that.slots_);
1682
601
        swap(size_, that.size_);
1683
601
        swap(capacity_, that.capacity_);
1684
601
        swap(growth_left(), that.growth_left());
1685
601
        swap(hash_ref(), that.hash_ref());
1686
601
        swap(eq_ref(), that.eq_ref());
1687
601
        swap(infoz_, that.infoz_);
1688
601
        SwapAlloc(alloc_ref(), that.alloc_ref(), typename AllocTraits::propagate_on_container_swap{});
1689
601
    }
1690
1691
#if !defined(PHMAP_NON_DETERMINISTIC)
1692
    template<typename OutputArchive>
1693
    bool phmap_dump(OutputArchive&) const;
1694
1695
    template<typename InputArchive>
1696
    bool  phmap_load(InputArchive&);
1697
#endif
1698
1699
    void rehash(size_t n) {
1700
        if (n == 0 && capacity_ == 0) return;
1701
        if (n == 0 && size_ == 0) {
1702
            destroy_slots();
1703
            infoz_.RecordStorageChanged(0, 0);
1704
            return;
1705
        }
1706
        // bitor is a faster way of doing `max` here. We will round up to the next
1707
        // power-of-2-minus-1, so bitor is good enough.
1708
        auto m = NormalizeCapacity(n | GrowthToLowerboundCapacity(size()));
1709
        // n == 0 unconditionally rehashes as per the standard.
1710
        if (n == 0 || m > capacity_) {
1711
            resize(m);
1712
        }
1713
    }
1714
1715
    void reserve(size_t n) { rehash(GrowthToLowerboundCapacity(n)); }
1716
1717
    // Extension API: support for heterogeneous keys.
1718
    //
1719
    //   std::unordered_set<std::string> s;
1720
    //   // Turns "abc" into std::string.
1721
    //   s.count("abc");
1722
    //
1723
    //   ch_set<std::string> s;
1724
    //   // Uses "abc" directly without copying it into std::string.
1725
    //   s.count("abc");
1726
    template <class K = key_type>
1727
    size_t count(const key_arg<K>& key) const {
1728
        return find(key) == end() ? size_t(0) : size_t(1);
1729
    }
1730
1731
    // Issues CPU prefetch instructions for the memory needed to find or insert
1732
    // a key.  Like all lookup functions, this support heterogeneous keys.
1733
    //
1734
    // NOTE: This is a very low level operation and should not be used without
1735
    // specific benchmarks indicating its importance.
1736
    void prefetch_hash(size_t hashval) const {
1737
        (void)hashval;
1738
#if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86))
1739
        auto seq = probe(hashval);
1740
        _mm_prefetch((const char *)(ctrl_ + seq.offset()), _MM_HINT_NTA);
1741
        _mm_prefetch((const char *)(slots_ + seq.offset()), _MM_HINT_NTA);
1742
#elif defined(__GNUC__)
1743
        auto seq = probe(hashval);
1744
        __builtin_prefetch(static_cast<const void*>(ctrl_ + seq.offset()));
1745
        __builtin_prefetch(static_cast<const void*>(slots_ + seq.offset()));
1746
#endif  // __GNUC__
1747
    }
1748
1749
    template <class K = key_type>
1750
    void prefetch(const key_arg<K>& key) const {
1751
        PHMAP_IF_CONSTEXPR (std_alloc_t::value)
1752
            prefetch_hash(this->hash(key));
1753
    }
1754
1755
    // The API of find() has two extensions.
1756
    //
1757
    // 1. The hash can be passed by the user. It must be equal to the hash of the
1758
    // key.
1759
    //
1760
    // 2. The type of the key argument doesn't have to be key_type. This is so
1761
    // called heterogeneous key support.
1762
    template <class K = key_type>
1763
    iterator find(const key_arg<K>& key, size_t hashval) {
1764
        size_t offset;
1765
        if (find_impl(key, hashval, offset))
1766
            return iterator_at(offset);
1767
        else
1768
            return end();
1769
    }
1770
1771
    template <class K = key_type>
1772
    pointer find_ptr(const key_arg<K>& key, size_t hashval) {
1773
        size_t offset;
1774
        if (find_impl(key, hashval, offset))
1775
            return &PolicyTraits::element(slots_ + offset);
1776
        else
1777
            return nullptr;
1778
    }
1779
1780
    template <class K = key_type>
1781
    iterator find(const key_arg<K>& key) {
1782
        return find(key, this->hash(key));
1783
    }
1784
1785
    template <class K = key_type>
1786
    const_iterator find(const key_arg<K>& key, size_t hashval) const {
1787
        return const_cast<raw_hash_set*>(this)->find(key, hashval);
1788
    }
1789
    template <class K = key_type>
1790
    const_iterator find(const key_arg<K>& key) const {
1791
        return find(key, this->hash(key));
1792
    }
1793
1794
    template <class K = key_type>
1795
    bool contains(const key_arg<K>& key) const {
1796
        return find(key) != end();
1797
    }
1798
1799
    template <class K = key_type>
1800
    bool contains(const key_arg<K>& key, size_t hashval) const {
1801
        return find(key, hashval) != end();
1802
    }
1803
1804
    template <class K = key_type>
1805
    std::pair<iterator, iterator> equal_range(const key_arg<K>& key) {
1806
        auto it = find(key);
1807
        if (it != end()) return {it, std::next(it)};
1808
        return {it, it};
1809
    }
1810
    template <class K = key_type>
1811
    std::pair<const_iterator, const_iterator> equal_range(
1812
        const key_arg<K>& key) const {
1813
        auto it = find(key);
1814
        if (it != end()) return {it, std::next(it)};
1815
        return {it, it};
1816
    }
1817
1818
    size_t bucket_count() const { return capacity_; }
1819
    float load_factor() const {
1820
        return capacity_ ? static_cast<float>(static_cast<double>(size()) / capacity_) : 0.0f;
1821
    }
1822
    float max_load_factor() const { return 1.0f; }
1823
    void max_load_factor(float) {
1824
        // Does nothing.
1825
    }
1826
1827
    hasher hash_function() const { return hash_ref(); } // warning: doesn't match internal hash - use hash() member function
1828
    key_equal key_eq() const { return eq_ref(); }
1829
    allocator_type get_allocator() const { return alloc_ref(); }
1830
1831
601
    friend bool operator==(const raw_hash_set& a, const raw_hash_set& b) {
1832
601
        if (a.size() != b.size()) return false;
1833
173
        const raw_hash_set* outer = &a;
1834
173
        const raw_hash_set* inner = &b;
1835
173
        if (outer->capacity() > inner->capacity()) 
1836
0
            std::swap(outer, inner);
1837
173
        for (const value_type& elem : *outer)
1838
694k
            if (!inner->has_element(elem)) return false;
1839
48
        return true;
1840
173
    }
1841
1842
    friend bool operator!=(const raw_hash_set& a, const raw_hash_set& b) {
1843
        return !(a == b);
1844
    }
1845
1846
    friend void swap(raw_hash_set& a,
1847
                     raw_hash_set& b) noexcept(noexcept(a.swap(b))) {
1848
        a.swap(b);
1849
    }
1850
1851
    template <class K>
1852
11.6M
    size_t hash(const K& key) const {
1853
11.6M
        return HashElement{hash_ref()}(key);
1854
11.6M
    }
1855
1856
private:
1857
    template <class Container, typename Enabler>
1858
    friend struct phmap::priv::hashtable_debug_internal::HashtableDebugAccess;
1859
1860
    template <class K = key_type>
1861
    bool find_impl(const key_arg<K>& PHMAP_RESTRICT key, size_t hashval, size_t& PHMAP_RESTRICT offset) {
1862
        PHMAP_IF_CONSTEXPR (!std_alloc_t::value) {
1863
            // ctrl_ could be nullptr
1864
            if (!ctrl_)
1865
                return false;
1866
        }
1867
        auto seq = probe(hashval);
1868
        while (true) {
1869
            Group g{ ctrl_ + seq.offset() };
1870
            for (uint32_t i : g.Match((h2_t)H2(hashval))) {
1871
                offset = seq.offset((size_t)i);
1872
                if (PHMAP_PREDICT_TRUE(PolicyTraits::apply(
1873
                    EqualElement<K>{key, eq_ref()},
1874
                    PolicyTraits::element(slots_ + offset))))
1875
                    return true;
1876
            }
1877
            if (PHMAP_PREDICT_TRUE(g.MatchEmpty()))
1878
                return false;
1879
            seq.next();
1880
        }
1881
    }
1882
1883
    struct FindElement 
1884
    {
1885
        template <class K, class... Args>
1886
        const_iterator operator()(const K& key, Args&&...) const {
1887
            return s.find(key);
1888
        }
1889
        const raw_hash_set& s;
1890
    };
1891
1892
    struct HashElement 
1893
    {
1894
        template <class K, class... Args>
1895
13.5M
        size_t operator()(const K& key, Args&&...) const {
1896
#if PHMAP_DISABLE_MIX
1897
            return h(key);
1898
#else
1899
13.5M
            return phmap_mix<sizeof(size_t)>()(h(key));
1900
13.5M
#endif
1901
13.5M
        }
unsigned long phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::HashElement::operator()<unsigned int, std::__1::piecewise_construct_t const&, std::__1::tuple<unsigned int const&>, std::__1::tuple<int const&> >(unsigned int const&, std::__1::piecewise_construct_t const&, std::__1::tuple<unsigned int const&>&&, std::__1::tuple<int const&>&&) const
Line
Count
Source
1895
1.94M
        size_t operator()(const K& key, Args&&...) const {
1896
#if PHMAP_DISABLE_MIX
1897
            return h(key);
1898
#else
1899
1.94M
            return phmap_mix<sizeof(size_t)>()(h(key));
1900
1.94M
#endif
1901
1.94M
        }
unsigned long phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::HashElement::operator()<unsigned int>(unsigned int const&) const
Line
Count
Source
1895
11.6M
        size_t operator()(const K& key, Args&&...) const {
1896
#if PHMAP_DISABLE_MIX
1897
            return h(key);
1898
#else
1899
11.6M
            return phmap_mix<sizeof(size_t)>()(h(key));
1900
11.6M
#endif
1901
11.6M
        }
1902
        const hasher& h;
1903
    };
1904
1905
    template <class K1>
1906
    struct EqualElement 
1907
    {
1908
        template <class K2, class... Args>
1909
13.4M
        bool operator()(const K2& lhs, Args&&...) const {
1910
13.4M
            return eq(lhs, rhs);
1911
13.4M
        }
1912
        const K1& rhs;
1913
        const key_equal& eq;
1914
    };
1915
1916
    template <class K, class... Args>
1917
    std::pair<iterator, bool> emplace_decomposable(const K& key, size_t hashval, 
1918
                                                   Args&&... args)
1919
11.6M
    {
1920
11.6M
        size_t offset = _find_key(key, hashval);
1921
11.6M
        if (offset == (size_t)-1) {
1922
711k
            offset = prepare_insert(hashval);
1923
711k
            emplace_at(offset, std::forward<Args>(args)...);
1924
711k
            this->set_ctrl(offset, H2(hashval));
1925
711k
            return {iterator_at(offset), true};
1926
711k
        }
1927
10.9M
        return {iterator_at(offset), false};
1928
11.6M
    }
1929
1930
    struct EmplaceDecomposable 
1931
    {
1932
        template <class K, class... Args>
1933
11.6M
        std::pair<iterator, bool> operator()(const K& key, Args&&... args) const {
1934
11.6M
            return s.emplace_decomposable(key, s.hash(key), std::forward<Args>(args)...);
1935
11.6M
        }
1936
        raw_hash_set& s;
1937
    };
1938
1939
    struct EmplaceDecomposableHashval {
1940
        template <class K, class... Args>
1941
        std::pair<iterator, bool> operator()(const K& key, Args&&... args) const {
1942
            return s.emplace_decomposable(key, hashval, std::forward<Args>(args)...);
1943
        }
1944
        raw_hash_set& s;
1945
        size_t hashval;
1946
    };
1947
1948
    template <bool do_destroy>
1949
    struct InsertSlot 
1950
    {
1951
        template <class K, class... Args>
1952
        std::pair<iterator, bool> operator()(const K& key, Args&&...) && {
1953
            size_t hashval = s.hash(key);
1954
            auto res = s.find_or_prepare_insert(key, hashval);
1955
            if (res.second) {
1956
                PolicyTraits::transfer(&s.alloc_ref(), s.slots_ + res.first, &slot);
1957
                s.set_ctrl(res.first, H2(hashval));
1958
            } else if (do_destroy) {
1959
                PolicyTraits::destroy(&s.alloc_ref(), &slot);
1960
            }
1961
            return {s.iterator_at(res.first), res.second};
1962
        }
1963
        raw_hash_set& s;
1964
        // Constructed slot. Either moved into place or destroyed.
1965
        slot_type&& slot;
1966
    };
1967
1968
    template <bool do_destroy>
1969
    struct InsertSlotWithHash 
1970
    {
1971
        template <class K, class... Args>
1972
        std::pair<iterator, bool> operator()(const K& key, Args&&...) && {
1973
            auto res = s.find_or_prepare_insert(key, hashval);
1974
            if (res.second) {
1975
                PolicyTraits::transfer(&s.alloc_ref(), s.slots_ + res.first, &slot);
1976
                s.set_ctrl(res.first, H2(hashval));
1977
            } else if (do_destroy) {
1978
                PolicyTraits::destroy(&s.alloc_ref(), &slot);
1979
            }
1980
            return {s.iterator_at(res.first), res.second};
1981
        }
1982
        raw_hash_set& s;
1983
        // Constructed slot. Either moved into place or destroyed.
1984
        slot_type&& slot;
1985
        size_t &hashval;
1986
    };
1987
1988
    // "erases" the object from the container, except that it doesn't actually
1989
    // destroy the object. It only updates all the metadata of the class.
1990
    // This can be used in conjunction with Policy::transfer to move the object to
1991
    // another place.
1992
    void erase_meta_only(const_iterator it) {
1993
        assert(IsFull(*it.inner_.ctrl_) && "erasing a dangling iterator");
1994
        --size_;
1995
        const size_t index = (size_t)(it.inner_.ctrl_ - ctrl_);
1996
        const size_t index_before = (index - Group::kWidth) & capacity_;
1997
        const auto empty_after = Group(it.inner_.ctrl_).MatchEmpty();
1998
        const auto empty_before = Group(ctrl_ + index_before).MatchEmpty();
1999
2000
        // We count how many consecutive non empties we have to the right and to the
2001
        // left of `it`. If the sum is >= kWidth then there is at least one probe
2002
        // window that might have seen a full group.
2003
        bool was_never_full =
2004
            empty_before && empty_after &&
2005
            static_cast<size_t>(empty_after.TrailingZeros() +
2006
                                empty_before.LeadingZeros()) < Group::kWidth;
2007
2008
        set_ctrl(index, was_never_full ? kEmpty : kDeleted);
2009
        growth_left() += was_never_full;
2010
        infoz_.RecordErase();
2011
    }
2012
2013
3.39k
    void initialize_slots(size_t new_capacity) {
2014
3.39k
        assert(new_capacity);
2015
        // Past this bound `layout.AllocSize()` can wrap around size_t and
2016
        // return a size far smaller than `new_capacity` slots.
2017
3.39k
        if (PHMAP_PREDICT_FALSE(new_capacity > (std::numeric_limits<size_t>::max)() / 2 /
2018
3.39k
                                                   (sizeof(slot_type) + 1)))
2019
0
            phmap::base_internal::ThrowStdLengthError("phmap: hash table size overflow");
2020
3.39k
        if (std::is_same<SlotAlloc, std::allocator<slot_type>>::value && 
2021
3.39k
            slots_ == nullptr) {
2022
706
            infoz_ = Sample();
2023
706
        }
2024
2025
3.39k
        auto layout = MakeLayout(new_capacity);
2026
3.39k
        char* mem = static_cast<char*>(
2027
3.39k
            Allocate<Layout::Alignment()>(&alloc_ref(), layout.AllocSize()));
2028
3.39k
        ctrl_ = reinterpret_cast<ctrl_t*>(layout.template Pointer<0>(mem));
2029
3.39k
        slots_ = layout.template Pointer<1>(mem);
2030
3.39k
        reset_ctrl(new_capacity);
2031
3.39k
        reset_growth_left(new_capacity);
2032
3.39k
        infoz_.RecordStorageChanged(size_, new_capacity);
2033
3.39k
    }
2034
2035
2.40k
    void destroy_slots() {
2036
2.40k
        if (!capacity_)
2037
1.69k
            return;
2038
        
2039
706
        PHMAP_IF_CONSTEXPR((!std::is_trivially_destructible<typename PolicyTraits::value_type>::value ||
2040
706
                            std::is_same<typename Policy::is_flat, std::false_type>::value)) {
2041
            // node map, or not trivially destructible... we  need to iterate and destroy values one by one
2042
            // std::cout << "either this is a node map or " << type_name<typename PolicyTraits::value_type>()  << " is not trivially_destructible\n";
2043
0
            for (size_t i = 0, cnt = capacity_; i != cnt; ++i) {
2044
0
                if (IsFull(ctrl_[i])) {
2045
0
                    PolicyTraits::destroy(&alloc_ref(), slots_ + i);
2046
0
                }
2047
0
            }
2048
0
        } 
2049
706
        auto layout = MakeLayout(capacity_);
2050
        // Unpoison before returning the memory to the allocator.
2051
706
        SanitizerUnpoisonMemoryRegion(slots_, sizeof(slot_type) * capacity_);
2052
706
        Deallocate<Layout::Alignment()>(&alloc_ref(), ctrl_, layout.AllocSize());
2053
706
        ctrl_ = EmptyGroup<std_alloc_t>();
2054
706
        slots_ = nullptr;
2055
706
        size_ = 0;
2056
706
        capacity_ = 0;
2057
706
        growth_left() = 0;
2058
706
    }
phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::destroy_slots()
Line
Count
Source
2035
1.80k
    void destroy_slots() {
2036
1.80k
        if (!capacity_)
2037
1.09k
            return;
2038
        
2039
706
        PHMAP_IF_CONSTEXPR((!std::is_trivially_destructible<typename PolicyTraits::value_type>::value ||
2040
706
                            std::is_same<typename Policy::is_flat, std::false_type>::value)) {
2041
            // node map, or not trivially destructible... we  need to iterate and destroy values one by one
2042
            // std::cout << "either this is a node map or " << type_name<typename PolicyTraits::value_type>()  << " is not trivially_destructible\n";
2043
            for (size_t i = 0, cnt = capacity_; i != cnt; ++i) {
2044
                if (IsFull(ctrl_[i])) {
2045
                    PolicyTraits::destroy(&alloc_ref(), slots_ + i);
2046
                }
2047
            }
2048
        } 
2049
706
        auto layout = MakeLayout(capacity_);
2050
        // Unpoison before returning the memory to the allocator.
2051
706
        SanitizerUnpoisonMemoryRegion(slots_, sizeof(slot_type) * capacity_);
2052
706
        Deallocate<Layout::Alignment()>(&alloc_ref(), ctrl_, layout.AllocSize());
2053
706
        ctrl_ = EmptyGroup<std_alloc_t>();
2054
706
        slots_ = nullptr;
2055
706
        size_ = 0;
2056
706
        capacity_ = 0;
2057
706
        growth_left() = 0;
2058
706
    }
phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, phmap::priv::StringHashEqT<char>::Hash, phmap::priv::StringHashEqT<char>::Eq, std::__1::allocator<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > >::destroy_slots()
Line
Count
Source
2035
601
    void destroy_slots() {
2036
601
        if (!capacity_)
2037
601
            return;
2038
        
2039
0
        PHMAP_IF_CONSTEXPR((!std::is_trivially_destructible<typename PolicyTraits::value_type>::value ||
2040
0
                            std::is_same<typename Policy::is_flat, std::false_type>::value)) {
2041
            // node map, or not trivially destructible... we  need to iterate and destroy values one by one
2042
            // std::cout << "either this is a node map or " << type_name<typename PolicyTraits::value_type>()  << " is not trivially_destructible\n";
2043
0
            for (size_t i = 0, cnt = capacity_; i != cnt; ++i) {
2044
0
                if (IsFull(ctrl_[i])) {
2045
0
                    PolicyTraits::destroy(&alloc_ref(), slots_ + i);
2046
0
                }
2047
0
            }
2048
0
        } 
2049
0
        auto layout = MakeLayout(capacity_);
2050
        // Unpoison before returning the memory to the allocator.
2051
0
        SanitizerUnpoisonMemoryRegion(slots_, sizeof(slot_type) * capacity_);
2052
0
        Deallocate<Layout::Alignment()>(&alloc_ref(), ctrl_, layout.AllocSize());
2053
0
        ctrl_ = EmptyGroup<std_alloc_t>();
2054
0
        slots_ = nullptr;
2055
0
        size_ = 0;
2056
0
        capacity_ = 0;
2057
0
        growth_left() = 0;
2058
0
    }
2059
2060
3.25k
    void resize(size_t new_capacity) {
2061
3.25k
        assert(IsValidCapacity(new_capacity));
2062
3.25k
        auto* old_ctrl = ctrl_;
2063
3.25k
        auto* old_slots = slots_;
2064
3.25k
        const size_t old_capacity = capacity_;
2065
3.25k
        initialize_slots(new_capacity);
2066
3.25k
        capacity_ = new_capacity;
2067
2068
1.43M
        for (size_t i = 0; i != old_capacity; ++i) {
2069
1.42M
            if (IsFull(old_ctrl[i])) {
2070
1.25M
                size_t hashval = PolicyTraits::apply(HashElement{hash_ref()},
2071
1.25M
                                                     PolicyTraits::element(old_slots + i));
2072
1.25M
                auto target = find_first_non_full(hashval);
2073
1.25M
                size_t new_i = target.offset;
2074
1.25M
                set_ctrl(new_i, H2(hashval));
2075
1.25M
                PolicyTraits::transfer(&alloc_ref(), slots_ + new_i, old_slots + i);
2076
1.25M
            }
2077
1.42M
        }
2078
3.25k
        if (old_capacity) {
2079
2.69k
            SanitizerUnpoisonMemoryRegion(old_slots,
2080
2.69k
                                          sizeof(slot_type) * old_capacity);
2081
2.69k
            auto layout = MakeLayout(old_capacity);
2082
2.69k
            Deallocate<Layout::Alignment()>(&alloc_ref(), old_ctrl,
2083
2.69k
                                            layout.AllocSize());
2084
2.69k
        }
2085
3.25k
    }
2086
2087
0
    void drop_deletes_without_resize() PHMAP_ATTRIBUTE_NOINLINE {
2088
0
        assert(IsValidCapacity(capacity_));
2089
0
        assert(!is_small());
2090
        // Algorithm:
2091
        // - mark all DELETED slots as EMPTY
2092
        // - mark all FULL slots as DELETED
2093
        // - for each slot marked as DELETED
2094
        //     hash = Hash(element)
2095
        //     target = find_first_non_full(hash)
2096
        //     if target is in the same group
2097
        //       mark slot as FULL
2098
        //     else if target is EMPTY
2099
        //       transfer element to target
2100
        //       mark slot as EMPTY
2101
        //       mark target as FULL
2102
        //     else if target is DELETED
2103
        //       swap current element with target element
2104
        //       mark target as FULL
2105
        //       repeat procedure for current slot with moved from element (target)
2106
0
        ConvertDeletedToEmptyAndFullToDeleted(ctrl_, capacity_);
2107
0
        typename phmap::aligned_storage<sizeof(slot_type), alignof(slot_type)>::type
2108
0
            raw;
2109
0
        slot_type* slot = reinterpret_cast<slot_type*>(&raw);
2110
0
        for (size_t i = 0; i != capacity_; ++i) {
2111
0
            if (!IsDeleted(ctrl_[i])) continue;
2112
0
            size_t hashval = PolicyTraits::apply(HashElement{hash_ref()},
2113
0
                                                 PolicyTraits::element(slots_ + i));
2114
0
            auto target = find_first_non_full(hashval);
2115
0
            size_t new_i = target.offset;
2116
2117
            // Verify if the old and new i fall within the same group wrt the hashval.
2118
            // If they do, we don't need to move the object as it falls already in the
2119
            // best probe we can.
2120
0
            const auto probe_index = [&](size_t pos) {
2121
0
                return ((pos - probe(hashval).offset()) & capacity_) / Group::kWidth;
2122
0
            };
2123
2124
            // Element doesn't move.
2125
0
            if (PHMAP_PREDICT_TRUE(probe_index(new_i) == probe_index(i))) {
2126
0
                set_ctrl(i, H2(hashval));
2127
0
                continue;
2128
0
            }
2129
0
            if (IsEmpty(ctrl_[new_i])) {
2130
                // Transfer element to the empty spot.
2131
                // set_ctrl poisons/unpoisons the slots so we have to call it at the
2132
                // right time.
2133
0
                set_ctrl(new_i, H2(hashval));
2134
0
                PolicyTraits::transfer(&alloc_ref(), slots_ + new_i, slots_ + i);
2135
0
                set_ctrl(i, kEmpty);
2136
0
            } else {
2137
0
                assert(IsDeleted(ctrl_[new_i]));
2138
0
                set_ctrl(new_i, H2(hashval));
2139
                // Until we are done rehashing, DELETED marks previously FULL slots.
2140
                // Swap i and new_i elements.
2141
0
                PolicyTraits::transfer(&alloc_ref(), slot, slots_ + i);
2142
0
                PolicyTraits::transfer(&alloc_ref(), slots_ + i, slots_ + new_i);
2143
0
                PolicyTraits::transfer(&alloc_ref(), slots_ + new_i, slot);
2144
0
                --i;  // repeat
2145
0
            }
2146
0
        }
2147
0
        reset_growth_left(capacity_);
2148
0
    }
2149
2150
3.25k
    void rehash_and_grow_if_necessary() {
2151
3.25k
        if (capacity_ == 0) {
2152
567
            resize(1);
2153
2.69k
        } else if (size() <= CapacityToGrowth(capacity()) / 2) {
2154
            // Squash DELETED without growing if there is enough capacity.
2155
0
            drop_deletes_without_resize();
2156
2.69k
        } else {
2157
            // Otherwise grow the container.
2158
2.69k
            resize(capacity_ * 2 + 1);
2159
2.69k
        }
2160
3.25k
    }
2161
2162
694k
    bool has_element(const value_type& PHMAP_RESTRICT elem, size_t hashval) const {
2163
694k
        PHMAP_IF_CONSTEXPR (!std_alloc_t::value) {
2164
            // ctrl_ could be nullptr
2165
            if (!ctrl_)
2166
                return false;
2167
        }
2168
694k
        auto seq = probe(hashval);
2169
697k
        while (true) {
2170
697k
            Group g{ctrl_ + seq.offset()};
2171
698k
            for (uint32_t i : g.Match((h2_t)H2(hashval))) {
2172
698k
                if (PHMAP_PREDICT_TRUE(PolicyTraits::element(slots_ + seq.offset((size_t)i)) ==
2173
698k
                                      elem))
2174
694k
                    return true;
2175
698k
            }
2176
2.70k
            if (PHMAP_PREDICT_TRUE(g.MatchEmpty())) return false;
2177
2.57k
            seq.next();
2178
2.57k
            assert(seq.getindex() < capacity_ && "full table!");
2179
2.57k
        }
2180
0
        return false;
2181
694k
    }
2182
2183
694k
    bool has_element(const value_type& elem) const {
2184
694k
        size_t hashval = PolicyTraits::apply(HashElement{hash_ref()}, elem);
2185
694k
        return has_element(elem, hashval);
2186
694k
    }
2187
2188
    // Probes the raw_hash_set with the probe sequence for hash and returns the
2189
    // pointer to the first empty or deleted slot.
2190
    // NOTE: this function must work with tables having both kEmpty and kDelete
2191
    // in one group. Such tables appears during drop_deletes_without_resize.
2192
    //
2193
    // This function is very useful when insertions happen and:
2194
    // - the input is already a set
2195
    // - there are enough slots
2196
    // - the element with the hash is not in the table
2197
    struct FindInfo 
2198
    {
2199
        size_t offset;
2200
        size_t probe_length;
2201
    };
2202
1.96M
    FindInfo find_first_non_full(size_t hashval) {
2203
1.96M
        auto seq = probe(hashval);
2204
2.07M
        while (true) {
2205
2.07M
            Group g{ctrl_ + seq.offset()};
2206
2.07M
            auto mask = g.MatchEmptyOrDeleted();
2207
2.07M
            if (mask) {
2208
1.96M
                return {seq.offset((size_t)mask.LowestBitSet()), seq.getindex()};
2209
1.96M
            }
2210
2.07M
            assert(seq.getindex() < capacity_ && "full table!");
2211
107k
            seq.next();
2212
107k
        }
2213
1.96M
    }
2214
2215
    // TODO(alkis): Optimize this assuming *this and that don't overlap.
2216
    raw_hash_set& move_assign(raw_hash_set&& that, std::true_type) {
2217
        raw_hash_set tmp(std::move(that));
2218
        swap(tmp);
2219
        return *this;
2220
    }
2221
    raw_hash_set& move_assign(raw_hash_set&& that, std::false_type) {
2222
        raw_hash_set tmp(std::move(that), alloc_ref());
2223
        swap(tmp);
2224
        return *this;
2225
    }
2226
2227
protected:
2228
    template <class K>
2229
11.6M
    size_t _find_key(const K& PHMAP_RESTRICT key, size_t hashval) {
2230
11.6M
        PHMAP_IF_CONSTEXPR (!std_alloc_t::value) {
2231
            // ctrl_ could be nullptr
2232
            if (!ctrl_)
2233
                return (size_t)-1;
2234
        }
2235
11.6M
        auto seq = probe(hashval);
2236
12.7M
        while (true) {
2237
12.7M
            Group g{ctrl_ + seq.offset()};
2238
13.4M
            for (uint32_t i : g.Match((h2_t)H2(hashval))) {
2239
13.4M
                if (PHMAP_PREDICT_TRUE(PolicyTraits::apply(
2240
13.4M
                                          EqualElement<K>{key, eq_ref()},
2241
13.4M
                                          PolicyTraits::element(slots_ + seq.offset((size_t)i)))))
2242
10.9M
                    return seq.offset((size_t)i);
2243
13.4M
            }
2244
1.84M
            if (PHMAP_PREDICT_TRUE(g.MatchEmpty())) break;
2245
1.13M
            seq.next();
2246
1.13M
        }
2247
711k
        return (size_t)-1;
2248
11.6M
    }
2249
2250
    template <class K>
2251
    std::pair<size_t, bool> find_or_prepare_insert(const K& key, size_t hashval) {
2252
        size_t offset = _find_key(key, hashval);
2253
        if (offset == (size_t)-1)
2254
            return {prepare_insert(hashval), true};
2255
        return {offset, false};
2256
    }
2257
2258
711k
    size_t prepare_insert(size_t hashval) PHMAP_ATTRIBUTE_NOINLINE {
2259
711k
        PHMAP_IF_CONSTEXPR (!std_alloc_t::value) {
2260
            // ctrl_ could be nullptr
2261
            if (!ctrl_)
2262
                rehash_and_grow_if_necessary();
2263
        }
2264
711k
        FindInfo target = find_first_non_full(hashval);
2265
711k
        if (PHMAP_PREDICT_FALSE(growth_left() == 0 &&
2266
711k
                               !IsDeleted(ctrl_[target.offset]))) {
2267
3.25k
            rehash_and_grow_if_necessary();
2268
3.25k
            target = find_first_non_full(hashval);
2269
3.25k
        }
2270
711k
        ++size_;
2271
711k
        growth_left() -= IsEmpty(ctrl_[target.offset]);
2272
        // set_ctrl(target.offset, H2(hashval));
2273
711k
        infoz_.RecordInsert(hashval, target.probe_length);
2274
711k
        return target.offset;
2275
711k
    }
2276
2277
    // Constructs the value in the space pointed by the iterator. This only works
2278
    // after an unsuccessful find_or_prepare_insert() and before any other
2279
    // modifications happen in the raw_hash_set.
2280
    //
2281
    // PRECONDITION: i is an index returned from find_or_prepare_insert(k), where
2282
    // k is the key decomposed from `forward<Args>(args)...`, and the bool
2283
    // returned by find_or_prepare_insert(k) was true.
2284
    // POSTCONDITION: *m.iterator_at(i) == value_type(forward<Args>(args)...).
2285
    template <class... Args>
2286
711k
    void emplace_at(size_t i, Args&&... args) {
2287
711k
        PolicyTraits::construct(&alloc_ref(), slots_ + i,
2288
711k
                                std::forward<Args>(args)...);
2289
        
2290
#ifdef PHMAP_CHECK_CONSTRUCTED_VALUE
2291
        // this check can be costly, so do it only when requested
2292
        assert(PolicyTraits::apply(FindElement{*this}, *iterator_at(i)) ==
2293
               iterator_at(i) &&
2294
               "constructed value does not match the lookup key");
2295
#endif
2296
711k
    }
2297
2298
11.6M
    iterator iterator_at(size_t i) { return {ctrl_ + i, slots_ + i}; }
phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::iterator_at(unsigned long)
Line
Count
Source
2298
11.6M
    iterator iterator_at(size_t i) { return {ctrl_ + i, slots_ + i}; }
Unexecuted instantiation: phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, phmap::priv::StringHashEqT<char>::Hash, phmap::priv::StringHashEqT<char>::Eq, std::__1::allocator<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > >::iterator_at(unsigned long)
2299
    const_iterator iterator_at(size_t i) const { return {ctrl_ + i, slots_ + i}; }
2300
2301
protected:
2302
    // Sets the control byte, and if `i < Group::kWidth`, set the cloned byte at
2303
    // the end too.
2304
1.96M
    void set_ctrl(size_t i, ctrl_t h) {
2305
1.96M
        assert(i < capacity_);
2306
2307
1.96M
        if (IsFull(h)) {
2308
1.96M
            SanitizerUnpoisonObject(slots_ + i);
2309
1.96M
        } else {
2310
0
            SanitizerPoisonObject(slots_ + i);
2311
0
        }
2312
2313
1.96M
        ctrl_[i] = h;
2314
1.96M
        ctrl_[((i - Group::kWidth) & capacity_) + 1 +
2315
1.96M
              ((Group::kWidth - 1) & capacity_)] = h;
2316
1.96M
    }
2317
2318
private:
2319
    friend struct RawHashSetTestOnlyAccess;
2320
2321
14.2M
    probe_seq<Group::kWidth> probe(size_t hashval) const {
2322
14.2M
        return probe_seq<Group::kWidth>(H1(hashval, ctrl_), capacity_);
2323
14.2M
    }
2324
2325
    // Reset all ctrl bytes back to kEmpty, except the sentinel.
2326
3.39k
    void reset_ctrl(size_t new_capacity) {
2327
3.39k
        std::memset(ctrl_, kEmpty, new_capacity + Group::kWidth);
2328
3.39k
        ctrl_[new_capacity] = kSentinel;
2329
3.39k
        SanitizerPoisonMemoryRegion(slots_, sizeof(slot_type) * new_capacity);
2330
3.39k
    }
2331
2332
3.39k
    void reset_growth_left(size_t new_capacity) {
2333
3.39k
        growth_left() = CapacityToGrowth(new_capacity) - size_;
2334
3.39k
    }
2335
2336
1.42M
    size_t& growth_left() { return std::get<0>(settings_); }
phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::growth_left()
Line
Count
Source
2336
1.42M
    size_t& growth_left() { return std::get<0>(settings_); }
Unexecuted instantiation: phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, phmap::priv::StringHashEqT<char>::Hash, phmap::priv::StringHashEqT<char>::Eq, std::__1::allocator<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > >::growth_left()
2337
2338
567
    const size_t& growth_left() const { return std::get<0>(settings_); }
2339
2340
    template <size_t N,
2341
              template <class, class, class, class> class RefSet,
2342
              class M, class P, class H, class E, class A>
2343
    friend class parallel_hash_set;
2344
2345
    template <size_t N,
2346
              template <class, class, class, class> class RefSet,
2347
              class M, class P, class H, class E, class A>
2348
    friend class parallel_hash_map;
2349
2350
    // The representation of the object has two modes:
2351
    //  - small: For capacities < kWidth-1
2352
    //  - large: For the rest.
2353
    //
2354
    // Differences:
2355
    //  - In small mode we are able to use the whole capacity. The extra control
2356
    //  bytes give us at least one "empty" control byte to stop the iteration.
2357
    //  This is important to make 1 a valid capacity.
2358
    //
2359
    //  - In small mode only the first `capacity()` control bytes after the
2360
    //  sentinel are valid. The rest contain dummy kEmpty values that do not
2361
    //  represent a real slot. This is important to take into account on
2362
    //  find_first_non_full(), where we never try ShouldInsertBackwards() for
2363
    //  small tables.
2364
0
    bool is_small() const { return capacity_ < Group::kWidth - 1; }
2365
2366
1.25M
    hasher& hash_ref() { return std::get<1>(settings_); }
2367
12.3M
    const hasher& hash_ref() const { return std::get<1>(settings_); }
2368
13.4M
    key_equal& eq_ref() { return std::get<2>(settings_); }
2369
    const key_equal& eq_ref() const { return std::get<2>(settings_); }
2370
1.97M
    allocator_type& alloc_ref() { return std::get<3>(settings_); }
phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::alloc_ref()
Line
Count
Source
2370
1.97M
    allocator_type& alloc_ref() { return std::get<3>(settings_); }
Unexecuted instantiation: phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, phmap::priv::StringHashEqT<char>::Hash, phmap::priv::StringHashEqT<char>::Eq, std::__1::allocator<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > >::alloc_ref()
2371
    const allocator_type& alloc_ref() const {
2372
        return std::get<3>(settings_);
2373
    }
2374
2375
    // TODO(alkis): Investigate removing some of these fields:
2376
    // - ctrl/slots can be derived from each other
2377
    // - size can be moved into the slot array
2378
    ctrl_t* ctrl_ = EmptyGroup<std_alloc_t>();    // [(capacity + 1) * ctrl_t]
2379
    slot_type* slots_ = nullptr;                  // [capacity * slot_type]
2380
    size_t size_ = 0;                             // number of full slots
2381
    size_t capacity_ = 0;                         // total number of slots
2382
    HashtablezInfoHandle infoz_;
2383
    std::tuple<size_t /* growth_left */, hasher, key_equal, allocator_type>
2384
        settings_{0, hasher{}, key_equal{}, allocator_type{}};
2385
};
2386
2387
2388
// --------------------------------------------------------------------------
2389
// --------------------------------------------------------------------------
2390
template <class Policy, class Hash, class Eq, class Alloc>
2391
class raw_hash_map : public raw_hash_set<Policy, Hash, Eq, Alloc> 
2392
{
2393
    // P is Policy. It's passed as a template argument to support maps that have
2394
    // incomplete types as values, as in unordered_map<K, IncompleteType>.
2395
    // MappedReference<> may be a non-reference type.
2396
    template <class P>
2397
    using MappedReference = decltype(P::value(
2398
               std::addressof(std::declval<typename raw_hash_map::reference>())));
2399
2400
    // MappedConstReference<> may be a non-reference type.
2401
    template <class P>
2402
    using MappedConstReference = decltype(P::value(
2403
               std::addressof(std::declval<typename raw_hash_map::const_reference>())));
2404
2405
    using KeyArgImpl =
2406
        KeyArg<IsTransparent<Eq>::value && IsTransparent<Hash>::value>;
2407
2408
    using Base = raw_hash_set<Policy, Hash, Eq, Alloc>;
2409
2410
public:
2411
    using key_type = typename Policy::key_type;
2412
    using mapped_type = typename Policy::mapped_type;
2413
    template <class K>
2414
    using key_arg = typename KeyArgImpl::template type<K, key_type>;
2415
2416
    static_assert(!std::is_reference<key_type>::value, "");
2417
2418
    // TODO(b/187807849): Evaluate whether to support reference mapped_type and
2419
    // remove this assertion if/when it is supported.
2420
     static_assert(!std::is_reference<mapped_type>::value, "");
2421
2422
    using iterator = typename raw_hash_map::raw_hash_set::iterator;
2423
    using const_iterator = typename raw_hash_map::raw_hash_set::const_iterator;
2424
2425
1.80k
    raw_hash_map() {}
phmap::priv::raw_hash_map<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::raw_hash_map()
Line
Count
Source
2425
1.20k
    raw_hash_map() {}
phmap::priv::raw_hash_map<phmap::priv::FlatHashMapPolicy<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >, phmap::priv::StringHashEqT<char>::Hash, phmap::priv::StringHashEqT<char>::Eq, std::__1::allocator<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > >::raw_hash_map()
Line
Count
Source
2425
601
    raw_hash_map() {}
2426
    using Base::raw_hash_set; // use raw_hash_set constructor  
2427
2428
    // The last two template parameters ensure that both arguments are rvalues
2429
    // (lvalue arguments are handled by the overloads below). This is necessary
2430
    // for supporting bitfield arguments.
2431
    //
2432
    //   union { int n : 1; };
2433
    //   flat_hash_map<int, int> m;
2434
    //   m.insert_or_assign(n, n);
2435
    template <class K = key_type, class V = mapped_type, K* = nullptr,
2436
              V* = nullptr>
2437
    std::pair<iterator, bool> insert_or_assign(key_arg<K>&& k, V&& v) {
2438
        return insert_or_assign_impl(std::forward<K>(k), std::forward<V>(v));
2439
    }
2440
2441
    template <class K = key_type, class V = mapped_type, K* = nullptr>
2442
    std::pair<iterator, bool> insert_or_assign(key_arg<K>&& k, const V& v) {
2443
        return insert_or_assign_impl(std::forward<K>(k), v);
2444
    }
2445
2446
    template <class K = key_type, class V = mapped_type, V* = nullptr>
2447
    std::pair<iterator, bool> insert_or_assign(const key_arg<K>& k, V&& v) {
2448
        return insert_or_assign_impl(k, std::forward<V>(v));
2449
    }
2450
2451
    template <class K = key_type, class V = mapped_type>
2452
    std::pair<iterator, bool> insert_or_assign(const key_arg<K>& k, const V& v) {
2453
        return insert_or_assign_impl(k, v);
2454
    }
2455
2456
    template <class K = key_type, class V = mapped_type, K* = nullptr,
2457
              V* = nullptr>
2458
    iterator insert_or_assign(const_iterator, key_arg<K>&& k, V&& v) {
2459
        return insert_or_assign(std::forward<K>(k), std::forward<V>(v)).first;
2460
    }
2461
2462
    template <class K = key_type, class V = mapped_type, K* = nullptr>
2463
    iterator insert_or_assign(const_iterator, key_arg<K>&& k, const V& v) {
2464
        return insert_or_assign(std::forward<K>(k), v).first;
2465
    }
2466
2467
    template <class K = key_type, class V = mapped_type, V* = nullptr>
2468
    iterator insert_or_assign(const_iterator, const key_arg<K>& k, V&& v) {
2469
        return insert_or_assign(k, std::forward<V>(v)).first;
2470
    }
2471
2472
    template <class K = key_type, class V = mapped_type>
2473
    iterator insert_or_assign(const_iterator, const key_arg<K>& k, const V& v) {
2474
        return insert_or_assign(k, v).first;
2475
    }
2476
2477
    template <class K = key_type, class... Args,
2478
              typename std::enable_if<
2479
                  !std::is_convertible<K, const_iterator>::value, int>::type = 0,
2480
              K* = nullptr>
2481
    std::pair<iterator, bool> try_emplace(key_arg<K>&& k, Args&&... args) {
2482
        return try_emplace_impl(std::forward<K>(k), std::forward<Args>(args)...);
2483
    }
2484
2485
    template <class K = key_type, class... Args,
2486
              typename std::enable_if<
2487
                  !std::is_convertible<K, const_iterator>::value, int>::type = 0>
2488
    std::pair<iterator, bool> try_emplace(const key_arg<K>& k, Args&&... args) {
2489
        return try_emplace_impl(k, std::forward<Args>(args)...);
2490
    }
2491
2492
    template <class K = key_type, class... Args, K* = nullptr>
2493
    iterator try_emplace(const_iterator, key_arg<K>&& k, Args&&... args) {
2494
        return try_emplace(std::forward<K>(k), std::forward<Args>(args)...).first;
2495
    }
2496
2497
    template <class K = key_type, class... Args>
2498
    iterator try_emplace(const_iterator, const key_arg<K>& k, Args&&... args) {
2499
        return try_emplace(k, std::forward<Args>(args)...).first;
2500
    }
2501
2502
    template <class K = key_type, class P = Policy>
2503
    MappedReference<P> at(const key_arg<K>& key) {
2504
        auto it = this->find(key);
2505
        if (it == this->end()) 
2506
            phmap::base_internal::ThrowStdOutOfRange("phmap at(): lookup non-existent key");
2507
        return Policy::value(&*it);
2508
    }
2509
2510
    template <class K = key_type, class P = Policy>
2511
    MappedConstReference<P> at(const key_arg<K>& key) const {
2512
        auto it = this->find(key);
2513
        if (it == this->end())
2514
            phmap::base_internal::ThrowStdOutOfRange("phmap at(): lookup non-existent key");
2515
        return Policy::value(&*it);
2516
    }
2517
2518
    template <class K = key_type, class P = Policy, K* = nullptr>
2519
    MappedReference<P> operator[](key_arg<K>&& key) {
2520
        return Policy::value(&*try_emplace(std::forward<K>(key)).first);
2521
    }
2522
2523
    template <class K = key_type, class P = Policy>
2524
    MappedReference<P> operator[](const key_arg<K>& key) {
2525
        return Policy::value(&*try_emplace(key).first);
2526
    }
2527
2528
private:
2529
    template <class K, class V>
2530
    std::pair<iterator, bool> insert_or_assign_impl(K&& k, V&& v) {
2531
        size_t hashval = this->hash(k);
2532
        size_t offset = this->_find_key(k, hashval);
2533
        if (offset == (size_t)-1) {
2534
            offset = this->prepare_insert(hashval);
2535
            this->emplace_at(offset, std::forward<K>(k), std::forward<V>(v));
2536
            this->set_ctrl(offset, H2(hashval));
2537
            return {this->iterator_at(offset), true};
2538
        } 
2539
        Policy::value(&*this->iterator_at(offset)) = std::forward<V>(v);
2540
        return {this->iterator_at(offset), false};
2541
    }
2542
2543
    template <class K = key_type, class... Args>
2544
    std::pair<iterator, bool> try_emplace_impl(K&& k, Args&&... args) {
2545
        size_t hashval = this->hash(k);
2546
        size_t offset = this->_find_key(k, hashval);
2547
        if (offset == (size_t)-1) {
2548
            offset = this->prepare_insert(hashval);
2549
            this->emplace_at(offset, std::piecewise_construct,
2550
                             std::forward_as_tuple(std::forward<K>(k)),
2551
                             std::forward_as_tuple(std::forward<Args>(args)...));
2552
            this->set_ctrl(offset, H2(hashval));
2553
            return {this->iterator_at(offset), true};
2554
        }
2555
        return {this->iterator_at(offset), false};
2556
    }
2557
};
2558
2559
// ----------------------------------------------------------------------------
2560
// ----------------------------------------------------------------------------
2561
// Returns "random" seed.
2562
inline size_t RandomSeed() 
2563
0
{
2564
0
#if PHMAP_HAVE_THREAD_LOCAL
2565
0
    static thread_local size_t counter = 0;
2566
0
    size_t value = ++counter;
2567
0
#else   // PHMAP_HAVE_THREAD_LOCAL
2568
0
    static std::atomic<size_t> counter(0);
2569
0
    size_t value = counter.fetch_add(1, std::memory_order_relaxed);
2570
0
#endif  // PHMAP_HAVE_THREAD_LOCAL
2571
0
    return value ^ static_cast<size_t>(reinterpret_cast<uintptr_t>(&counter));
2572
0
}
2573
2574
// ----------------------------------------------------------------------------
2575
// ----------------------------------------------------------------------------
2576
template <size_t N,
2577
          template <class, class, class, class> class RefSet,
2578
          class Mtx_,
2579
          class Policy, class Hash, class Eq, class Alloc>
2580
class parallel_hash_set 
2581
{
2582
    using PolicyTraits = hash_policy_traits<Policy>;
2583
    using KeyArgImpl =
2584
        KeyArg<IsTransparent<Eq>::value && IsTransparent<Hash>::value>;
2585
2586
    static_assert(N <= 12, "N = 12 means 4096 hash tables!");
2587
    constexpr static size_t num_tables = 1 << N;
2588
    constexpr static size_t mask = num_tables - 1;
2589
2590
public:
2591
    using EmbeddedSet     = RefSet<Policy, Hash, Eq, Alloc>;
2592
    using EmbeddedIterator= typename EmbeddedSet::iterator;
2593
    using EmbeddedConstIterator= typename EmbeddedSet::const_iterator;
2594
    using constructor     = typename EmbeddedSet::constructor;
2595
    using init_type       = typename PolicyTraits::init_type;
2596
    using key_type        = typename PolicyTraits::key_type;
2597
    using slot_type       = typename PolicyTraits::slot_type;
2598
    using allocator_type  = Alloc;
2599
    using size_type       = size_t;
2600
    using difference_type = ptrdiff_t;
2601
    using hasher          = Hash;
2602
    using key_equal       = Eq;
2603
    using policy_type     = Policy;
2604
    using value_type      = typename PolicyTraits::value_type;
2605
    using reference       = value_type&;
2606
    using const_reference = const value_type&;
2607
    using pointer         = typename phmap::allocator_traits<
2608
        allocator_type>::template rebind_traits<value_type>::pointer;
2609
    using const_pointer   = typename phmap::allocator_traits<
2610
        allocator_type>::template rebind_traits<value_type>::const_pointer;
2611
2612
    // Alias used for heterogeneous lookup functions.
2613
    // `key_arg<K>` evaluates to `K` when the functors are transparent and to
2614
    // `key_type` otherwise. It permits template argument deduction on `K` for the
2615
    // transparent case.
2616
    // --------------------------------------------------------------------
2617
    template <class K>
2618
    using key_arg         = typename KeyArgImpl::template type<K, key_type>;
2619
2620
protected:
2621
    using Lockable      = phmap::LockableImpl<Mtx_>;
2622
    using UniqueLock    = typename Lockable::UniqueLock;
2623
    using SharedLock    = typename Lockable::SharedLock;
2624
    using ReadWriteLock = typename Lockable::ReadWriteLock;
2625
2626
    // --------------------------------------------------------------------
2627
    struct Inner : public Lockable
2628
    {
2629
        struct Params
2630
        {
2631
            size_t bucket_cnt;
2632
            const hasher& hashfn;
2633
            const key_equal& eq;
2634
            const allocator_type& alloc;
2635
        };
2636
2637
        Inner() {}
2638
2639
        Inner(Params const &p) : set_(p.bucket_cnt, p.hashfn, p.eq, p.alloc)
2640
        {}
2641
2642
        bool operator==(const Inner& o) const
2643
        {
2644
            typename Lockable::SharedLocks l(const_cast<Inner &>(*this), const_cast<Inner &>(o));
2645
            return set_ == o.set_;
2646
        }
2647
2648
        EmbeddedSet set_;
2649
    };
2650
2651
private:
2652
    // Give an early error when key_type is not hashable/eq.
2653
    // --------------------------------------------------------------------
2654
    auto KeyTypeCanBeHashed(const Hash& h, const key_type& k) -> decltype(h(k));
2655
    auto KeyTypeCanBeEq(const Eq& eq, const key_type& k)      -> decltype(eq(k, k));
2656
2657
    using AllocTraits     = phmap::allocator_traits<allocator_type>;
2658
2659
    static_assert(std::is_lvalue_reference<reference>::value,
2660
                  "Policy::element() must return a reference");
2661
2662
    template <typename T>
2663
    struct SameAsElementReference : std::is_same<
2664
        typename std::remove_cv<typename std::remove_reference<reference>::type>::type,
2665
        typename std::remove_cv<typename std::remove_reference<T>::type>::type> {};
2666
2667
    // An enabler for insert(T&&): T must be convertible to init_type or be the
2668
    // same as [cv] value_type [ref].
2669
    // Note: we separate SameAsElementReference into its own type to avoid using
2670
    // reference unless we need to. MSVC doesn't seem to like it in some
2671
    // cases.
2672
    // --------------------------------------------------------------------
2673
    template <class T>
2674
    using RequiresInsertable = typename std::enable_if<
2675
        phmap::disjunction<std::is_convertible<T, init_type>, SameAsElementReference<T>>::value, int>::type;
2676
2677
    // RequiresNotInit is a workaround for gcc prior to 7.1.
2678
    // See https://godbolt.org/g/Y4xsUh.
2679
    template <class T>
2680
    using RequiresNotInit =
2681
        typename std::enable_if<!std::is_same<T, init_type>::value, int>::type;
2682
2683
    template <class... Ts>
2684
    using IsDecomposable = IsDecomposable<void, PolicyTraits, Hash, Eq, Ts...>;
2685
2686
public:
2687
    static_assert(std::is_same<pointer, value_type*>::value,
2688
                  "Allocators with custom pointer types are not supported");
2689
    static_assert(std::is_same<const_pointer, const value_type*>::value,
2690
                  "Allocators with custom pointer types are not supported");
2691
2692
    // --------------------- i t e r a t o r ------------------------------
2693
    class iterator 
2694
    {
2695
        friend class parallel_hash_set;
2696
2697
    public:
2698
        using iterator_category = std::forward_iterator_tag;
2699
        using value_type        = typename parallel_hash_set::value_type;
2700
        using reference         =
2701
            phmap::conditional_t<PolicyTraits::constant_iterators::value,
2702
                                const value_type&, value_type&>;
2703
        using pointer           = phmap::remove_reference_t<reference>*;
2704
        using difference_type   = typename parallel_hash_set::difference_type;
2705
        using Inner             = typename parallel_hash_set::Inner;
2706
        using EmbeddedSet       = typename parallel_hash_set::EmbeddedSet;
2707
        using EmbeddedIterator  = typename EmbeddedSet::iterator;
2708
2709
        iterator() {}
2710
2711
        reference operator*()  const { return *it_; }
2712
        pointer   operator->() const { return &operator*(); }
2713
2714
        iterator& operator++() {
2715
            assert(inner_); // null inner means we are already at the end
2716
            ++it_;
2717
            skip_empty();
2718
            return *this;
2719
        }
2720
    
2721
        iterator operator++(int) {
2722
            assert(inner_);  // null inner means we are already at the end
2723
            auto tmp = *this;
2724
            ++*this;
2725
            return tmp;
2726
        }
2727
2728
        friend bool operator==(const iterator& a, const iterator& b) {
2729
            return a.inner_ == b.inner_ && (!a.inner_ || a.it_ == b.it_);
2730
        }
2731
2732
        friend bool operator!=(const iterator& a, const iterator& b) {
2733
            return !(a == b);
2734
        }
2735
2736
    private:
2737
        iterator(Inner *inner, Inner *inner_end, const EmbeddedIterator& it) : 
2738
            inner_(inner), inner_end_(inner_end), it_(it)  {  // for begin() and end()
2739
            if (inner)
2740
                it_end_ = inner->set_.end();
2741
        }
2742
2743
        void skip_empty() {
2744
            while (it_ == it_end_) {
2745
                ++inner_;
2746
                if (inner_ == inner_end_) {
2747
                    inner_ = nullptr; // marks end()
2748
                    break;
2749
                }
2750
                else {
2751
                    it_ = inner_->set_.begin();
2752
                    it_end_ = inner_->set_.end();
2753
                }
2754
            }
2755
        }
2756
2757
        Inner *inner_      = nullptr;
2758
        Inner *inner_end_  = nullptr;
2759
        EmbeddedIterator it_, it_end_;
2760
    };
2761
2762
    // --------------------- c o n s t   i t e r a t o r -----------------
2763
    class const_iterator 
2764
    {
2765
        friend class parallel_hash_set;
2766
2767
    public:
2768
        using iterator_category = typename iterator::iterator_category;
2769
        using value_type        = typename parallel_hash_set::value_type;
2770
        using reference         = typename parallel_hash_set::const_reference;
2771
        using pointer           = typename parallel_hash_set::const_pointer;
2772
        using difference_type   = typename parallel_hash_set::difference_type;
2773
        using Inner             = typename parallel_hash_set::Inner;
2774
2775
        const_iterator() {}
2776
        // Implicit construction from iterator.
2777
        const_iterator(iterator i) : iter_(std::move(i)) {}
2778
2779
        reference operator*()  const { return *(iter_); }
2780
        pointer   operator->() const { return iter_.operator->(); }
2781
2782
        const_iterator& operator++() {
2783
            ++iter_;
2784
            return *this;
2785
        }
2786
        const_iterator operator++(int) { return iter_++; }
2787
2788
        friend bool operator==(const const_iterator& a, const const_iterator& b) {
2789
            return a.iter_ == b.iter_;
2790
        }
2791
        friend bool operator!=(const const_iterator& a, const const_iterator& b) {
2792
            return !(a == b);
2793
        }
2794
2795
    private:
2796
        const_iterator(const Inner *inner, const Inner *inner_end, const EmbeddedIterator& it)
2797
            : iter_(const_cast<Inner**>(inner), 
2798
                    const_cast<Inner**>(inner_end),
2799
                    const_cast<EmbeddedIterator*>(it)) {}
2800
2801
        iterator iter_;
2802
    };
2803
2804
    using node_type = node_handle<Policy, hash_policy_traits<Policy>, Alloc>;
2805
    using insert_return_type = InsertReturnType<iterator, node_type>;
2806
2807
    // ------------------------- c o n s t r u c t o r s ------------------
2808
2809
    parallel_hash_set() noexcept(
2810
        std::is_nothrow_default_constructible<hasher>::value&&
2811
        std::is_nothrow_default_constructible<key_equal>::value&&
2812
        std::is_nothrow_default_constructible<allocator_type>::value) {}
2813
2814
#if  (__cplusplus >= 201703L || _MSVC_LANG >= 201402) && (defined(_MSC_VER) || defined(__clang__) || (defined(__GNUC__) && __GNUC__ > 6))
2815
    explicit parallel_hash_set(size_t bucket_cnt, 
2816
                               const hasher& hash_param    = hasher(),
2817
                               const key_equal& eq         = key_equal(),
2818
                               const allocator_type& alloc = allocator_type()) :
2819
        parallel_hash_set(typename Inner::Params{bucket_cnt, hash_param, eq, alloc}, 
2820
                          phmap::make_index_sequence<num_tables>{})
2821
    {}
2822
2823
    template <std::size_t... i>
2824
    parallel_hash_set(typename Inner::Params const &p,
2825
                      phmap::index_sequence<i...>) : sets_{((void)i, p)...}
2826
    {}
2827
#else
2828
    explicit parallel_hash_set(size_t bucket_cnt, 
2829
                               const hasher& hash_param    = hasher(),
2830
                               const key_equal& eq         = key_equal(),
2831
                               const allocator_type& alloc = allocator_type()) {
2832
        for (auto& inner : sets_)
2833
            inner.set_ = EmbeddedSet(bucket_cnt / N, hash_param, eq, alloc);
2834
    }
2835
#endif
2836
2837
    parallel_hash_set(size_t bucket_cnt, 
2838
                      const hasher& hash_param,
2839
                      const allocator_type& alloc)
2840
        : parallel_hash_set(bucket_cnt, hash_param, key_equal(), alloc) {}
2841
2842
    parallel_hash_set(size_t bucket_cnt, const allocator_type& alloc)
2843
        : parallel_hash_set(bucket_cnt, hasher(), key_equal(), alloc) {}
2844
2845
    explicit parallel_hash_set(const allocator_type& alloc)
2846
        : parallel_hash_set(0, hasher(), key_equal(), alloc) {}
2847
2848
    template <class InputIter>
2849
    parallel_hash_set(InputIter first, InputIter last, size_t bucket_cnt = 0,
2850
                      const hasher& hash_param = hasher(), const key_equal& eq = key_equal(),
2851
                      const allocator_type& alloc = allocator_type())
2852
        : parallel_hash_set(bucket_cnt, hash_param, eq, alloc) {
2853
        insert(first, last);
2854
    }
2855
2856
    template <class InputIter>
2857
    parallel_hash_set(InputIter first, InputIter last, size_t bucket_cnt,
2858
                      const hasher& hash_param, const allocator_type& alloc)
2859
        : parallel_hash_set(first, last, bucket_cnt, hash_param, key_equal(), alloc) {}
2860
2861
    template <class InputIter>
2862
    parallel_hash_set(InputIter first, InputIter last, size_t bucket_cnt,
2863
                      const allocator_type& alloc)
2864
        : parallel_hash_set(first, last, bucket_cnt, hasher(), key_equal(), alloc) {}
2865
2866
    template <class InputIter>
2867
    parallel_hash_set(InputIter first, InputIter last, const allocator_type& alloc)
2868
        : parallel_hash_set(first, last, 0, hasher(), key_equal(), alloc) {}
2869
2870
    // Instead of accepting std::initializer_list<value_type> as the first
2871
    // argument like std::unordered_set<value_type> does, we have two overloads
2872
    // that accept std::initializer_list<T> and std::initializer_list<init_type>.
2873
    // This is advantageous for performance.
2874
    //
2875
    //   // Turns {"abc", "def"} into std::initializer_list<std::string>, then copies
2876
    //   // the strings into the set.
2877
    //   std::unordered_set<std::string> s = {"abc", "def"};
2878
    //
2879
    //   // Turns {"abc", "def"} into std::initializer_list<const char*>, then
2880
    //   // copies the strings into the set.
2881
    //   phmap::flat_hash_set<std::string> s = {"abc", "def"};
2882
    //
2883
    // The same trick is used in insert().
2884
    //
2885
    // The enabler is necessary to prevent this constructor from triggering where
2886
    // the copy constructor is meant to be called.
2887
    //
2888
    //   phmap::flat_hash_set<int> a, b{a};
2889
    //
2890
    // RequiresNotInit<T> is a workaround for gcc prior to 7.1.
2891
    // --------------------------------------------------------------------
2892
    template <class T, RequiresNotInit<T> = 0, RequiresInsertable<T> = 0>
2893
    parallel_hash_set(std::initializer_list<T> init, size_t bucket_cnt = 0,
2894
                      const hasher& hash_param = hasher(), const key_equal& eq = key_equal(),
2895
                      const allocator_type& alloc = allocator_type())
2896
        : parallel_hash_set(init.begin(), init.end(), bucket_cnt, hash_param, eq, alloc) {}
2897
2898
    parallel_hash_set(std::initializer_list<init_type> init, size_t bucket_cnt = 0,
2899
                      const hasher& hash_param = hasher(), const key_equal& eq = key_equal(),
2900
                      const allocator_type& alloc = allocator_type())
2901
        : parallel_hash_set(init.begin(), init.end(), bucket_cnt, hash_param, eq, alloc) {}
2902
2903
    template <class T, RequiresNotInit<T> = 0, RequiresInsertable<T> = 0>
2904
    parallel_hash_set(std::initializer_list<T> init, size_t bucket_cnt,
2905
                      const hasher& hash_param, const allocator_type& alloc)
2906
        : parallel_hash_set(init, bucket_cnt, hash_param, key_equal(), alloc) {}
2907
2908
    parallel_hash_set(std::initializer_list<init_type> init, size_t bucket_cnt,
2909
                      const hasher& hash_param, const allocator_type& alloc)
2910
        : parallel_hash_set(init, bucket_cnt, hash_param, key_equal(), alloc) {}
2911
2912
    template <class T, RequiresNotInit<T> = 0, RequiresInsertable<T> = 0>
2913
    parallel_hash_set(std::initializer_list<T> init, size_t bucket_cnt,
2914
                      const allocator_type& alloc)
2915
        : parallel_hash_set(init, bucket_cnt, hasher(), key_equal(), alloc) {}
2916
2917
    parallel_hash_set(std::initializer_list<init_type> init, size_t bucket_cnt,
2918
                      const allocator_type& alloc)
2919
        : parallel_hash_set(init, bucket_cnt, hasher(), key_equal(), alloc) {}
2920
2921
    template <class T, RequiresNotInit<T> = 0, RequiresInsertable<T> = 0>
2922
    parallel_hash_set(std::initializer_list<T> init, const allocator_type& alloc)
2923
        : parallel_hash_set(init, 0, hasher(), key_equal(), alloc) {}
2924
  
2925
    parallel_hash_set(std::initializer_list<init_type> init,
2926
                      const allocator_type& alloc)
2927
        : parallel_hash_set(init, 0, hasher(), key_equal(), alloc) {}
2928
2929
    parallel_hash_set(const parallel_hash_set& that)
2930
        : parallel_hash_set(that, AllocTraits::select_on_container_copy_construction(
2931
                                that.alloc_ref())) {}
2932
2933
    parallel_hash_set(const parallel_hash_set& that, const allocator_type& a)
2934
        : parallel_hash_set(0, that.hash_ref(), that.eq_ref(), a) {
2935
        for (size_t i=0; i<num_tables; ++i)
2936
            sets_[i].set_ = { that.sets_[i].set_, a };
2937
    }
2938
  
2939
    parallel_hash_set(parallel_hash_set&& that) noexcept(
2940
        std::is_nothrow_copy_constructible<hasher>::value&&
2941
        std::is_nothrow_copy_constructible<key_equal>::value&&
2942
        std::is_nothrow_copy_constructible<allocator_type>::value)
2943
        : parallel_hash_set(std::move(that), that.alloc_ref()) {
2944
    }
2945
2946
    parallel_hash_set(parallel_hash_set&& that, const allocator_type& a)
2947
    {
2948
        for (size_t i=0; i<num_tables; ++i)
2949
            sets_[i].set_ = { std::move(that.sets_[i]).set_, a };
2950
    }
2951
2952
    parallel_hash_set& operator=(const parallel_hash_set& that) {
2953
        for (size_t i=0; i<num_tables; ++i)
2954
            sets_[i].set_ = that.sets_[i].set_;
2955
        return *this;
2956
    }
2957
2958
    parallel_hash_set& operator=(parallel_hash_set&& that) noexcept(
2959
        phmap::allocator_traits<allocator_type>::is_always_equal::value &&
2960
        std::is_nothrow_move_assignable<hasher>::value &&
2961
        std::is_nothrow_move_assignable<key_equal>::value) {
2962
        for (size_t i=0; i<num_tables; ++i)
2963
            sets_[i].set_ = std::move(that.sets_[i].set_);
2964
        return *this;
2965
    }
2966
2967
    ~parallel_hash_set() {}
2968
2969
    iterator begin() {
2970
        auto it = iterator(&sets_[0], &sets_[0] + num_tables, sets_[0].set_.begin());
2971
        it.skip_empty();
2972
        return it;
2973
    }
2974
2975
    iterator       end()          { return iterator(); }
2976
    const_iterator begin()  const { return const_cast<parallel_hash_set *>(this)->begin(); }
2977
    const_iterator end()    const { return const_cast<parallel_hash_set *>(this)->end(); }
2978
    const_iterator cbegin() const { return begin(); }
2979
    const_iterator cend()   const { return end(); }
2980
2981
    bool empty() const { return !size(); }
2982
2983
    size_t size() const { 
2984
        size_t sz = 0;
2985
        for (const auto& inner : sets_)
2986
            sz += inner.set_.size();
2987
        return sz; 
2988
    }
2989
  
2990
    size_t capacity() const { 
2991
        size_t c = 0;
2992
        for (const auto& inner : sets_)
2993
            c += inner.set_.capacity();
2994
        return c; 
2995
    }
2996
2997
    size_t max_size() const { return (std::numeric_limits<size_t>::max)(); }
2998
2999
    PHMAP_ATTRIBUTE_REINITIALIZES void clear() {
3000
        for (auto& inner : sets_)
3001
        {
3002
            UniqueLock m(inner);
3003
            inner.set_.clear();
3004
        }
3005
    }
3006
3007
    // extension - clears only soecified submap
3008
    // ----------------------------------------
3009
    void clear(std::size_t submap_index) {
3010
        Inner& inner = sets_[submap_index];
3011
        UniqueLock m(inner);
3012
        inner.set_.clear();
3013
    }
3014
3015
    // This overload kicks in when the argument is an rvalue of insertable and
3016
    // decomposable type other than init_type.
3017
    //
3018
    //   flat_hash_map<std::string, int> m;
3019
    //   m.insert(std::make_pair("abc", 42));
3020
    // --------------------------------------------------------------------
3021
    template <class T, RequiresInsertable<T> = 0,
3022
              typename std::enable_if<IsDecomposable<T>::value, int>::type = 0,
3023
              T* = nullptr>
3024
    std::pair<iterator, bool> insert(T&& value) {
3025
        return emplace(std::forward<T>(value));
3026
    }
3027
3028
    // This overload kicks in when the argument is a bitfield or an lvalue of
3029
    // insertable and decomposable type.
3030
    //
3031
    //   union { int n : 1; };
3032
    //   flat_hash_set<int> s;
3033
    //   s.insert(n);
3034
    //
3035
    //   flat_hash_set<std::string> s;
3036
    //   const char* p = "hello";
3037
    //   s.insert(p);
3038
    //
3039
    // TODO(romanp): Once we stop supporting gcc 5.1 and below, replace
3040
    // RequiresInsertable<T> with RequiresInsertable<const T&>.
3041
    // We are hitting this bug: https://godbolt.org/g/1Vht4f.
3042
    // --------------------------------------------------------------------
3043
    template <
3044
        class T, RequiresInsertable<T> = 0,
3045
        typename std::enable_if<IsDecomposable<const T&>::value, int>::type = 0>
3046
    std::pair<iterator, bool> insert(const T& value) {
3047
        return emplace(value);
3048
    }
3049
3050
    // This overload kicks in when the argument is an rvalue of init_type. Its
3051
    // purpose is to handle brace-init-list arguments.
3052
    //
3053
    //   flat_hash_set<std::pair<std::string, int>> s;
3054
    //   s.insert({"abc", 42});
3055
    // --------------------------------------------------------------------
3056
    std::pair<iterator, bool> insert(init_type&& value) {
3057
        return emplace(std::move(value));
3058
    }
3059
3060
    template <class T, RequiresInsertable<T> = 0,
3061
              typename std::enable_if<IsDecomposable<T>::value, int>::type = 0,
3062
              T* = nullptr>
3063
    iterator insert(const_iterator, T&& value) {
3064
        return insert(std::forward<T>(value)).first;
3065
    }
3066
3067
    // TODO(romanp): Once we stop supporting gcc 5.1 and below, replace
3068
    // RequiresInsertable<T> with RequiresInsertable<const T&>.
3069
    // We are hitting this bug: https://godbolt.org/g/1Vht4f.
3070
    // --------------------------------------------------------------------
3071
    template <
3072
        class T, RequiresInsertable<T> = 0,
3073
        typename std::enable_if<IsDecomposable<const T&>::value, int>::type = 0>
3074
    iterator insert(const_iterator, const T& value) {
3075
        return insert(value).first;
3076
    }
3077
3078
    iterator insert(const_iterator, init_type&& value) {
3079
        return insert(std::move(value)).first;
3080
    }
3081
3082
    template <class InputIt>
3083
    void insert(InputIt first, InputIt last) {
3084
        for (; first != last; ++first) insert(*first);
3085
    }
3086
3087
    template <class T, RequiresNotInit<T> = 0, RequiresInsertable<const T&> = 0>
3088
    void insert(std::initializer_list<T> ilist) {
3089
        insert(ilist.begin(), ilist.end());
3090
    }
3091
3092
    void insert(std::initializer_list<init_type> ilist) {
3093
        insert(ilist.begin(), ilist.end());
3094
    }
3095
3096
    insert_return_type insert(node_type&& node) {
3097
        if (!node) 
3098
            return {end(), false, node_type()};
3099
        auto& key      = node.key();
3100
        size_t hashval = this->hash(key);
3101
        Inner& inner   = sets_[subidx(hashval)];
3102
        auto&  set     = inner.set_;
3103
3104
        UniqueLock m(inner);
3105
        auto   res  = set.insert(std::move(node), hashval);
3106
        return { make_iterator(&inner, res.position),
3107
                 res.inserted,
3108
                 res.inserted ? node_type() : std::move(res.node) };
3109
    }
3110
3111
    iterator insert(const_iterator, node_type&& node) {
3112
        return insert(std::move(node)).first;
3113
    }
3114
3115
    struct ReturnKey_ 
3116
    {
3117
        template <class Key, class... Args>
3118
        Key operator()(Key&& k, const Args&...) const {
3119
            return std::forward<Key>(k);
3120
        }
3121
    };
3122
3123
    // --------------------------------------------------------------------
3124
    // phmap extension: emplace_with_hash
3125
    // ----------------------------------
3126
    // same as emplace, but hashval is provided
3127
    // --------------------------------------------------------------------
3128
    struct EmplaceDecomposableHashval 
3129
    {
3130
        template <class K, class... Args>
3131
        std::pair<iterator, bool> operator()(const K& key, Args&&... args) const {
3132
            return s.emplace_decomposable_with_hash(key, hashval, std::forward<Args>(args)...);
3133
        }
3134
        parallel_hash_set& s;
3135
        size_t hashval;
3136
    };
3137
3138
    // This overload kicks in if we can deduce the key from args. This enables us
3139
    // to avoid constructing value_type if an entry with the same key already
3140
    // exists.
3141
    //
3142
    // For example:
3143
    //
3144
    //   flat_hash_map<std::string, std::string> m = {{"abc", "def"}};
3145
    //   // Creates no std::string copies and makes no heap allocations.
3146
    //   m.emplace("abc", "xyz");
3147
    // --------------------------------------------------------------------
3148
    template <class... Args, typename std::enable_if<IsDecomposable<Args...>::value, int>::type = 0>
3149
    std::pair<iterator, bool> emplace_with_hash(size_t hashval, Args&&... args) {
3150
        return PolicyTraits::apply(EmplaceDecomposableHashval{*this, hashval},
3151
                                   std::forward<Args>(args)...);
3152
    }
3153
3154
    // This overload kicks in if we cannot deduce the key from args. It constructs
3155
    // value_type unconditionally and then either moves it into the table or
3156
    // destroys.
3157
    // --------------------------------------------------------------------
3158
    template <class... Args, typename std::enable_if<!IsDecomposable<Args...>::value, int>::type = 0>
3159
    std::pair<iterator, bool> emplace_with_hash(size_t hashval, Args&&... args) {
3160
        typename phmap::aligned_storage<sizeof(slot_type), alignof(slot_type)>::type raw;
3161
        slot_type* slot = reinterpret_cast<slot_type*>(&raw);
3162
3163
        PolicyTraits::construct(&alloc_ref(), slot, std::forward<Args>(args)...);
3164
        const auto& elem = PolicyTraits::element(slot);
3165
        Inner& inner    = sets_[subidx(hashval)];
3166
        auto&  set      = inner.set_;
3167
        UniqueLock m(inner);
3168
        typename EmbeddedSet::template InsertSlotWithHash<true> f { inner.set_, std::move(*slot), hashval };
3169
        return make_rv(&inner, PolicyTraits::apply(std::move(f), elem));
3170
    }
3171
3172
    template <class... Args>
3173
    iterator emplace_hint_with_hash(size_t hashval, const_iterator, Args&&... args) {
3174
        return emplace_with_hash(hashval, std::forward<Args>(args)...).first;
3175
    }
3176
3177
    // --------------------------------------------------------------------
3178
    // end of phmap expension
3179
    // --------------------------------------------------------------------
3180
3181
    template <class K, class... Args>
3182
    std::pair<iterator, bool> emplace_decomposable_with_hash(const K& key, size_t hashval, Args&&... args)
3183
    {
3184
        Inner& inner   = sets_[subidx(hashval)];
3185
        auto&  set     = inner.set_;
3186
        UniqueLock m(inner);
3187
        
3188
        size_t offset = set._find_key(key, hashval);
3189
        if (offset == (size_t)-1) {
3190
            offset = set.prepare_insert(hashval);
3191
            set.emplace_at(offset, std::forward<Args>(args)...);
3192
            set.set_ctrl(offset, H2(hashval));
3193
            return make_rv(&inner, {set.iterator_at(offset), true});
3194
        }
3195
        return make_rv(&inner, {set.iterator_at(offset), false});
3196
    }
3197
3198
    template <class K, class... Args>
3199
    std::pair<iterator, bool> emplace_decomposable(const K& key, Args&&... args)
3200
    {
3201
        return emplace_decomposable_with_hash(key, this->hash(key), std::forward<Args>(args)...);
3202
    }
3203
3204
    struct EmplaceDecomposable 
3205
    {
3206
        template <class K, class... Args>
3207
        std::pair<iterator, bool> operator()(const K& key, Args&&... args) const {
3208
            return s.emplace_decomposable(key, std::forward<Args>(args)...);
3209
        }
3210
        parallel_hash_set& s;
3211
    };
3212
3213
    // This overload kicks in if we can deduce the key from args. This enables us
3214
    // to avoid constructing value_type if an entry with the same key already
3215
    // exists.
3216
    //
3217
    // For example:
3218
    //
3219
    //   flat_hash_map<std::string, std::string> m = {{"abc", "def"}};
3220
    //   // Creates no std::string copies and makes no heap allocations.
3221
    //   m.emplace("abc", "xyz");
3222
    // --------------------------------------------------------------------
3223
    template <class... Args, typename std::enable_if<IsDecomposable<Args...>::value, int>::type = 0>
3224
    std::pair<iterator, bool> emplace(Args&&... args) {
3225
        return PolicyTraits::apply(EmplaceDecomposable{*this}, std::forward<Args>(args)...);
3226
    }
3227
3228
    // This overload kicks in if we cannot deduce the key from args. It constructs
3229
    // value_type unconditionally and then either moves it into the table or
3230
    // destroys.
3231
    // --------------------------------------------------------------------
3232
    template <class... Args, typename std::enable_if<!IsDecomposable<Args...>::value, int>::type = 0>
3233
    std::pair<iterator, bool> emplace(Args&&... args) {
3234
        typename phmap::aligned_storage<sizeof(slot_type), alignof(slot_type)>::type raw;
3235
        slot_type* slot = reinterpret_cast<slot_type*>(&raw);
3236
        PolicyTraits::construct(&alloc_ref(), slot, std::forward<Args>(args)...);
3237
3238
        const auto& elem = PolicyTraits::element(slot);
3239
        size_t hashval   = this->hash(PolicyTraits::key(slot));
3240
        Inner& inner     = sets_[subidx(hashval)];
3241
        auto&  set       = inner.set_;
3242
        UniqueLock m(inner);
3243
        typename EmbeddedSet::template InsertSlotWithHash<true> f { inner.set_, std::move(*slot), hashval };
3244
        return make_rv(&inner, PolicyTraits::apply(std::move(f), elem));
3245
    }
3246
3247
    template <class... Args>
3248
    iterator emplace_hint(const_iterator, Args&&... args) {
3249
        return emplace(std::forward<Args>(args)...).first;
3250
    }
3251
3252
    iterator make_iterator(Inner* inner, const EmbeddedIterator it)
3253
    {
3254
        if (it == inner->set_.end())
3255
            return iterator();
3256
        return iterator(inner, &sets_[0] + num_tables, it);
3257
    }
3258
3259
    std::pair<iterator, bool> make_rv(Inner* inner, 
3260
                                      const std::pair<EmbeddedIterator, bool>& res)
3261
    {
3262
        return {iterator(inner, &sets_[0] + num_tables, res.first), res.second};
3263
    }
3264
3265
    // lazy_emplace
3266
    // ------------
3267
    template <class K = key_type, class F>
3268
    iterator lazy_emplace_with_hash(const key_arg<K>& key, size_t hashval, F&& f) {
3269
        Inner& inner = sets_[subidx(hashval)];
3270
        auto&  set   = inner.set_;
3271
        UniqueLock m(inner);
3272
        size_t offset = set._find_key(key, hashval);
3273
        if (offset == (size_t)-1) {
3274
            offset = set.prepare_insert(hashval);
3275
            set.lazy_emplace_at(offset, std::forward<F>(f));
3276
            set.set_ctrl(offset, H2(hashval));
3277
        }
3278
        return make_iterator(&inner, set.iterator_at(offset));
3279
    }
3280
3281
    template <class K = key_type, class F>
3282
    iterator lazy_emplace(const key_arg<K>& key, F&& f) {
3283
        return lazy_emplace_with_hash(key, this->hash(key), std::forward<F>(f));
3284
    }
3285
    
3286
    // emplace_single
3287
    // --------------
3288
    template <class K = key_type, class F>
3289
    void emplace_single_with_hash(const key_arg<K>& key, size_t hashval, F&& f) {
3290
        Inner& inner = sets_[subidx(hashval)];
3291
        auto&  set   = inner.set_;
3292
        UniqueLock m(inner);
3293
        set.emplace_single_with_hash(key, hashval, std::forward<F>(f));
3294
    }
3295
3296
    template <class K = key_type, class F>
3297
    void emplace_single(const key_arg<K>& key, F&& f) {
3298
        emplace_single_with_hash<K, F>(key, this->hash(key), std::forward<F>(f));
3299
    }
3300
3301
    // if set contains key, lambda is called with the value_type (under read lock protection),
3302
    // and if_contains returns true. This is a const API and lambda should not modify the value
3303
    // -----------------------------------------------------------------------------------------
3304
    template <class K = key_type, class F>
3305
    bool if_contains_with_hash(const key_arg<K>& key, size_t hashval, F&& f) const {
3306
        return const_cast<parallel_hash_set*>(this)->template 
3307
            modify_if_impl_with_hash<K, F, SharedLock>(key, hashval, std::forward<F>(f));
3308
    }
3309
3310
    // if set contains key, lambda is called with the value_type (under read lock protection),
3311
    // and if_contains returns true. This is a const API and lambda should not modify the value
3312
    // -----------------------------------------------------------------------------------------
3313
    template <class K = key_type, class F>
3314
    bool if_contains(const key_arg<K>& key, F&& f) const {
3315
        return if_contains_with_hash<K, F>(key, this->hash(key), std::forward<F>(f));
3316
    }
3317
3318
    // if set contains key, lambda is called with the value_type  without read lock protection,
3319
    // and if_contains_unsafe returns true. This is a const API and lambda should not modify the value
3320
    // This should be used only if we know that no other thread may be mutating the set at the time.
3321
    // -----------------------------------------------------------------------------------------
3322
    template <class K = key_type, class F>
3323
    bool if_contains_unsafe(const key_arg<K>& key, F&& f) const {
3324
        return const_cast<parallel_hash_set*>(this)->template 
3325
            modify_if_impl<K, F, LockableBaseImpl<phmap::NullMutex>::DoNothing>(key, std::forward<F>(f));
3326
    }
3327
3328
    // if map contains key, lambda is called with the value_type  (under write lock protection),
3329
    // and modify_if returns true. This is a non-const API and lambda is allowed to modify the mapped value
3330
    // ----------------------------------------------------------------------------------------------------
3331
    template <class K = key_type, class F>
3332
    bool modify_if(const key_arg<K>& key, F&& f) {
3333
        return modify_if_impl<K, F, UniqueLock>(key, std::forward<F>(f));
3334
    }
3335
3336
    // -----------------------------------------------------------------------------------------
3337
    template <class K = key_type, class F, class L>
3338
    bool modify_if_impl_with_hash(const key_arg<K>& key, size_t hashval, F&& f) {
3339
#if __cplusplus >= 201703L
3340
        static_assert(std::is_invocable<F, value_type&>::value);
3341
#endif
3342
        L m;
3343
        auto ptr = this->template find_ptr<K, L>(key, hashval, m);
3344
        if (ptr == nullptr)
3345
            return false;
3346
        std::forward<F>(f)(*ptr);
3347
        return true;
3348
    }
3349
3350
    // -----------------------------------------------------------------------------------------
3351
    template <class K = key_type, class F, class L>
3352
    bool modify_if_impl(const key_arg<K>& key, F&& f) {
3353
        return modify_if_impl_with_hash<K, F, L>(key, this->hash(key), std::forward<F>(f));
3354
    }
3355
3356
    // if map contains key, lambda is called with the mapped value  (under write lock protection).
3357
    // If the lambda returns true, the key is subsequently erased from the map (the write lock
3358
    // is only released after erase).
3359
    // returns true if key was erased, false otherwise.
3360
    // ----------------------------------------------------------------------------------------------------
3361
    template <class K = key_type, class F>
3362
    bool erase_if(const key_arg<K>& key, F&& f) {
3363
        return !!erase_if_impl<K, F, ReadWriteLock>(key, std::forward<F>(f));
3364
    }
3365
3366
    template <class K = key_type, class F, class L>
3367
    size_type erase_if_impl(const key_arg<K>& key, F&& f) {
3368
#if __cplusplus >= 201703L
3369
        static_assert(std::is_invocable<F, value_type&>::value);
3370
#endif
3371
        auto hashval = this->hash(key);
3372
        Inner& inner = sets_[subidx(hashval)];
3373
        auto& set = inner.set_;
3374
        L m(inner);
3375
        auto it = set.find(key, hashval);
3376
        if (it == set.end())
3377
            return 0;
3378
        if (m.switch_to_unique()) {
3379
            // we did an unlock/lock, need to call `find()` again
3380
            it = set.find(key, hashval);
3381
            if (it == set.end())
3382
                return 0;
3383
        }
3384
        if (std::forward<F>(f)(const_cast<value_type &>(*it)))
3385
        {
3386
            set._erase(it);
3387
            return 1;
3388
        }
3389
        return 0;
3390
    }
3391
3392
    // if map already  contains key, the first lambda is called with the mapped value (under 
3393
    // write lock protection) and can update the mapped value.
3394
    // if map does not contains key, the second lambda is called and it should invoke the 
3395
    // passed constructor to construct the value
3396
    // returns true if key was not already present, false otherwise.
3397
    // ---------------------------------------------------------------------------------------
3398
    template <class K = key_type, class FExists, class FEmplace>
3399
    bool lazy_emplace_l_with_hash(const key_arg<K>& key, size_t hashval, FExists&& fExists, FEmplace&& fEmplace) {
3400
        UniqueLock m;
3401
        auto res = this->find_or_prepare_insert_with_hash(hashval, key, m);
3402
        Inner* inner = std::get<0>(res);
3403
        if (std::get<2>(res)) {
3404
            // key not found. call fEmplace lambda which should invoke passed constructor
3405
            inner->set_.lazy_emplace_at(std::get<1>(res), std::forward<FEmplace>(fEmplace));
3406
            inner->set_.set_ctrl(std::get<1>(res), H2(hashval));
3407
        } else {
3408
            // key found. Call fExists lambda. In case of the set, non "key" part of value_type can be changed
3409
            auto it = this->iterator_at(inner, inner->set_.iterator_at(std::get<1>(res)));
3410
            std::forward<FExists>(fExists)(const_cast<value_type &>(*it)); 
3411
        }
3412
        return std::get<2>(res);
3413
    }
3414
3415
    // if map already  contains key, the first lambda is called with the mapped value (under
3416
    // write lock protection) and can update the mapped value.
3417
    // if map does not contains key, the second lambda is called and it should invoke the
3418
    // passed constructor to construct the value
3419
    // returns true if key was not already present, false otherwise.
3420
    // ---------------------------------------------------------------------------------------
3421
    template <class K = key_type, class FExists, class FEmplace>
3422
    bool lazy_emplace_l(const key_arg<K>& key, FExists&& fExists, FEmplace&& fEmplace) {
3423
        return lazy_emplace_l_with_hash<K, FExists, FEmplace>(key, this->hash(key),
3424
                                                              std::forward<FExists>(fExists),
3425
                                                              std::forward<FEmplace>(fEmplace));
3426
    }
3427
3428
    // Extension API: support iterating over all values
3429
    //
3430
    // flat_hash_set<std::string> s;
3431
    // s.insert(...);
3432
    // s.for_each([](auto const & key) {
3433
    //    // Safely iterates over all the keys
3434
    // });
3435
    template <class F>
3436
    void for_each(F&& fCallback) const {
3437
        for (auto const& inner : sets_) {
3438
            SharedLock m(const_cast<Inner&>(inner));
3439
            std::for_each(inner.set_.begin(), inner.set_.end(), fCallback);
3440
        }
3441
    }
3442
3443
    // this version allows to modify the values
3444
    template <class F>
3445
    void for_each_m(F&& fCallback) {
3446
        for (auto& inner : sets_) {
3447
            UniqueLock m(inner);
3448
            std::for_each(inner.set_.begin(), inner.set_.end(), fCallback);
3449
        }
3450
    }
3451
3452
#if __cplusplus >= 201703L
3453
    template <class ExecutionPolicy, class F>
3454
    void for_each(ExecutionPolicy&& policy, F&& fCallback) const {
3455
        std::for_each(
3456
            std::forward<ExecutionPolicy>(policy), sets_.begin(), sets_.end(),
3457
            [&](auto const& inner) {
3458
                SharedLock m(const_cast<Inner&>(inner));
3459
                std::for_each(inner.set_.begin(), inner.set_.end(), fCallback);
3460
            }
3461
        );
3462
    }
3463
3464
    template <class ExecutionPolicy, class F>
3465
    void for_each_m(ExecutionPolicy&& policy, F&& fCallback) {
3466
        std::for_each(
3467
            std::forward<ExecutionPolicy>(policy), sets_.begin(), sets_.end(),
3468
            [&](auto& inner) {
3469
                UniqueLock m(inner);
3470
                std::for_each(inner.set_.begin(), inner.set_.end(), fCallback);
3471
            }
3472
        );
3473
    }
3474
#endif
3475
3476
    // Extension API: access internal submaps by index
3477
    // under lock protection
3478
    // ex: m.with_submap(i, [&](const Map::EmbeddedSet& set) {
3479
    //        for (auto& p : set) { ...; }});
3480
    // -------------------------------------------------
3481
    template <class F>
3482
    void with_submap(size_t idx, F&& fCallback) const {
3483
        const Inner& inner     = sets_[idx];
3484
        const auto&  set = inner.set_;
3485
        SharedLock m(const_cast<Inner&>(inner));
3486
        fCallback(set);
3487
    }
3488
3489
    template <class F>
3490
    void with_submap_m(size_t idx, F&& fCallback) {
3491
        Inner& inner   = sets_[idx];
3492
        auto&  set     = inner.set_;
3493
        UniqueLock m(inner);
3494
        fCallback(set);
3495
    }
3496
3497
    // unsafe, for internal use only
3498
    Inner& get_inner(size_t idx) {
3499
        return  sets_[idx];
3500
    }
3501
3502
    const Inner& get_inner(size_t idx) const {
3503
        return  sets_[idx];
3504
    }
3505
3506
    // Extension API: support for heterogeneous keys.
3507
    //
3508
    //   std::unordered_set<std::string> s;
3509
    //   // Turns "abc" into std::string.
3510
    //   s.erase("abc");
3511
    //
3512
    //   flat_hash_set<std::string> s;
3513
    //   // Uses "abc" directly without copying it into std::string.
3514
    //   s.erase("abc");
3515
    //
3516
    // --------------------------------------------------------------------
3517
    template <class K = key_type>
3518
    size_type erase(const key_arg<K>& key) {
3519
        auto always_erase =  [](const value_type&){ return true; };
3520
        return erase_if_impl<K, decltype(always_erase), ReadWriteLock>(key, std::move(always_erase));
3521
    }
3522
3523
    // --------------------------------------------------------------------
3524
    iterator erase(const_iterator cit) { return erase(cit.iter_); }
3525
3526
    // Erases the element pointed to by `it`.  Unlike `std::unordered_set::erase`,
3527
    // this method returns void to reduce algorithmic complexity to O(1).  In
3528
    // order to erase while iterating across a map, use the following idiom (which
3529
    // also works for standard containers):
3530
    //
3531
    // for (auto it = m.begin(), end = m.end(); it != end;) {
3532
    //   if (<pred>) {
3533
    //     m._erase(it++);
3534
    //   } else {
3535
    //     ++it;
3536
    //   }
3537
    // }
3538
    //
3539
    // Do not use erase APIs taking iterators when accessing the map concurrently
3540
    // --------------------------------------------------------------------
3541
    void _erase(iterator it) {
3542
        Inner* inner = it.inner_;
3543
        assert(inner != nullptr);
3544
        auto&  set   = inner->set_;
3545
        // UniqueLock m(*inner); // don't lock here 
3546
        
3547
        set._erase(it.it_);
3548
    }
3549
    void _erase(const_iterator cit) { _erase(cit.iter_); }
3550
3551
    // This overload is necessary because otherwise erase<K>(const K&) would be
3552
    // a better match if non-const iterator is passed as an argument.
3553
    // Do not use erase APIs taking iterators when accessing the map concurrently
3554
    // --------------------------------------------------------------------
3555
    iterator erase(iterator it) { _erase(it++); return it; }
3556
3557
    iterator erase(const_iterator first, const_iterator last) {
3558
        while (first != last) {
3559
            _erase(first++);
3560
        }
3561
        return last.iter_;
3562
    }
3563
3564
    // Moves elements from `src` into `this`.
3565
    // If the element already exists in `this`, it is left unmodified in `src`.
3566
    // Do not use erase APIs taking iterators when accessing the map concurrently
3567
    // --------------------------------------------------------------------
3568
    template <typename E = Eq>
3569
    void merge(parallel_hash_set<N, RefSet, Mtx_, Policy, Hash, E, Alloc>& src) {  // NOLINT
3570
        assert(this != &src);
3571
        if (this != &src)
3572
        {
3573
            for (size_t i=0; i<num_tables; ++i)
3574
            {
3575
                typename Lockable::UniqueLocks l(sets_[i], src.sets_[i]);
3576
                sets_[i].set_.merge(src.sets_[i].set_);
3577
            }
3578
        }
3579
    }
3580
3581
    template <typename E = Eq>
3582
    void merge(parallel_hash_set<N, RefSet, Mtx_, Policy, Hash, E, Alloc>&& src) {
3583
        merge(src);
3584
    }
3585
3586
    node_type extract(const_iterator position) {
3587
        return position.iter_.inner_->set_.extract(EmbeddedConstIterator(position.iter_.it_));
3588
    }
3589
3590
    template <
3591
        class K = key_type,
3592
        typename std::enable_if<!std::is_same<K, iterator>::value, int>::type = 0>
3593
    node_type extract(const key_arg<K>& key) {
3594
        UniqueLock m;
3595
        auto it = this->template find<K, UniqueLock>(key, this->hash(key), m);
3596
        return it == end() ? node_type() : extract(const_iterator{it});
3597
    }
3598
3599
    template<class Mtx2_>
3600
    void swap(parallel_hash_set<N, RefSet, Mtx2_, Policy, Hash, Eq, Alloc>& that)
3601
        noexcept(IsNoThrowSwappable<EmbeddedSet>() &&
3602
                 (!AllocTraits::propagate_on_container_swap::value ||
3603
                  IsNoThrowSwappable<allocator_type>(typename AllocTraits::propagate_on_container_swap{})))
3604
    {
3605
        using std::swap;
3606
        using Lockable2 = phmap::LockableImpl<Mtx2_>;
3607
         
3608
        for (size_t i=0; i<num_tables; ++i)
3609
        {
3610
            typename Lockable::UniqueLock l(sets_[i]);
3611
            typename Lockable2::UniqueLock l2(that.get_inner(i));
3612
            swap(sets_[i].set_, that.get_inner(i).set_);
3613
        }
3614
    }
3615
3616
    void rehash(size_t n) {
3617
        size_t nn = n / num_tables;
3618
        for (auto& inner : sets_)
3619
        {
3620
            UniqueLock m(inner);
3621
            inner.set_.rehash(nn);
3622
        }
3623
    }
3624
3625
    void reserve(size_t n) 
3626
    {
3627
        if (n <= capacity())
3628
            return;
3629
        size_t target = GrowthToLowerboundCapacity(n);
3630
        size_t normalized = num_tables * NormalizeCapacity(n / num_tables);
3631
        rehash(normalized > target ? normalized : target); 
3632
    }
3633
3634
    // Extension API: support for heterogeneous keys.
3635
    //
3636
    //   std::unordered_set<std::string> s;
3637
    //   // Turns "abc" into std::string.
3638
    //   s.count("abc");
3639
    //
3640
    //   ch_set<std::string> s;
3641
    //   // Uses "abc" directly without copying it into std::string.
3642
    //   s.count("abc");
3643
    // --------------------------------------------------------------------
3644
    template <class K = key_type>
3645
    size_t count(const key_arg<K>& key) const {
3646
        return find(key) == end() ? 0 : 1;
3647
    }
3648
3649
    // Issues CPU prefetch instructions for the memory needed to find or insert
3650
    // a key.  Like all lookup functions, this support heterogeneous keys.
3651
    //
3652
    // NOTE: This is a very low level operation and should not be used without
3653
    // specific benchmarks indicating its importance.
3654
    // --------------------------------------------------------------------
3655
    void prefetch_hash(size_t hashval) const {
3656
        const Inner& inner = sets_[subidx(hashval)];
3657
        const auto&  set   = inner.set_;
3658
        SharedLock m(const_cast<Inner&>(inner));
3659
        set.prefetch_hash(hashval);
3660
    }
3661
3662
    template <class K = key_type>
3663
    void prefetch(const key_arg<K>& key) const {
3664
        prefetch_hash(this->hash(key));
3665
    }
3666
3667
    // The API of find() has two extensions.
3668
    //
3669
    // 1. The hash can be passed by the user. It must be equal to the hash of the
3670
    // key.
3671
    //
3672
    // 2. The type of the key argument doesn't have to be key_type. This is so
3673
    // called heterogeneous key support.
3674
    // --------------------------------------------------------------------
3675
    template <class K = key_type>
3676
    iterator find(const key_arg<K>& key, size_t hashval) {
3677
        SharedLock m;
3678
        return find(key, hashval, m);
3679
    }
3680
3681
    template <class K = key_type>
3682
    iterator find(const key_arg<K>& key) {
3683
        return find(key, this->hash(key));
3684
    }
3685
3686
    template <class K = key_type>
3687
    const_iterator find(const key_arg<K>& key, size_t hashval) const {
3688
        return const_cast<parallel_hash_set*>(this)->find(key, hashval);
3689
    }
3690
3691
    template <class K = key_type>
3692
    const_iterator find(const key_arg<K>& key) const {
3693
        return find(key, this->hash(key));
3694
    }
3695
3696
    template <class K = key_type>
3697
    bool contains(const key_arg<K>& key) const {
3698
        return find(key) != end();
3699
    }
3700
3701
    template <class K = key_type>
3702
    bool contains(const key_arg<K>& key, size_t hashval) const {
3703
        return find(key, hashval) != end();
3704
    }
3705
3706
    template <class K = key_type>
3707
    std::pair<iterator, iterator> equal_range(const key_arg<K>& key) {
3708
        auto it = find(key);
3709
        if (it != end()) return {it, std::next(it)};
3710
        return {it, it};
3711
    }
3712
3713
    template <class K = key_type>
3714
    std::pair<const_iterator, const_iterator> equal_range(
3715
        const key_arg<K>& key) const {
3716
        auto it = find(key);
3717
        if (it != end()) return {it, std::next(it)};
3718
        return {it, it};
3719
    }
3720
3721
    size_t bucket_count() const {
3722
        size_t sz = 0;
3723
        for (const auto& inner : sets_)
3724
        {
3725
            SharedLock m(const_cast<Inner&>(inner));
3726
            sz += inner.set_.bucket_count();
3727
        }
3728
        return sz; 
3729
    }
3730
3731
    float load_factor() const {
3732
        size_t _capacity = bucket_count();
3733
        return _capacity ? static_cast<float>(static_cast<double>(size()) / _capacity) : 0;
3734
    }
3735
3736
    float max_load_factor() const { return 1.0f; }
3737
    void max_load_factor(float) {
3738
        // Does nothing.
3739
    }
3740
3741
    hasher hash_function() const { return hash_ref(); }  // warning: doesn't match internal hash - use hash() member function
3742
    key_equal key_eq() const { return eq_ref(); }
3743
    allocator_type get_allocator() const { return alloc_ref(); }
3744
3745
    friend bool operator==(const parallel_hash_set& a, const parallel_hash_set& b) {
3746
        return std::equal(a.sets_.begin(), a.sets_.end(), b.sets_.begin());
3747
    }
3748
3749
    friend bool operator!=(const parallel_hash_set& a, const parallel_hash_set& b) {
3750
        return !(a == b);
3751
    }
3752
3753
    template<class Mtx2_>
3754
    friend void swap(parallel_hash_set& a,
3755
                     parallel_hash_set<N, RefSet, Mtx2_, Policy, Hash, Eq, Alloc>& b)
3756
        noexcept(noexcept(a.swap(b)))
3757
    {
3758
        a.swap(b);
3759
    }
3760
3761
    template <class K>
3762
    size_t hash(const K& key) const {
3763
        return HashElement{hash_ref()}(key);
3764
    }
3765
3766
#if !defined(PHMAP_NON_DETERMINISTIC)
3767
    template<typename OutputArchive>
3768
    bool phmap_dump(OutputArchive& ar) const;
3769
3770
    template<typename InputArchive>
3771
    bool phmap_load(InputArchive& ar);
3772
#endif
3773
3774
private:
3775
    template <class Container, typename Enabler>
3776
    friend struct phmap::priv::hashtable_debug_internal::HashtableDebugAccess;
3777
3778
    struct FindElement 
3779
    {
3780
        template <class K, class... Args>
3781
        const_iterator operator()(const K& key, Args&&...) const {
3782
            return s.find(key);
3783
        }
3784
        const parallel_hash_set& s;
3785
    };
3786
3787
    struct HashElement 
3788
    {
3789
        template <class K, class... Args>
3790
        size_t operator()(const K& key, Args&&...) const {
3791
#if PHMAP_DISABLE_MIX
3792
            return h(key);
3793
#else
3794
            return phmap_mix<sizeof(size_t)>()(h(key));
3795
#endif
3796
        }
3797
        const hasher& h;
3798
    };
3799
3800
    template <class K1>
3801
    struct EqualElement 
3802
    {
3803
        template <class K2, class... Args>
3804
        bool operator()(const K2& lhs, Args&&...) const {
3805
            return eq(lhs, rhs);
3806
        }
3807
        const K1& rhs;
3808
        const key_equal& eq;
3809
    };
3810
3811
    // "erases" the object from the container, except that it doesn't actually
3812
    // destroy the object. It only updates all the metadata of the class.
3813
    // This can be used in conjunction with Policy::transfer to move the object to
3814
    // another place.
3815
    // --------------------------------------------------------------------
3816
    void erase_meta_only(const_iterator cit) {
3817
        auto &it = cit.iter_;
3818
        assert(it.set_ != nullptr);
3819
        it.set_.erase_meta_only(const_iterator(it.it_));
3820
    }
3821
3822
    void drop_deletes_without_resize() PHMAP_ATTRIBUTE_NOINLINE {
3823
        for (auto& inner : sets_)
3824
        {
3825
            UniqueLock m(inner);
3826
            inner.set_.drop_deletes_without_resize();
3827
        }
3828
    }
3829
3830
    bool has_element(const value_type& elem) const {
3831
        size_t hashval = PolicyTraits::apply(HashElement{hash_ref()}, elem);
3832
        Inner& inner   = sets_[subidx(hashval)];
3833
        auto&  set     = inner.set_;
3834
        SharedLock m(const_cast<Inner&>(inner));
3835
        return set.has_element(elem, hashval);
3836
    }
3837
3838
    // TODO(alkis): Optimize this assuming *this and that don't overlap.
3839
    // --------------------------------------------------------------------
3840
    template<class Mtx2_>
3841
    parallel_hash_set& move_assign(parallel_hash_set<N, RefSet, Mtx2_, Policy, Hash, Eq, Alloc>&& that, std::true_type) {
3842
        parallel_hash_set<N, RefSet, Mtx2_, Policy, Hash, Eq, Alloc> tmp(std::move(that));
3843
        swap(tmp);
3844
        return *this;
3845
    }
3846
3847
    template<class Mtx2_>
3848
    parallel_hash_set& move_assign(parallel_hash_set<N, RefSet, Mtx2_, Policy, Hash, Eq, Alloc>&& that, std::false_type) {
3849
        parallel_hash_set<N, RefSet, Mtx2_, Policy, Hash, Eq, Alloc> tmp(std::move(that), alloc_ref());
3850
        swap(tmp);
3851
        return *this;
3852
    }
3853
3854
protected:
3855
    template <class K = key_type, class L = SharedLock>
3856
    pointer find_ptr(const key_arg<K>& key, size_t hashval, L& mutexlock)
3857
    {
3858
        Inner& inner = sets_[subidx(hashval)];
3859
        auto& set = inner.set_;
3860
        mutexlock = std::move(L(inner));
3861
        return set.find_ptr(key, hashval);
3862
    }
3863
3864
    template <class K = key_type, class L = SharedLock>
3865
    iterator find(const key_arg<K>& key, size_t hashval, L& mutexlock) {
3866
        Inner& inner = sets_[subidx(hashval)];
3867
        auto& set = inner.set_;
3868
        mutexlock = std::move(L(inner));
3869
        return make_iterator(&inner, set.find(key, hashval));
3870
    }
3871
3872
    template <class K>
3873
    std::tuple<Inner*, size_t, bool> 
3874
    find_or_prepare_insert_with_hash(size_t hashval, const K& key, UniqueLock &mutexlock) {
3875
        Inner& inner = sets_[subidx(hashval)];
3876
        auto&  set   = inner.set_;
3877
        mutexlock    = std::move(UniqueLock(inner));
3878
        size_t offset = set._find_key(key, hashval);
3879
        if (offset == (size_t)-1) {
3880
            offset = set.prepare_insert(hashval);
3881
            return std::make_tuple(&inner, offset, true);
3882
        }
3883
        return std::make_tuple(&inner, offset, false);
3884
    }
3885
3886
    template <class K>
3887
    std::tuple<Inner*, size_t, bool> 
3888
    find_or_prepare_insert(const K& key, UniqueLock &mutexlock) {
3889
        return find_or_prepare_insert_with_hash<K>(this->hash(key), key, mutexlock);
3890
    }
3891
3892
    iterator iterator_at(Inner *inner, 
3893
                         const EmbeddedIterator& it) { 
3894
        return {inner, &sets_[0] + num_tables, it}; 
3895
    }
3896
    const_iterator iterator_at(Inner *inner, 
3897
                               const EmbeddedIterator& it) const { 
3898
        return {inner, &sets_[0] + num_tables, it}; 
3899
    }
3900
3901
    static size_t subidx(size_t hashval) {
3902
        return ((hashval >> 8) ^ (hashval >> 16) ^ (hashval >> 24)) & mask;
3903
    }
3904
3905
    static size_t subcnt() {
3906
        return num_tables;
3907
    }
3908
3909
private:
3910
    friend struct RawHashSetTestOnlyAccess;
3911
3912
    size_t growth_left() { 
3913
        size_t sz = 0;
3914
        for (const auto& set : sets_)
3915
            sz += set.growth_left();
3916
        return sz; 
3917
    }
3918
3919
    hasher&       hash_ref()        { return sets_[0].set_.hash_ref(); }
3920
    const hasher& hash_ref() const  { return sets_[0].set_.hash_ref(); }
3921
    key_equal&       eq_ref()       { return sets_[0].set_.eq_ref(); }
3922
    const key_equal& eq_ref() const { return sets_[0].set_.eq_ref(); }
3923
    allocator_type&  alloc_ref()    { return sets_[0].set_.alloc_ref(); }
3924
    const allocator_type& alloc_ref() const { 
3925
        return sets_[0].set_.alloc_ref();
3926
    }
3927
3928
protected:       // protected in case users want to derive fromm this
3929
    std::array<Inner, num_tables> sets_;
3930
};
3931
3932
// --------------------------------------------------------------------------
3933
// --------------------------------------------------------------------------
3934
template <size_t N,
3935
          template <class, class, class, class> class RefSet,
3936
          class Mtx_,
3937
          class Policy, class Hash, class Eq, class Alloc>
3938
class parallel_hash_map : public parallel_hash_set<N, RefSet, Mtx_, Policy, Hash, Eq, Alloc> 
3939
{
3940
    // P is Policy. It's passed as a template argument to support maps that have
3941
    // incomplete types as values, as in unordered_map<K, IncompleteType>.
3942
    // MappedReference<> may be a non-reference type.
3943
    template <class P>
3944
    using MappedReference = decltype(P::value(
3945
            std::addressof(std::declval<typename parallel_hash_map::reference>())));
3946
3947
    // MappedConstReference<> may be a non-reference type.
3948
    template <class P>
3949
    using MappedConstReference = decltype(P::value(
3950
            std::addressof(std::declval<typename parallel_hash_map::const_reference>())));
3951
3952
    using KeyArgImpl =
3953
        KeyArg<IsTransparent<Eq>::value && IsTransparent<Hash>::value>;
3954
3955
    using Base = typename parallel_hash_map::parallel_hash_set;
3956
    using Lockable      = phmap::LockableImpl<Mtx_>;
3957
    using UniqueLock    = typename Lockable::UniqueLock;
3958
    using SharedLock    = typename Lockable::SharedLock;
3959
    using ReadWriteLock = typename Lockable::ReadWriteLock;
3960
3961
public:
3962
    using key_type    = typename Policy::key_type;
3963
    using mapped_type = typename Policy::mapped_type;
3964
    using value_type  = typename Base::value_type;
3965
    template <class K>
3966
    using key_arg = typename KeyArgImpl::template type<K, key_type>;
3967
3968
    static_assert(!std::is_reference<key_type>::value, "");
3969
    // TODO(alkis): remove this assertion and verify that reference mapped_type is
3970
    // supported.
3971
    static_assert(!std::is_reference<mapped_type>::value, "");
3972
3973
    using iterator = typename parallel_hash_map::parallel_hash_set::iterator;
3974
    using const_iterator = typename parallel_hash_map::parallel_hash_set::const_iterator;
3975
3976
    parallel_hash_map() {}
3977
3978
#ifdef __INTEL_COMPILER
3979
    using Base::parallel_hash_set;
3980
#else
3981
    using parallel_hash_map::parallel_hash_set::parallel_hash_set;
3982
#endif
3983
3984
    // The last two template parameters ensure that both arguments are rvalues
3985
    // (lvalue arguments are handled by the overloads below). This is necessary
3986
    // for supporting bitfield arguments.
3987
    //
3988
    //   union { int n : 1; };
3989
    //   flat_hash_map<int, int> m;
3990
    //   m.insert_or_assign(n, n);
3991
    template <class K = key_type, class V = mapped_type, K* = nullptr,
3992
              V* = nullptr>
3993
    std::pair<iterator, bool> insert_or_assign(key_arg<K>&& k, V&& v) {
3994
        return insert_or_assign_impl(std::forward<K>(k), std::forward<V>(v));
3995
    }
3996
3997
    template <class K = key_type, class V = mapped_type, K* = nullptr>
3998
    std::pair<iterator, bool> insert_or_assign(key_arg<K>&& k, const V& v) {
3999
        return insert_or_assign_impl(std::forward<K>(k), v);
4000
    }
4001
4002
    template <class K = key_type, class V = mapped_type, V* = nullptr>
4003
    std::pair<iterator, bool> insert_or_assign(const key_arg<K>& k, V&& v) {
4004
        return insert_or_assign_impl(k, std::forward<V>(v));
4005
    }
4006
4007
    template <class K = key_type, class V = mapped_type>
4008
    std::pair<iterator, bool> insert_or_assign(const key_arg<K>& k, const V& v) {
4009
        return insert_or_assign_impl(k, v);
4010
    }
4011
4012
    template <class K = key_type, class V = mapped_type, K* = nullptr,
4013
              V* = nullptr>
4014
    iterator insert_or_assign(const_iterator, key_arg<K>&& k, V&& v) {
4015
        return insert_or_assign(std::forward<K>(k), std::forward<V>(v)).first;
4016
    }
4017
4018
    template <class K = key_type, class V = mapped_type, K* = nullptr>
4019
    iterator insert_or_assign(const_iterator, key_arg<K>&& k, const V& v) {
4020
        return insert_or_assign(std::forward<K>(k), v).first;
4021
    }
4022
4023
    template <class K = key_type, class V = mapped_type, V* = nullptr>
4024
    iterator insert_or_assign(const_iterator, const key_arg<K>& k, V&& v) {
4025
        return insert_or_assign(k, std::forward<V>(v)).first;
4026
    }
4027
4028
    template <class K = key_type, class V = mapped_type>
4029
    iterator insert_or_assign(const_iterator, const key_arg<K>& k, const V& v) {
4030
        return insert_or_assign(k, v).first;
4031
    }
4032
4033
    template <class K = key_type, class... Args,
4034
              typename std::enable_if<
4035
                  !std::is_convertible<K, const_iterator>::value, int>::type = 0,
4036
              K* = nullptr>
4037
    std::pair<iterator, bool> try_emplace(key_arg<K>&& k, Args&&... args) {
4038
        return try_emplace_impl(std::forward<K>(k), std::forward<Args>(args)...);
4039
    }
4040
4041
    template <class K = key_type, class... Args,
4042
              typename std::enable_if<
4043
                  !std::is_convertible<K, const_iterator>::value, int>::type = 0>
4044
    std::pair<iterator, bool> try_emplace(const key_arg<K>& k, Args&&... args) {
4045
        return try_emplace_impl(k, std::forward<Args>(args)...);
4046
    }
4047
4048
    template <class K = key_type, class... Args, K* = nullptr>
4049
    iterator try_emplace(const_iterator, key_arg<K>&& k, Args&&... args) {
4050
        return try_emplace(std::forward<K>(k), std::forward<Args>(args)...).first;
4051
    }
4052
4053
    template <class K = key_type, class... Args>
4054
    iterator try_emplace(const_iterator, const key_arg<K>& k, Args&&... args) {
4055
        return try_emplace(k, std::forward<Args>(args)...).first;
4056
    }
4057
4058
    template <class K = key_type, class P = Policy>
4059
    MappedReference<P> at(const key_arg<K>& key) {
4060
        auto it = this->find(key);
4061
        if (it == this->end()) 
4062
            phmap::base_internal::ThrowStdOutOfRange("phmap at(): lookup non-existent key");
4063
        return Policy::value(&*it);
4064
    }
4065
4066
    template <class K = key_type, class P = Policy>
4067
    MappedConstReference<P> at(const key_arg<K>& key) const {
4068
        auto it = this->find(key);
4069
        if (it == this->end()) 
4070
            phmap::base_internal::ThrowStdOutOfRange("phmap at(): lookup non-existent key");
4071
        return Policy::value(&*it);
4072
    }
4073
4074
    // ----------- phmap extensions --------------------------
4075
4076
    template <class K = key_type, class... Args,
4077
              typename std::enable_if<
4078
                  !std::is_convertible<K, const_iterator>::value, int>::type = 0,
4079
              K* = nullptr>
4080
    std::pair<iterator, bool> try_emplace_with_hash(size_t hashval, key_arg<K>&& k, Args&&... args) {
4081
        return try_emplace_impl_with_hash(hashval, std::forward<K>(k), std::forward<Args>(args)...);
4082
    }
4083
4084
    template <class K = key_type, class... Args,
4085
              typename std::enable_if<
4086
                  !std::is_convertible<K, const_iterator>::value, int>::type = 0>
4087
    std::pair<iterator, bool> try_emplace_with_hash(size_t hashval, const key_arg<K>& k, Args&&... args) {
4088
        return try_emplace_impl_with_hash(hashval, k, std::forward<Args>(args)...);
4089
    }
4090
4091
    template <class K = key_type, class... Args, K* = nullptr>
4092
    iterator try_emplace_with_hash(size_t hashval, const_iterator, key_arg<K>&& k, Args&&... args) {
4093
        return try_emplace_with_hash(hashval, std::forward<K>(k), std::forward<Args>(args)...).first;
4094
    }
4095
4096
    template <class K = key_type, class... Args>
4097
    iterator try_emplace_with_hash(size_t hashval, const_iterator, const key_arg<K>& k, Args&&... args) {
4098
        return try_emplace_with_hash(hashval, k, std::forward<Args>(args)...).first;
4099
    }
4100
4101
    // if map does not contains key, it is inserted and the mapped value is value-constructed 
4102
    // with the provided arguments (if any), as with try_emplace. 
4103
    // if map already  contains key, then the lambda is called with the mapped value (under 
4104
    // write lock protection) and can update the mapped value.
4105
    // returns true if key was not already present, false otherwise.
4106
    // ---------------------------------------------------------------------------------------
4107
    template <class K = key_type, class F, class... Args>
4108
    bool try_emplace_l(K&& k, F&& f, Args&&... args) {
4109
        size_t hashval = this->hash(k);
4110
        UniqueLock m;
4111
        auto res = this->find_or_prepare_insert_with_hash(hashval, k, m);
4112
        typename Base::Inner *inner = std::get<0>(res);
4113
        if (std::get<2>(res)) {
4114
            inner->set_.emplace_at(std::get<1>(res), std::piecewise_construct,
4115
                                   std::forward_as_tuple(std::forward<K>(k)),
4116
                                   std::forward_as_tuple(std::forward<Args>(args)...));
4117
            inner->set_.set_ctrl(std::get<1>(res), H2(hashval));
4118
        } else {
4119
            auto it = this->iterator_at(inner, inner->set_.iterator_at(std::get<1>(res)));
4120
            // call lambda. in case of the set, non "key" part of value_type can be changed
4121
            std::forward<F>(f)(const_cast<value_type &>(*it));
4122
        }
4123
        return std::get<2>(res);
4124
    }
4125
4126
    // returns {pointer, bool} instead of {iterator, bool} per try_emplace.
4127
    // useful for node-based containers, since the pointer is not invalidated by concurrent insert etc.
4128
    template <class K = key_type, class... Args>
4129
    std::pair<typename parallel_hash_map::parallel_hash_set::pointer, bool> try_emplace_p(K&& k, Args&&... args) {
4130
        size_t hashval = this->hash(k);
4131
        UniqueLock m;
4132
        auto res = this->find_or_prepare_insert_with_hash(hashval, k, m);
4133
        typename Base::Inner *inner = std::get<0>(res);
4134
        if (std::get<2>(res)) {
4135
            inner->set_.emplace_at(std::get<1>(res), std::piecewise_construct,
4136
                                   std::forward_as_tuple(std::forward<K>(k)),
4137
                                   std::forward_as_tuple(std::forward<Args>(args)...));
4138
            inner->set_.set_ctrl(std::get<1>(res), H2(hashval));
4139
        }
4140
        auto it = this->iterator_at(inner, inner->set_.iterator_at(std::get<1>(res)));
4141
        return {&*it, std::get<2>(res)};
4142
    }
4143
4144
    // ----------- end of phmap extensions --------------------------
4145
4146
    template <class K = key_type, class P = Policy, K* = nullptr>
4147
    MappedReference<P> operator[](key_arg<K>&& key) {
4148
        return Policy::value(&*try_emplace(std::forward<K>(key)).first);
4149
    }
4150
4151
    template <class K = key_type, class P = Policy>
4152
    MappedReference<P> operator[](const key_arg<K>& key) {
4153
        return Policy::value(&*try_emplace(key).first);
4154
    }
4155
4156
private:
4157
4158
    template <class K, class V>
4159
    std::pair<iterator, bool> insert_or_assign_impl(K&& k, V&& v) {
4160
        size_t hashval = this->hash(k);
4161
        UniqueLock m;
4162
        auto res = this->find_or_prepare_insert_with_hash(hashval, k, m);
4163
        typename Base::Inner *inner = std::get<0>(res);
4164
        if (std::get<2>(res)) {
4165
            inner->set_.emplace_at(std::get<1>(res), std::forward<K>(k), std::forward<V>(v));
4166
            inner->set_.set_ctrl(std::get<1>(res), H2(hashval));
4167
        } else
4168
            Policy::value(&*inner->set_.iterator_at(std::get<1>(res))) = std::forward<V>(v);
4169
        return {this->iterator_at(inner, inner->set_.iterator_at(std::get<1>(res))), 
4170
                std::get<2>(res)};
4171
    }
4172
4173
    template <class K = key_type, class... Args>
4174
    std::pair<iterator, bool> try_emplace_impl(K&& k, Args&&... args) {
4175
        return try_emplace_impl_with_hash(this->hash(k), std::forward<K>(k),
4176
                                          std::forward<Args>(args)...);
4177
    }
4178
4179
    template <class K = key_type, class... Args>
4180
    std::pair<iterator, bool> try_emplace_impl_with_hash(size_t hashval, K&& k, Args&&... args) {
4181
        UniqueLock m;
4182
        auto res = this->find_or_prepare_insert_with_hash(hashval, k, m);
4183
        typename Base::Inner *inner = std::get<0>(res);
4184
        if (std::get<2>(res)) {
4185
            inner->set_.emplace_at(std::get<1>(res), std::piecewise_construct,
4186
                                   std::forward_as_tuple(std::forward<K>(k)),
4187
                                   std::forward_as_tuple(std::forward<Args>(args)...));
4188
            inner->set_.set_ctrl(std::get<1>(res), H2(hashval));
4189
        }
4190
        return {this->iterator_at(inner, inner->set_.iterator_at(std::get<1>(res))), 
4191
                std::get<2>(res)};
4192
    }
4193
4194
    
4195
};
4196
4197
4198
// Constructs T into uninitialized storage pointed by `ptr` using the args
4199
// specified in the tuple.
4200
// ----------------------------------------------------------------------------
4201
template <class Alloc, class T, class Tuple>
4202
void ConstructFromTuple(Alloc* alloc, T* ptr, Tuple&& t) {
4203
    memory_internal::ConstructFromTupleImpl(
4204
        alloc, ptr, std::forward<Tuple>(t),
4205
        phmap::make_index_sequence<
4206
        std::tuple_size<typename std::decay<Tuple>::type>::value>());
4207
}
4208
4209
// Constructs T using the args specified in the tuple and calls F with the
4210
// constructed value.
4211
// ----------------------------------------------------------------------------
4212
template <class T, class Tuple, class F>
4213
decltype(std::declval<F>()(std::declval<T>())) WithConstructed(
4214
    Tuple&& t, F&& f) {
4215
    return memory_internal::WithConstructedImpl<T>(
4216
        std::forward<Tuple>(t),
4217
        phmap::make_index_sequence<
4218
        std::tuple_size<typename std::decay<Tuple>::type>::value>(),
4219
        std::forward<F>(f));
4220
}
4221
4222
// ----------------------------------------------------------------------------
4223
// Given arguments of an std::pair's consructor, PairArgs() returns a pair of
4224
// tuples with references to the passed arguments. The tuples contain
4225
// constructor arguments for the first and the second elements of the pair.
4226
//
4227
// The following two snippets are equivalent.
4228
//
4229
// 1. std::pair<F, S> p(args...);
4230
//
4231
// 2. auto a = PairArgs(args...);
4232
//    std::pair<F, S> p(std::piecewise_construct,
4233
//                      std::move(p.first), std::move(p.second));
4234
// ----------------------------------------------------------------------------
4235
0
inline std::pair<std::tuple<>, std::tuple<>> PairArgs() { return {}; }
4236
4237
template <class F, class S>
4238
27.0M
std::pair<std::tuple<F&&>, std::tuple<S&&>> PairArgs(F&& f, S&& s) {
4239
27.0M
  return {std::piecewise_construct, std::forward_as_tuple(std::forward<F>(f)),
4240
27.0M
          std::forward_as_tuple(std::forward<S>(s))};
4241
27.0M
}
std::__1::pair<std::__1::tuple<unsigned int const&>, std::__1::tuple<int const&> > phmap::priv::PairArgs<unsigned int const&, int const&>(unsigned int const&, int const&)
Line
Count
Source
4238
15.4M
std::pair<std::tuple<F&&>, std::tuple<S&&>> PairArgs(F&& f, S&& s) {
4239
15.4M
  return {std::piecewise_construct, std::forward_as_tuple(std::forward<F>(f)),
4240
15.4M
          std::forward_as_tuple(std::forward<S>(s))};
4241
15.4M
}
std::__1::pair<std::__1::tuple<unsigned int const&&>, std::__1::tuple<int&&> > phmap::priv::PairArgs<unsigned int const, int>(unsigned int const&&, int&&)
Line
Count
Source
4238
11.6M
std::pair<std::tuple<F&&>, std::tuple<S&&>> PairArgs(F&& f, S&& s) {
4239
11.6M
  return {std::piecewise_construct, std::forward_as_tuple(std::forward<F>(f)),
4240
11.6M
          std::forward_as_tuple(std::forward<S>(s))};
4241
11.6M
}
4242
4243
template <class F, class S>
4244
std::pair<std::tuple<const F&>, std::tuple<const S&>> PairArgs(
4245
15.4M
    const std::pair<F, S>& p) {
4246
15.4M
    return PairArgs(p.first, p.second);
4247
15.4M
}
4248
4249
template <class F, class S>
4250
11.6M
std::pair<std::tuple<F&&>, std::tuple<S&&>> PairArgs(std::pair<F, S>&& p) {
4251
11.6M
    return PairArgs(std::forward<F>(p.first), std::forward<S>(p.second));
4252
11.6M
}
4253
4254
template <class F, class S>
4255
auto PairArgs(std::piecewise_construct_t, F&& f, S&& s)
4256
    -> decltype(std::make_pair(memory_internal::TupleRef(std::forward<F>(f)),
4257
                               memory_internal::TupleRef(std::forward<S>(s)))) {
4258
    return std::make_pair(memory_internal::TupleRef(std::forward<F>(f)),
4259
                          memory_internal::TupleRef(std::forward<S>(s)));
4260
}
4261
4262
// A helper function for implementing apply() in map policies.
4263
// ----------------------------------------------------------------------------
4264
template <class F, class... Args>
4265
auto DecomposePair(F&& f, Args&&... args)
4266
    -> decltype(memory_internal::DecomposePairImpl(
4267
27.0M
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...))) {
4268
27.0M
    return memory_internal::DecomposePairImpl(
4269
27.0M
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...));
4270
27.0M
}
decltype (memory_internal::DecomposePairImpl((std::forward<phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::EmplaceDecomposable>)({parm#1}), PairArgs((std::forward<std::__1::pair<unsigned int const, int> >)({parm#2})))) phmap::priv::DecomposePair<phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::EmplaceDecomposable, std::__1::pair<unsigned int const, int> >(phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::EmplaceDecomposable&&, std::__1::pair<unsigned int const, int>&&)
Line
Count
Source
4267
11.6M
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...))) {
4268
11.6M
    return memory_internal::DecomposePairImpl(
4269
11.6M
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...));
4270
11.6M
}
decltype (memory_internal::DecomposePairImpl((std::forward<phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::EqualElement<unsigned int> >)({parm#1}), PairArgs((std::forward<std::__1::pair<unsigned int const, int>&>)({parm#2})))) phmap::priv::DecomposePair<phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::EqualElement<unsigned int>, std::__1::pair<unsigned int const, int>&>(phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::EqualElement<unsigned int>&&, std::__1::pair<unsigned int const, int>&)
Line
Count
Source
4267
13.4M
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...))) {
4268
13.4M
    return memory_internal::DecomposePairImpl(
4269
13.4M
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...));
4270
13.4M
}
decltype (memory_internal::DecomposePairImpl((std::forward<phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::HashElement>)({parm#1}), PairArgs((std::forward<std::__1::pair<unsigned int const, int>&>)({parm#2})))) phmap::priv::DecomposePair<phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::HashElement, std::__1::pair<unsigned int const, int>&>(phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::HashElement&&, std::__1::pair<unsigned int const, int>&)
Line
Count
Source
4267
1.25M
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...))) {
4268
1.25M
    return memory_internal::DecomposePairImpl(
4269
1.25M
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...));
4270
1.25M
}
decltype (memory_internal::DecomposePairImpl((std::forward<phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::HashElement>)({parm#1}), PairArgs((std::forward<std::__1::pair<unsigned int const, int> const&>)({parm#2})))) phmap::priv::DecomposePair<phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::HashElement, std::__1::pair<unsigned int const, int> const&>(phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::HashElement&&, std::__1::pair<unsigned int const, int> const&)
Line
Count
Source
4267
694k
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...))) {
4268
694k
    return memory_internal::DecomposePairImpl(
4269
694k
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...));
4270
694k
}
4271
4272
// A helper function for implementing apply() in set policies.
4273
// ----------------------------------------------------------------------------
4274
template <class F, class Arg>
4275
decltype(std::declval<F>()(std::declval<const Arg&>(), std::declval<Arg>()))
4276
DecomposeValue(F&& f, Arg&& arg) {
4277
    const auto& key = arg;
4278
    return std::forward<F>(f)(key, std::forward<Arg>(arg));
4279
}
4280
4281
4282
// --------------------------------------------------------------------------
4283
// Policy: a policy defines how to perform different operations on
4284
// the slots of the hashtable (see hash_policy_traits.h for the full interface
4285
// of policy).
4286
//
4287
// Hash: a (possibly polymorphic) functor that hashes keys of the hashtable. The
4288
// functor should accept a key and return size_t as hash. For best performance
4289
// it is important that the hash function provides high entropy across all bits
4290
// of the hash.
4291
//
4292
// Eq: a (possibly polymorphic) functor that compares two keys for equality. It
4293
// should accept two (of possibly different type) keys and return a bool: true
4294
// if they are equal, false if they are not. If two keys compare equal, then
4295
// their hash values as defined by Hash MUST be equal.
4296
//
4297
// Allocator: an Allocator [https://devdocs.io/cpp/concept/allocator] with which
4298
// the storage of the hashtable will be allocated and the elements will be
4299
// constructed and destroyed.
4300
// --------------------------------------------------------------------------
4301
template <class T>
4302
struct FlatHashSetPolicy 
4303
{
4304
    using slot_type = T;
4305
    using key_type = T;
4306
    using init_type = T;
4307
    using constant_iterators = std::true_type;
4308
    using is_flat = std::true_type;
4309
4310
    template <class Allocator, class... Args>
4311
    static void construct(Allocator* alloc, slot_type* slot, Args&&... args) {
4312
        phmap::allocator_traits<Allocator>::construct(*alloc, slot,
4313
                                                      std::forward<Args>(args)...);
4314
    }
4315
4316
    template <class Allocator>
4317
    static void destroy(Allocator* alloc, slot_type* slot) {
4318
        phmap::allocator_traits<Allocator>::destroy(*alloc, slot);
4319
    }
4320
4321
    template <class Allocator>
4322
    static void transfer(Allocator* alloc, slot_type* new_slot,
4323
                         slot_type* old_slot) {
4324
        construct(alloc, new_slot, std::move(*old_slot));
4325
        destroy(alloc, old_slot);
4326
    }
4327
4328
    static T& element(slot_type* slot) { return *slot; }
4329
4330
    template <class F, class... Args>
4331
    static decltype(phmap::priv::DecomposeValue(
4332
                        std::declval<F>(), std::declval<Args>()...))
4333
    apply(F&& f, Args&&... args) {
4334
        return phmap::priv::DecomposeValue(
4335
            std::forward<F>(f), std::forward<Args>(args)...);
4336
    }
4337
4338
    static size_t space_used(const T*) { return 0; }
4339
};
4340
4341
// --------------------------------------------------------------------------
4342
// --------------------------------------------------------------------------
4343
template <class K, class V>
4344
struct FlatHashMapPolicy 
4345
{
4346
    using slot_policy = priv::map_slot_policy<K, V>;
4347
    using slot_type = typename slot_policy::slot_type;
4348
    using key_type = K;
4349
    using mapped_type = V;
4350
    using init_type = std::pair</*non const*/ key_type, mapped_type>;
4351
    using is_flat = std::true_type;
4352
4353
    template <class Allocator, class... Args>
4354
711k
    static void construct(Allocator* alloc, slot_type* slot, Args&&... args) {
4355
711k
        slot_policy::construct(alloc, slot, std::forward<Args>(args)...);
4356
711k
    }
4357
4358
    template <class Allocator>
4359
0
    static void destroy(Allocator* alloc, slot_type* slot) {
4360
0
        slot_policy::destroy(alloc, slot);
4361
0
    }
4362
4363
    template <class Allocator>
4364
    static void transfer(Allocator* alloc, slot_type* new_slot,
4365
1.25M
                         slot_type* old_slot) {
4366
1.25M
        slot_policy::transfer(alloc, new_slot, old_slot);
4367
1.25M
    }
4368
4369
    template <class F, class... Args>
4370
    static decltype(phmap::priv::DecomposePair(
4371
                        std::declval<F>(), std::declval<Args>()...))
4372
27.0M
    apply(F&& f, Args&&... args) {
4373
27.0M
        return phmap::priv::DecomposePair(std::forward<F>(f),
4374
27.0M
                                                        std::forward<Args>(args)...);
4375
27.0M
    }
decltype (phmap::priv::DecomposePair((std::declval<phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::EmplaceDecomposable>)(), (std::declval<std::__1::pair<unsigned int const, int> >)())) phmap::priv::FlatHashMapPolicy<unsigned int, int>::apply<phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::EmplaceDecomposable, std::__1::pair<unsigned int const, int> >(phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::EmplaceDecomposable&&, std::__1::pair<unsigned int const, int>&&)
Line
Count
Source
4372
11.6M
    apply(F&& f, Args&&... args) {
4373
11.6M
        return phmap::priv::DecomposePair(std::forward<F>(f),
4374
11.6M
                                                        std::forward<Args>(args)...);
4375
11.6M
    }
decltype (phmap::priv::DecomposePair((std::declval<phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::EqualElement<unsigned int> >)(), (std::declval<std::__1::pair<unsigned int const, int>&>)())) phmap::priv::FlatHashMapPolicy<unsigned int, int>::apply<phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::EqualElement<unsigned int>, std::__1::pair<unsigned int const, int>&>(phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::EqualElement<unsigned int>&&, std::__1::pair<unsigned int const, int>&)
Line
Count
Source
4372
13.4M
    apply(F&& f, Args&&... args) {
4373
13.4M
        return phmap::priv::DecomposePair(std::forward<F>(f),
4374
13.4M
                                                        std::forward<Args>(args)...);
4375
13.4M
    }
decltype (phmap::priv::DecomposePair((std::declval<phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::HashElement>)(), (std::declval<std::__1::pair<unsigned int const, int>&>)())) phmap::priv::FlatHashMapPolicy<unsigned int, int>::apply<phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::HashElement, std::__1::pair<unsigned int const, int>&>(phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::HashElement&&, std::__1::pair<unsigned int const, int>&)
Line
Count
Source
4372
1.25M
    apply(F&& f, Args&&... args) {
4373
1.25M
        return phmap::priv::DecomposePair(std::forward<F>(f),
4374
1.25M
                                                        std::forward<Args>(args)...);
4375
1.25M
    }
decltype (phmap::priv::DecomposePair((std::declval<phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::HashElement>)(), (std::declval<std::__1::pair<unsigned int const, int> const&>)())) phmap::priv::FlatHashMapPolicy<unsigned int, int>::apply<phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::HashElement, std::__1::pair<unsigned int const, int> const&>(phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::HashElement&&, std::__1::pair<unsigned int const, int> const&)
Line
Count
Source
4372
694k
    apply(F&& f, Args&&... args) {
4373
694k
        return phmap::priv::DecomposePair(std::forward<F>(f),
4374
694k
                                                        std::forward<Args>(args)...);
4375
694k
    }
4376
4377
    static size_t space_used(const slot_type*) { return 0; }
4378
4379
16.0M
    static std::pair<const K, V>& element(slot_type* slot) { return slot->value; }
phmap::priv::FlatHashMapPolicy<unsigned int, int>::element(phmap::priv::map_slot_type<unsigned int, int>*)
Line
Count
Source
4379
16.0M
    static std::pair<const K, V>& element(slot_type* slot) { return slot->value; }
Unexecuted instantiation: phmap::priv::FlatHashMapPolicy<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >::element(phmap::priv::map_slot_type<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >*)
4380
4381
    static V& value(std::pair<const K, V>* kv) { return kv->second; }
4382
    static const V& value(const std::pair<const K, V>* kv) { return kv->second; }
4383
};
4384
4385
template <class Reference, class Policy>
4386
struct node_hash_policy {
4387
    static_assert(std::is_lvalue_reference<Reference>::value, "");
4388
4389
    using slot_type = typename std::remove_cv<
4390
        typename std::remove_reference<Reference>::type>::type*;
4391
4392
    template <class Alloc, class... Args>
4393
    static void construct(Alloc* alloc, slot_type* slot, Args&&... args) {
4394
        *slot = Policy::new_element(alloc, std::forward<Args>(args)...);
4395
    }
4396
4397
    template <class Alloc>
4398
    static void destroy(Alloc* alloc, slot_type* slot) {
4399
        Policy::delete_element(alloc, *slot);
4400
    }
4401
4402
    template <class Alloc>
4403
    static void transfer(Alloc*, slot_type* new_slot, slot_type* old_slot) {
4404
        *new_slot = *old_slot;
4405
    }
4406
4407
    static size_t space_used(const slot_type* slot) {
4408
        if (slot == nullptr) return Policy::element_space_used(nullptr);
4409
        return Policy::element_space_used(*slot);
4410
    }
4411
4412
    static Reference element(slot_type* slot) { return **slot; }
4413
4414
    template <class T, class P = Policy>
4415
    static auto value(T* elem) -> decltype(P::value(elem)) {
4416
        return P::value(elem);
4417
    }
4418
4419
    template <class... Ts, class P = Policy>
4420
    static auto apply(Ts&&... ts) -> decltype(P::apply(std::forward<Ts>(ts)...)) {
4421
        return P::apply(std::forward<Ts>(ts)...);
4422
    }
4423
};
4424
4425
// --------------------------------------------------------------------------
4426
// --------------------------------------------------------------------------
4427
template <class T>
4428
struct NodeHashSetPolicy
4429
    : phmap::priv::node_hash_policy<T&, NodeHashSetPolicy<T>> 
4430
{
4431
    using key_type = T;
4432
    using init_type = T;
4433
    using constant_iterators = std::true_type;
4434
    using is_flat = std::false_type;
4435
4436
    template <class Allocator, class... Args>
4437
        static T* new_element(Allocator* alloc, Args&&... args) {
4438
        using ValueAlloc =
4439
            typename phmap::allocator_traits<Allocator>::template rebind_alloc<T>;
4440
        ValueAlloc value_alloc(*alloc);
4441
        T* res = phmap::allocator_traits<ValueAlloc>::allocate(value_alloc, 1);
4442
        phmap::allocator_traits<ValueAlloc>::construct(value_alloc, res,
4443
                                                       std::forward<Args>(args)...);
4444
        return res;
4445
    }
4446
4447
    template <class Allocator>
4448
        static void delete_element(Allocator* alloc, T* elem) {
4449
        using ValueAlloc =
4450
            typename phmap::allocator_traits<Allocator>::template rebind_alloc<T>;
4451
        ValueAlloc value_alloc(*alloc);
4452
        phmap::allocator_traits<ValueAlloc>::destroy(value_alloc, elem);
4453
        phmap::allocator_traits<ValueAlloc>::deallocate(value_alloc, elem, 1);
4454
    }
4455
4456
    template <class F, class... Args>
4457
        static decltype(phmap::priv::DecomposeValue(
4458
                            std::declval<F>(), std::declval<Args>()...))
4459
        apply(F&& f, Args&&... args) {
4460
        return phmap::priv::DecomposeValue(
4461
            std::forward<F>(f), std::forward<Args>(args)...);
4462
    }
4463
4464
    static size_t element_space_used(const T*) { return sizeof(T); }
4465
};
4466
4467
// --------------------------------------------------------------------------
4468
// --------------------------------------------------------------------------
4469
template <class Key, class Value>
4470
class NodeHashMapPolicy
4471
    : public phmap::priv::node_hash_policy<
4472
          std::pair<const Key, Value>&, NodeHashMapPolicy<Key, Value>> 
4473
{
4474
    using value_type = std::pair<const Key, Value>;
4475
4476
public:
4477
    using key_type = Key;
4478
    using mapped_type = Value;
4479
    using init_type = std::pair</*non const*/ key_type, mapped_type>;
4480
    using is_flat = std::false_type;
4481
4482
    template <class Allocator, class... Args>
4483
        static value_type* new_element(Allocator* alloc, Args&&... args) {
4484
        using PairAlloc = typename phmap::allocator_traits<
4485
            Allocator>::template rebind_alloc<value_type>;
4486
        PairAlloc pair_alloc(*alloc);
4487
        value_type* res =
4488
            phmap::allocator_traits<PairAlloc>::allocate(pair_alloc, 1);
4489
        phmap::allocator_traits<PairAlloc>::construct(pair_alloc, res,
4490
                                                      std::forward<Args>(args)...);
4491
        return res;
4492
    }
4493
4494
    template <class Allocator>
4495
        static void delete_element(Allocator* alloc, value_type* pair) {
4496
        using PairAlloc = typename phmap::allocator_traits<
4497
            Allocator>::template rebind_alloc<value_type>;
4498
        PairAlloc pair_alloc(*alloc);
4499
        phmap::allocator_traits<PairAlloc>::destroy(pair_alloc, pair);
4500
        phmap::allocator_traits<PairAlloc>::deallocate(pair_alloc, pair, 1);
4501
    }
4502
4503
    template <class F, class... Args>
4504
        static decltype(phmap::priv::DecomposePair(
4505
                            std::declval<F>(), std::declval<Args>()...))
4506
        apply(F&& f, Args&&... args) {
4507
        return phmap::priv::DecomposePair(std::forward<F>(f),
4508
                                                        std::forward<Args>(args)...);
4509
    }
4510
4511
    static size_t element_space_used(const value_type*) {
4512
        return sizeof(value_type);
4513
    }
4514
4515
    static Value& value(value_type* elem) { return elem->second; }
4516
    static const Value& value(const value_type* elem) { return elem->second; }
4517
};
4518
4519
4520
// --------------------------------------------------------------------------
4521
//  hash_default
4522
// --------------------------------------------------------------------------
4523
4524
#if PHMAP_HAVE_STD_STRING_VIEW
4525
4526
// Supports heterogeneous lookup for basic_string<T>-like elements.
4527
template<class CharT> 
4528
struct StringHashEqT
4529
{
4530
    struct Hash 
4531
    {
4532
        using is_transparent = void;
4533
        
4534
        size_t operator()(std::basic_string_view<CharT> v) const {
4535
            std::string_view bv{
4536
                reinterpret_cast<const char*>(v.data()), v.size() * sizeof(CharT)};
4537
            return std::hash<std::string_view>()(bv);
4538
        }
4539
    };
4540
4541
    struct Eq {
4542
        using is_transparent = void;
4543
4544
        bool operator()(std::basic_string_view<CharT> lhs,
4545
                        std::basic_string_view<CharT> rhs) const {
4546
            return lhs == rhs;
4547
        }
4548
    };
4549
};
4550
4551
template <>
4552
struct HashEq<std::string> : StringHashEqT<char> {};
4553
4554
template <>
4555
struct HashEq<std::string_view> : StringHashEqT<char> {};
4556
4557
// char16_t
4558
template <>
4559
struct HashEq<std::u16string> : StringHashEqT<char16_t> {};
4560
4561
template <>
4562
struct HashEq<std::u16string_view> : StringHashEqT<char16_t> {};
4563
4564
// wchar_t
4565
template <>
4566
struct HashEq<std::wstring> : StringHashEqT<wchar_t> {};
4567
4568
template <>
4569
struct HashEq<std::wstring_view> : StringHashEqT<wchar_t> {};
4570
4571
#endif
4572
4573
// Supports heterogeneous lookup for pointers and smart pointers.
4574
// -------------------------------------------------------------
4575
template <class T>
4576
struct HashEq<T*> 
4577
{
4578
    struct Hash {
4579
        using is_transparent = void;
4580
        template <class U>
4581
        size_t operator()(const U& ptr) const {
4582
            // we want phmap::Hash<T*> and not phmap::Hash<const T*>
4583
            // so "struct std::hash<T*> " override works
4584
            return phmap::Hash<T*>{}((T*)(uintptr_t)HashEq::ToPtr(ptr));
4585
        }
4586
    };
4587
4588
    struct Eq {
4589
        using is_transparent = void;
4590
        template <class A, class B>
4591
        bool operator()(const A& a, const B& b) const {
4592
            return HashEq::ToPtr(a) == HashEq::ToPtr(b);
4593
        }
4594
    };
4595
4596
private:
4597
    static const T* ToPtr(const T* ptr) { return ptr; }
4598
4599
    template <class U, class D>
4600
    static const T* ToPtr(const std::unique_ptr<U, D>& ptr) {
4601
        return ptr.get();
4602
    }
4603
4604
    template <class U>
4605
    static const T* ToPtr(const std::shared_ptr<U>& ptr) {
4606
        return ptr.get();
4607
    }
4608
};
4609
4610
template <class T, class D>
4611
struct HashEq<std::unique_ptr<T, D>> : HashEq<T*> {};
4612
4613
template <class T>
4614
struct HashEq<std::shared_ptr<T>> : HashEq<T*> {};
4615
4616
namespace hashtable_debug_internal {
4617
4618
// --------------------------------------------------------------------------
4619
// --------------------------------------------------------------------------
4620
4621
template<typename, typename = void >
4622
struct has_member_type_raw_hash_set : std::false_type
4623
{};
4624
template<typename T>
4625
struct has_member_type_raw_hash_set<T, phmap::void_t<typename T::raw_hash_set>> : std::true_type
4626
{};
4627
4628
template <typename Set>
4629
struct HashtableDebugAccess<Set, typename std::enable_if<has_member_type_raw_hash_set<Set>::value>::type>
4630
{
4631
    using Traits = typename Set::PolicyTraits;
4632
    using Slot = typename Traits::slot_type;
4633
4634
    static size_t GetNumProbes(const Set& set,
4635
                               const typename Set::key_type& key) {
4636
        if (!set.ctrl_)
4637
            return 0;
4638
        size_t num_probes = 0;
4639
        size_t hashval = set.hash(key); 
4640
        auto seq = set.probe(hashval);
4641
        while (true) {
4642
            priv::Group g{set.ctrl_ + seq.offset()};
4643
            for (uint32_t i : g.Match((h2_t)priv::H2(hashval))) {
4644
                if (Traits::apply(
4645
                        typename Set::template EqualElement<typename Set::key_type>{
4646
                            key, set.eq_ref()},
4647
                        Traits::element(set.slots_ + seq.offset((size_t)i))))
4648
                    return num_probes;
4649
                ++num_probes;
4650
            }
4651
            if (g.MatchEmpty()) return num_probes;
4652
            seq.next();
4653
            ++num_probes;
4654
        }
4655
    }
4656
4657
    static size_t AllocatedByteSize(const Set& c) {
4658
        size_t capacity = c.capacity_;
4659
        if (capacity == 0) return 0;
4660
        auto layout = Set::MakeLayout(capacity);
4661
        size_t m = layout.AllocSize();
4662
4663
        size_t per_slot = Traits::space_used(static_cast<const Slot*>(nullptr));
4664
        if (per_slot != ~size_t{}) {
4665
            m += per_slot * c.size();
4666
        } else {
4667
            for (size_t i = 0; i != capacity; ++i) {
4668
                if (priv::IsFull(c.ctrl_[i])) {
4669
                    m += Traits::space_used(c.slots_ + i);
4670
                }
4671
            }
4672
        }
4673
        return m;
4674
    }
4675
4676
    static size_t LowerBoundAllocatedByteSize(size_t size) {
4677
        size_t capacity = GrowthToLowerboundCapacity(size);
4678
        if (capacity == 0) return 0;
4679
        auto layout = Set::MakeLayout(NormalizeCapacity(capacity));
4680
        size_t m = layout.AllocSize();
4681
        size_t per_slot = Traits::space_used(static_cast<const Slot*>(nullptr));
4682
        if (per_slot != ~size_t{}) {
4683
            m += per_slot * size;
4684
        }
4685
        return m;
4686
    }
4687
};
4688
4689
4690
template<typename, typename = void >
4691
struct has_member_type_EmbeddedSet : std::false_type
4692
{};
4693
template<typename T>
4694
struct has_member_type_EmbeddedSet<T, phmap::void_t<typename T::EmbeddedSet>> : std::true_type
4695
{};
4696
4697
template <typename Set>
4698
struct HashtableDebugAccess<Set, typename std::enable_if<has_member_type_EmbeddedSet<Set>::value>::type> {
4699
    using Traits = typename Set::PolicyTraits;
4700
    using Slot = typename Traits::slot_type;
4701
    using EmbeddedSet = typename Set::EmbeddedSet;
4702
4703
    static size_t GetNumProbes(const Set& set, const typename Set::key_type& key) {
4704
        size_t hashval = set.hash(key);
4705
        auto& inner = set.sets_[set.subidx(hashval)];
4706
        auto& inner_set = inner.set_;
4707
        return HashtableDebugAccess<EmbeddedSet>::GetNumProbes(inner_set, key);
4708
    }
4709
};
4710
4711
}  // namespace hashtable_debug_internal
4712
}  // namespace priv
4713
4714
// -----------------------------------------------------------------------------
4715
// phmap::flat_hash_set
4716
// -----------------------------------------------------------------------------
4717
// An `phmap::flat_hash_set<T>` is an unordered associative container which has
4718
// been optimized for both speed and memory footprint in most common use cases.
4719
// Its interface is similar to that of `std::unordered_set<T>` with the
4720
// following notable differences:
4721
//
4722
// * Supports heterogeneous lookup, through `find()`, `operator[]()` and
4723
//   `insert()`, provided that the set is provided a compatible heterogeneous
4724
//   hashing function and equality operator.
4725
// * Invalidates any references and pointers to elements within the table after
4726
//   `rehash()`.
4727
// * Contains a `capacity()` member function indicating the number of element
4728
//   slots (open, deleted, and empty) within the hash set.
4729
// * Returns `void` from the `_erase(iterator)` overload.
4730
// -----------------------------------------------------------------------------
4731
template <class T, class Hash, class Eq, class Alloc> // default values in phmap_fwd_decl.h
4732
class flat_hash_set
4733
    : public phmap::priv::raw_hash_set<
4734
          phmap::priv::FlatHashSetPolicy<T>, Hash, Eq, Alloc> 
4735
{
4736
    using Base = typename flat_hash_set::raw_hash_set;
4737
4738
public:
4739
    flat_hash_set() {}
4740
#ifdef __INTEL_COMPILER
4741
    using Base::raw_hash_set;
4742
#else
4743
    using Base::Base;
4744
#endif
4745
    using Base::begin;
4746
    using Base::cbegin;
4747
    using Base::cend;
4748
    using Base::end;
4749
    using Base::capacity;
4750
    using Base::empty;
4751
    using Base::max_size;
4752
    using Base::size;
4753
    using Base::clear; // may shrink - To avoid shrinking `erase(begin(), end())`
4754
    using Base::erase;
4755
    using Base::insert;
4756
    using Base::emplace;
4757
    using Base::emplace_hint; 
4758
    using Base::extract;
4759
    using Base::merge;
4760
    using Base::swap;
4761
    using Base::rehash;
4762
    using Base::reserve;
4763
    using Base::contains;
4764
    using Base::count;
4765
    using Base::equal_range;
4766
    using Base::find;
4767
    using Base::bucket_count;
4768
    using Base::load_factor;
4769
    using Base::max_load_factor;
4770
    using Base::get_allocator;
4771
    using Base::hash_function;
4772
    using Base::hash;
4773
    using Base::key_eq;
4774
};
4775
4776
// -----------------------------------------------------------------------------
4777
// phmap::flat_hash_map
4778
// -----------------------------------------------------------------------------
4779
//
4780
// An `phmap::flat_hash_map<K, V>` is an unordered associative container which
4781
// has been optimized for both speed and memory footprint in most common use
4782
// cases. Its interface is similar to that of `std::unordered_map<K, V>` with
4783
// the following notable differences:
4784
//
4785
// * Supports heterogeneous lookup, through `find()`, `operator[]()` and
4786
//   `insert()`, provided that the map is provided a compatible heterogeneous
4787
//   hashing function and equality operator.
4788
// * Invalidates any references and pointers to elements within the table after
4789
//   `rehash()`.
4790
// * Contains a `capacity()` member function indicating the number of element
4791
//   slots (open, deleted, and empty) within the hash map.
4792
// * Returns `void` from the `_erase(iterator)` overload.
4793
// -----------------------------------------------------------------------------
4794
template <class K, class V, class Hash, class Eq, class Alloc> // default values in phmap_fwd_decl.h
4795
class flat_hash_map : public phmap::priv::raw_hash_map<
4796
                          phmap::priv::FlatHashMapPolicy<K, V>,
4797
                          Hash, Eq, Alloc> {
4798
    using Base = typename flat_hash_map::raw_hash_map;
4799
4800
public:
4801
1.80k
    flat_hash_map() {}
phmap::flat_hash_map<unsigned int, int, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::flat_hash_map()
Line
Count
Source
4801
1.20k
    flat_hash_map() {}
phmap::flat_hash_map<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, phmap::priv::StringHashEqT<char>::Hash, phmap::priv::StringHashEqT<char>::Eq, std::__1::allocator<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > >::flat_hash_map()
Line
Count
Source
4801
601
    flat_hash_map() {}
4802
#ifdef __INTEL_COMPILER
4803
    using Base::raw_hash_map;
4804
#else
4805
    using Base::Base;
4806
#endif
4807
    using Base::begin;
4808
    using Base::cbegin;
4809
    using Base::cend;
4810
    using Base::end;
4811
    using Base::capacity;
4812
    using Base::empty;
4813
    using Base::max_size;
4814
    using Base::size;
4815
    using Base::clear;
4816
    using Base::erase;
4817
    using Base::insert;
4818
    using Base::insert_or_assign;
4819
    using Base::emplace;
4820
    using Base::emplace_hint;
4821
    using Base::try_emplace;
4822
    using Base::extract;
4823
    using Base::merge;
4824
    using Base::swap;
4825
    using Base::rehash;
4826
    using Base::reserve;
4827
    using Base::at;
4828
    using Base::contains;
4829
    using Base::count;
4830
    using Base::equal_range;
4831
    using Base::find;
4832
    using Base::operator[];
4833
    using Base::bucket_count;
4834
    using Base::load_factor;
4835
    using Base::max_load_factor;
4836
    using Base::get_allocator;
4837
    using Base::hash_function;
4838
    using Base::hash;
4839
    using Base::key_eq;
4840
};
4841
4842
// -----------------------------------------------------------------------------
4843
// phmap::node_hash_set
4844
// -----------------------------------------------------------------------------
4845
// An `phmap::node_hash_set<T>` is an unordered associative container which
4846
// has been optimized for both speed and memory footprint in most common use
4847
// cases. Its interface is similar to that of `std::unordered_set<T>` with the
4848
// following notable differences:
4849
//
4850
// * Supports heterogeneous lookup, through `find()`, `operator[]()` and
4851
//   `insert()`, provided that the map is provided a compatible heterogeneous
4852
//   hashing function and equality operator.
4853
// * Contains a `capacity()` member function indicating the number of element
4854
//   slots (open, deleted, and empty) within the hash set.
4855
// * Returns `void` from the `_erase(iterator)` overload.
4856
// -----------------------------------------------------------------------------
4857
template <class T, class Hash, class Eq, class Alloc> // default values in phmap_fwd_decl.h
4858
class node_hash_set
4859
    : public phmap::priv::raw_hash_set<
4860
          phmap::priv::NodeHashSetPolicy<T>, Hash, Eq, Alloc> 
4861
{
4862
    using Base = typename node_hash_set::raw_hash_set;
4863
4864
public:
4865
    node_hash_set() {}
4866
#ifdef __INTEL_COMPILER
4867
    using Base::raw_hash_set;
4868
#else
4869
    using Base::Base;
4870
#endif
4871
    using Base::begin;
4872
    using Base::cbegin;
4873
    using Base::cend;
4874
    using Base::end;
4875
    using Base::capacity;
4876
    using Base::empty;
4877
    using Base::max_size;
4878
    using Base::size;
4879
    using Base::clear;
4880
    using Base::erase;
4881
    using Base::insert;
4882
    using Base::emplace;
4883
    using Base::emplace_hint;
4884
    using Base::emplace_with_hash;
4885
    using Base::emplace_hint_with_hash;
4886
    using Base::extract;
4887
    using Base::merge;
4888
    using Base::swap;
4889
    using Base::rehash;
4890
    using Base::reserve;
4891
    using Base::contains;
4892
    using Base::count;
4893
    using Base::equal_range;
4894
    using Base::find;
4895
    using Base::bucket_count;
4896
    using Base::load_factor;
4897
    using Base::max_load_factor;
4898
    using Base::get_allocator;
4899
    using Base::hash_function;
4900
    using Base::hash;
4901
    using Base::key_eq;
4902
    typename Base::hasher hash_funct() { return this->hash_function(); }
4903
    void resize(typename Base::size_type hint) { this->rehash(hint); }
4904
};
4905
4906
// -----------------------------------------------------------------------------
4907
// phmap::node_hash_map
4908
// -----------------------------------------------------------------------------
4909
//
4910
// An `phmap::node_hash_map<K, V>` is an unordered associative container which
4911
// has been optimized for both speed and memory footprint in most common use
4912
// cases. Its interface is similar to that of `std::unordered_map<K, V>` with
4913
// the following notable differences:
4914
//
4915
// * Supports heterogeneous lookup, through `find()`, `operator[]()` and
4916
//   `insert()`, provided that the map is provided a compatible heterogeneous
4917
//   hashing function and equality operator.
4918
// * Contains a `capacity()` member function indicating the number of element
4919
//   slots (open, deleted, and empty) within the hash map.
4920
// * Returns `void` from the `_erase(iterator)` overload.
4921
// -----------------------------------------------------------------------------
4922
template <class Key, class Value, class Hash, class Eq, class Alloc>  // default values in phmap_fwd_decl.h
4923
class node_hash_map
4924
    : public phmap::priv::raw_hash_map<
4925
          phmap::priv::NodeHashMapPolicy<Key, Value>, Hash, Eq,
4926
          Alloc> 
4927
{
4928
    using Base = typename node_hash_map::raw_hash_map;
4929
4930
public:
4931
    node_hash_map() {}
4932
#ifdef __INTEL_COMPILER
4933
    using Base::raw_hash_map;
4934
#else
4935
    using Base::Base;
4936
#endif
4937
    using Base::begin;
4938
    using Base::cbegin;
4939
    using Base::cend;
4940
    using Base::end;
4941
    using Base::capacity;
4942
    using Base::empty;
4943
    using Base::max_size;
4944
    using Base::size;
4945
    using Base::clear;
4946
    using Base::erase;
4947
    using Base::insert;
4948
    using Base::insert_or_assign;
4949
    using Base::emplace;
4950
    using Base::emplace_hint;
4951
    using Base::try_emplace;
4952
    using Base::extract;
4953
    using Base::merge;
4954
    using Base::swap;
4955
    using Base::rehash;
4956
    using Base::reserve;
4957
    using Base::at;
4958
    using Base::contains;
4959
    using Base::count;
4960
    using Base::equal_range;
4961
    using Base::find;
4962
    using Base::operator[];
4963
    using Base::bucket_count;
4964
    using Base::load_factor;
4965
    using Base::max_load_factor;
4966
    using Base::get_allocator;
4967
    using Base::hash_function;
4968
    using Base::hash;
4969
    using Base::key_eq;
4970
    typename Base::hasher hash_funct() { return this->hash_function(); }
4971
    void resize(typename Base::size_type hint) { this->rehash(hint); }
4972
};
4973
4974
// -----------------------------------------------------------------------------
4975
// phmap::parallel_flat_hash_set
4976
// -----------------------------------------------------------------------------
4977
template <class T, class Hash, class Eq, class Alloc, size_t N, class Mtx_> // default values in phmap_fwd_decl.h
4978
class parallel_flat_hash_set
4979
    : public phmap::priv::parallel_hash_set<
4980
         N, phmap::priv::raw_hash_set, Mtx_,
4981
         phmap::priv::FlatHashSetPolicy<T>, 
4982
         Hash, Eq, Alloc> 
4983
{
4984
    using Base = typename parallel_flat_hash_set::parallel_hash_set;
4985
4986
public:
4987
    parallel_flat_hash_set() {}
4988
#ifdef __INTEL_COMPILER
4989
    using Base::parallel_hash_set;
4990
#else
4991
    using Base::Base;
4992
#endif
4993
    using Base::hash;
4994
    using Base::subidx;
4995
    using Base::subcnt;
4996
    using Base::begin;
4997
    using Base::cbegin;
4998
    using Base::cend;
4999
    using Base::end;
5000
    using Base::capacity;
5001
    using Base::empty;
5002
    using Base::max_size;
5003
    using Base::size;
5004
    using Base::clear;
5005
    using Base::erase;
5006
    using Base::insert;
5007
    using Base::emplace;
5008
    using Base::emplace_hint;
5009
    using Base::emplace_with_hash;
5010
    using Base::emplace_hint_with_hash;
5011
    using Base::extract;
5012
    using Base::merge;
5013
    using Base::swap;
5014
    using Base::rehash;
5015
    using Base::reserve;
5016
    using Base::contains;
5017
    using Base::count;
5018
    using Base::equal_range;
5019
    using Base::find;
5020
    using Base::bucket_count;
5021
    using Base::load_factor;
5022
    using Base::max_load_factor;
5023
    using Base::get_allocator;
5024
    using Base::hash_function;
5025
    using Base::key_eq;
5026
};
5027
5028
// -----------------------------------------------------------------------------
5029
// phmap::parallel_flat_hash_map - default values in phmap_fwd_decl.h
5030
// -----------------------------------------------------------------------------
5031
template <class K, class V, class Hash, class Eq, class Alloc, size_t N, class Mtx_>
5032
class parallel_flat_hash_map : public phmap::priv::parallel_hash_map<
5033
                N, phmap::priv::raw_hash_set, Mtx_,
5034
                phmap::priv::FlatHashMapPolicy<K, V>,
5035
                Hash, Eq, Alloc> 
5036
{
5037
    using Base = typename parallel_flat_hash_map::parallel_hash_map;
5038
5039
public:
5040
    parallel_flat_hash_map() {}
5041
#ifdef __INTEL_COMPILER
5042
    using Base::parallel_hash_map;
5043
#else
5044
    using Base::Base;
5045
#endif
5046
    using Base::hash;
5047
    using Base::subidx;
5048
    using Base::subcnt;
5049
    using Base::begin;
5050
    using Base::cbegin;
5051
    using Base::cend;
5052
    using Base::end;
5053
    using Base::capacity;
5054
    using Base::empty;
5055
    using Base::max_size;
5056
    using Base::size;
5057
    using Base::clear;
5058
    using Base::erase;
5059
    using Base::insert;
5060
    using Base::insert_or_assign;
5061
    using Base::emplace;
5062
    using Base::emplace_hint;
5063
    using Base::try_emplace;
5064
    using Base::emplace_with_hash;
5065
    using Base::emplace_hint_with_hash;
5066
    using Base::try_emplace_with_hash;
5067
    using Base::extract;
5068
    using Base::merge;
5069
    using Base::swap;
5070
    using Base::rehash;
5071
    using Base::reserve;
5072
    using Base::at;
5073
    using Base::contains;
5074
    using Base::count;
5075
    using Base::equal_range;
5076
    using Base::find;
5077
    using Base::operator[];
5078
    using Base::bucket_count;
5079
    using Base::load_factor;
5080
    using Base::max_load_factor;
5081
    using Base::get_allocator;
5082
    using Base::hash_function;
5083
    using Base::key_eq;
5084
};
5085
5086
// -----------------------------------------------------------------------------
5087
// phmap::parallel_node_hash_set
5088
// -----------------------------------------------------------------------------
5089
template <class T, class Hash, class Eq, class Alloc, size_t N, class Mtx_>
5090
class parallel_node_hash_set
5091
    : public phmap::priv::parallel_hash_set<
5092
             N, phmap::priv::raw_hash_set, Mtx_,
5093
             phmap::priv::NodeHashSetPolicy<T>, Hash, Eq, Alloc> 
5094
{
5095
    using Base = typename parallel_node_hash_set::parallel_hash_set;
5096
5097
public:
5098
    parallel_node_hash_set() {}
5099
#ifdef __INTEL_COMPILER
5100
    using Base::parallel_hash_set;
5101
#else
5102
    using Base::Base;
5103
#endif
5104
    using Base::hash;
5105
    using Base::subidx;
5106
    using Base::subcnt;
5107
    using Base::begin;
5108
    using Base::cbegin;
5109
    using Base::cend;
5110
    using Base::end;
5111
    using Base::capacity;
5112
    using Base::empty;
5113
    using Base::max_size;
5114
    using Base::size;
5115
    using Base::clear;
5116
    using Base::erase;
5117
    using Base::insert;
5118
    using Base::emplace;
5119
    using Base::emplace_hint;
5120
    using Base::emplace_with_hash;
5121
    using Base::emplace_hint_with_hash;
5122
    using Base::extract;
5123
    using Base::merge;
5124
    using Base::swap;
5125
    using Base::rehash;
5126
    using Base::reserve;
5127
    using Base::contains;
5128
    using Base::count;
5129
    using Base::equal_range;
5130
    using Base::find;
5131
    using Base::bucket_count;
5132
    using Base::load_factor;
5133
    using Base::max_load_factor;
5134
    using Base::get_allocator;
5135
    using Base::hash_function;
5136
    using Base::key_eq;
5137
    typename Base::hasher hash_funct() { return this->hash_function(); }
5138
    void resize(typename Base::size_type hint) { this->rehash(hint); }
5139
};
5140
5141
// -----------------------------------------------------------------------------
5142
// phmap::parallel_node_hash_map
5143
// -----------------------------------------------------------------------------
5144
template <class Key, class Value, class Hash, class Eq, class Alloc, size_t N, class Mtx_>
5145
class parallel_node_hash_map
5146
    : public phmap::priv::parallel_hash_map<
5147
          N, phmap::priv::raw_hash_set, Mtx_,
5148
          phmap::priv::NodeHashMapPolicy<Key, Value>, Hash, Eq,
5149
          Alloc> 
5150
{
5151
    using Base = typename parallel_node_hash_map::parallel_hash_map;
5152
5153
public:
5154
    parallel_node_hash_map() {}
5155
#ifdef __INTEL_COMPILER
5156
    using Base::parallel_hash_map;
5157
#else
5158
    using Base::Base;
5159
#endif
5160
    using Base::hash;
5161
    using Base::subidx;
5162
    using Base::subcnt;
5163
    using Base::begin;
5164
    using Base::cbegin;
5165
    using Base::cend;
5166
    using Base::end;
5167
    using Base::capacity;
5168
    using Base::empty;
5169
    using Base::max_size;
5170
    using Base::size;
5171
    using Base::clear;
5172
    using Base::erase;
5173
    using Base::insert;
5174
    using Base::insert_or_assign;
5175
    using Base::emplace;
5176
    using Base::emplace_hint;
5177
    using Base::try_emplace;
5178
    using Base::emplace_with_hash;
5179
    using Base::emplace_hint_with_hash;
5180
    using Base::try_emplace_with_hash;
5181
    using Base::extract;
5182
    using Base::merge;
5183
    using Base::swap;
5184
    using Base::rehash;
5185
    using Base::reserve;
5186
    using Base::at;
5187
    using Base::contains;
5188
    using Base::count;
5189
    using Base::equal_range;
5190
    using Base::find;
5191
    using Base::operator[];
5192
    using Base::bucket_count;
5193
    using Base::load_factor;
5194
    using Base::max_load_factor;
5195
    using Base::get_allocator;
5196
    using Base::hash_function;
5197
    using Base::key_eq;
5198
    typename Base::hasher hash_funct() { return this->hash_function(); }
5199
    void resize(typename Base::size_type hint) { this->rehash(hint); }
5200
};
5201
5202
}  // namespace phmap
5203
5204
5205
namespace phmap {
5206
    namespace priv {
5207
        template <class C, class Pred> 
5208
        std::size_t erase_if(C &c, Pred pred) {
5209
            auto old_size = c.size();
5210
            for (auto i = c.begin(), last = c.end(); i != last; ) {
5211
                if (pred(*i)) {
5212
                    i = c.erase(i);
5213
                } else {
5214
                    ++i;
5215
                }
5216
            }
5217
            return old_size - c.size();
5218
        }
5219
    } // priv
5220
5221
    // ======== erase_if for phmap set containers ==================================
5222
    template <class T, class Hash, class Eq, class Alloc, class Pred> 
5223
    std::size_t erase_if(phmap::flat_hash_set<T, Hash, Eq, Alloc>& c, Pred pred) {
5224
        return phmap::priv::erase_if(c, std::move(pred));
5225
    }
5226
5227
    template <class T, class Hash, class Eq, class Alloc, class Pred> 
5228
    std::size_t erase_if(phmap::node_hash_set<T, Hash, Eq, Alloc>& c, Pred pred) {
5229
        return phmap::priv::erase_if(c, std::move(pred));
5230
    }
5231
5232
    template <class T, class Hash, class Eq, class Alloc, size_t N, class Mtx_, class Pred> 
5233
    std::size_t erase_if(phmap::parallel_flat_hash_set<T, Hash, Eq, Alloc, N, Mtx_>& c, Pred pred) {
5234
        return phmap::priv::erase_if(c, std::move(pred));
5235
    }
5236
5237
    template <class T, class Hash, class Eq, class Alloc, size_t N, class Mtx_, class Pred> 
5238
    std::size_t erase_if(phmap::parallel_node_hash_set<T, Hash, Eq, Alloc, N, Mtx_>& c, Pred pred) {
5239
        return phmap::priv::erase_if(c, std::move(pred));
5240
    }
5241
5242
    // ======== erase_if for phmap map containers ==================================
5243
    template <class K, class V, class Hash, class Eq, class Alloc, class Pred> 
5244
    std::size_t erase_if(phmap::flat_hash_map<K, V, Hash, Eq, Alloc>& c, Pred pred) {
5245
        return phmap::priv::erase_if(c, std::move(pred));
5246
    }
5247
5248
    template <class K, class V, class Hash, class Eq, class Alloc, class Pred> 
5249
    std::size_t erase_if(phmap::node_hash_map<K, V, Hash, Eq, Alloc>& c, Pred pred) {
5250
        return phmap::priv::erase_if(c, std::move(pred));
5251
    }
5252
5253
    template <class K, class V, class Hash, class Eq, class Alloc, size_t N, class Mtx_, class Pred> 
5254
    std::size_t erase_if(phmap::parallel_flat_hash_map<K, V, Hash, Eq, Alloc, N, Mtx_>& c, Pred pred) {
5255
        return phmap::priv::erase_if(c, std::move(pred));
5256
    }
5257
5258
    template <class K, class V, class Hash, class Eq, class Alloc, size_t N, class Mtx_, class Pred> 
5259
    std::size_t erase_if(phmap::parallel_node_hash_map<K, V, Hash, Eq, Alloc, N, Mtx_>& c, Pred pred) {
5260
        return phmap::priv::erase_if(c, std::move(pred));
5261
    }
5262
5263
} // phmap
5264
5265
#ifdef _MSC_VER
5266
     #pragma warning(pop)  
5267
#endif
5268
5269
5270
#endif // phmap_h_guard_