Coverage Report

Created: 2026-09-14 06:56

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
593
               std::false_type /* propagate_on_container_swap */) {}
142
143
// --------------------------------------------------------------------------
144
template <size_t Width>
145
class probe_seq 
146
{
147
public:
148
14.0M
    probe_seq(size_t hashval, size_t mask) {
149
14.0M
        assert(((mask + 1) & mask) == 0 && "not a mask");
150
14.0M
        mask_ = mask;
151
14.0M
        offset_ = hashval & mask_;
152
14.0M
    }
153
15.3M
    size_t offset() const { return offset_; }
154
25.8M
    size_t offset(size_t i) const { return (offset_ + i) & mask_; }
155
156
1.31M
    void next() {
157
1.31M
        index_ += Width;
158
1.31M
        offset_ += index_;
159
1.31M
        offset_ &= mask_;
160
1.31M
    }
161
    // 0-based probe index. The i-th probe in the probe sequence.
162
2.16M
    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
15.6M
uint32_t TrailingZeros(T x) {
209
15.6M
    uint32_t res;
210
15.6M
    PHMAP_IF_CONSTEXPR(sizeof(T) == 8)
211
        res = base_internal::CountTrailingZerosNonZero64(static_cast<uint64_t>(x));
212
    else
213
15.6M
        res = base_internal::CountTrailingZerosNonZero32(static_cast<uint32_t>(x));
214
15.6M
    return res;
215
15.6M
}
unsigned int phmap::priv::TrailingZeros<unsigned int>(unsigned int)
Line
Count
Source
208
15.6M
uint32_t TrailingZeros(T x) {
209
15.6M
    uint32_t res;
210
15.6M
    PHMAP_IF_CONSTEXPR(sizeof(T) == 8)
211
        res = base_internal::CountTrailingZerosNonZero64(static_cast<uint64_t>(x));
212
    else
213
15.6M
        res = base_internal::CountTrailingZerosNonZero32(static_cast<uint32_t>(x));
214
15.6M
    return res;
215
15.6M
}
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.5M
    explicit BitMask(T mask) : mask_(mask) {}
252
253
2.01M
    BitMask& operator++() {    // ++iterator
254
2.01M
        mask_ &= (mask_ - 1);  // clear the least significant bit set
255
2.01M
        return *this;
256
2.01M
    }
257
258
4.10M
    explicit operator bool() const { return mask_ != 0; }
259
13.2M
    uint32_t operator*() const { return LowestBitSet(); }
260
261
15.3M
    uint32_t LowestBitSet() const {
262
15.3M
        return priv::TrailingZeros(mask_) >> Shift;
263
15.3M
    }
264
265
    uint32_t HighestBitSet() const {
266
        return (sizeof(T) * CHAR_BIT - priv::LeadingZeros(mask_) - 1) >> Shift;
267
    }
268
269
13.2M
    BitMask begin() const { return *this; }
270
13.2M
    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.2M
    friend bool operator!=(const BitMask& a, const BitMask& b) {
287
15.2M
        return a.mask_ != b.mask_;
288
15.2M
    }
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.07k
inline ctrl_t* EmptyGroup() {
334
3.07k
  PHMAP_IF_CONSTEXPR (std_alloc_t::value) {
335
3.07k
      alignas(16) static constexpr ctrl_t empty_group[] = {
336
3.07k
          kSentinel, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty,
337
3.07k
          kEmpty,    kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty};
338
339
3.07k
      return const_cast<ctrl_t*>(empty_group);
340
  } else {
341
       return nullptr;
342
  }
343
3.07k
}
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.48k
inline ctrl_t* EmptyGroup() {
334
2.48k
  PHMAP_IF_CONSTEXPR (std_alloc_t::value) {
335
2.48k
      alignas(16) static constexpr ctrl_t empty_group[] = {
336
2.48k
          kSentinel, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty,
337
2.48k
          kEmpty,    kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty};
338
339
2.48k
      return const_cast<ctrl_t*>(empty_group);
340
  } else {
341
       return nullptr;
342
  }
343
2.48k
}
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
593
inline ctrl_t* EmptyGroup() {
334
593
  PHMAP_IF_CONSTEXPR (std_alloc_t::value) {
335
593
      alignas(16) static constexpr ctrl_t empty_group[] = {
336
593
          kSentinel, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty,
337
593
          kEmpty,    kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty};
338
339
593
      return const_cast<ctrl_t*>(empty_group);
340
  } else {
341
       return nullptr;
342
  }
343
593
}
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.0M
inline size_t H1(size_t hashval, const ctrl_t* ) {
364
14.0M
    return (hashval >> 7);
365
14.0M
}
366
367
#endif
368
369
370
15.2M
inline ctrl_t H2(size_t hashval)       { return (ctrl_t)(hashval & 0x7F); }
371
372
738k
inline bool IsEmpty(ctrl_t c)          { return c == kEmpty; }
373
3.54M
inline bool IsFull(ctrl_t c)           { return c >= static_cast<ctrl_t>(0); }
374
3.20k
inline bool IsDeleted(ctrl_t c)        { return c == kDeleted; }
375
1.00M
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.44M
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.44M
  return _mm_cmpgt_epi8(a, b);
405
2.44M
}
406
407
// --------------------------------------------------------------------------
408
// --------------------------------------------------------------------------
409
struct GroupSse2Impl 
410
{
411
    enum { kWidth = 16 };  // the number of slots per group
412
413
15.6M
    explicit GroupSse2Impl(const ctrl_t* pos) {
414
15.6M
        ctrl = _mm_loadu_si128(reinterpret_cast<const __m128i*>(pos));
415
15.6M
    }
416
417
    // Returns a bitmask representing the positions of slots that match hash.
418
    // ----------------------------------------------------------------------
419
15.1M
    BitMask<uint32_t, kWidth> Match(h2_t hash) const {
420
15.1M
        auto match = _mm_set1_epi8((char)hash);
421
15.1M
        return BitMask<uint32_t, kWidth>(
422
15.1M
            static_cast<uint32_t>(_mm_movemask_epi8(_mm_cmpeq_epi8(match, ctrl))));
423
15.1M
    }
424
425
    // Returns a bitmask representing the positions of empty slots.
426
    // ------------------------------------------------------------
427
1.94M
    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.94M
        return Match(static_cast<h2_t>(kEmpty));
434
1.94M
#endif
435
1.94M
    }
436
437
    // Returns a bitmask representing the positions of empty or deleted slots.
438
    // -----------------------------------------------------------------------
439
2.16M
    BitMask<uint32_t, kWidth> MatchEmptyOrDeleted() const {
440
2.16M
        auto special = _mm_set1_epi8(static_cast<char>(kSentinel));
441
2.16M
        return BitMask<uint32_t, kWidth>(
442
2.16M
            static_cast<uint32_t>(_mm_movemask_epi8(_mm_cmpgt_epi8_fixed(special, ctrl))));
443
2.16M
    }
444
445
    // Returns the number of trailing empty or deleted elements in the group.
446
    // ----------------------------------------------------------------------
447
283k
    uint32_t CountLeadingEmptyOrDeleted() const {
448
283k
        auto special = _mm_set1_epi8(static_cast<char>(kSentinel));
449
283k
        return TrailingZeros(
450
283k
            static_cast<uint32_t>(_mm_movemask_epi8(_mm_cmpgt_epi8_fixed(special, ctrl)) + 1));
451
283k
    }
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
15.8k
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
5.99k
{
584
5.99k
    assert(IsValidCapacity(capacity));
585
    // `capacity*7/8`
586
5.99k
    PHMAP_IF_CONSTEXPR (Group::kWidth == 8) {
587
5.99k
        if (capacity == 7) {
588
            // x-x/8 does not work when x==7.
589
            return 6;
590
        }
591
    }
592
5.99k
    return capacity - capacity / 8;
593
5.99k
}
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.34k
    inline void RecordStorageChanged(size_t , size_t ) {}
677
0
    inline void RecordRehash(size_t ) {}
678
738k
    inline void RecordInsert(size_t , size_t ) {}
679
0
    inline void RecordErase() {}
680
    friend inline void swap(HashtablezInfoHandle& ,
681
593
                            HashtablezInfoHandle& ) noexcept {}
682
};
683
684
704
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
25.8M
DecomposePairImpl(F&& f, std::pair<std::tuple<K>, V> p) {
757
25.8M
    const auto& key = std::get<0>(p.first);
758
25.8M
    return std::forward<F>(f)(key, std::piecewise_construct, std::move(p.first),
759
25.8M
                              std::move(p.second));
760
25.8M
}
_ZN5phmap4priv15memory_internal17DecomposePairImplINS0_12raw_hash_setINS0_17FlatHashMapPolicyIjiEENS_4HashIjEENS_7EqualToIjEENSt3__19allocatorINSA_4pairIKjiEEEEE19EmplaceDecomposableEOSD_NSA_5tupleIJOiEEEEEDTclclsr3stdE7declvalIT_EEclsr3stdE7declvalIRKT0_EEL_ZNSA_19piecewise_constructEEclsr3stdE7declvalINSJ_IJSN_EEEEEclsr3stdE7declvalIT1_EEEEOSM_NSC_ISQ_SR_EE
Line
Count
Source
756
11.2M
DecomposePairImpl(F&& f, std::pair<std::tuple<K>, V> p) {
757
11.2M
    const auto& key = std::get<0>(p.first);
758
11.2M
    return std::forward<F>(f)(key, std::piecewise_construct, std::move(p.first),
759
11.2M
                              std::move(p.second));
760
11.2M
}
_ZN5phmap4priv15memory_internal17DecomposePairImplINS0_12raw_hash_setINS0_17FlatHashMapPolicyIjiEENS_4HashIjEENS_7EqualToIjEENSt3__19allocatorINSA_4pairIKjiEEEEE12EqualElementIjEERSD_NSA_5tupleIJRKiEEEEEDTclclsr3stdE7declvalIT_EEclsr3stdE7declvalIRKT0_EEL_ZNSA_19piecewise_constructEEclsr3stdE7declvalINSK_IJSP_EEEEEclsr3stdE7declvalIT1_EEEEOSO_NSC_ISS_ST_EE
Line
Count
Source
756
12.5M
DecomposePairImpl(F&& f, std::pair<std::tuple<K>, V> p) {
757
12.5M
    const auto& key = std::get<0>(p.first);
758
12.5M
    return std::forward<F>(f)(key, std::piecewise_construct, std::move(p.first),
759
12.5M
                              std::move(p.second));
760
12.5M
}
_ZN5phmap4priv15memory_internal17DecomposePairImplINS0_12raw_hash_setINS0_17FlatHashMapPolicyIjiEENS_4HashIjEENS_7EqualToIjEENSt3__19allocatorINSA_4pairIKjiEEEEE11HashElementERSD_NSA_5tupleIJRKiEEEEEDTclclsr3stdE7declvalIT_EEclsr3stdE7declvalIRKT0_EEL_ZNSA_19piecewise_constructEEclsr3stdE7declvalINSJ_IJSO_EEEEEclsr3stdE7declvalIT1_EEEEOSN_NSC_ISR_SS_EE
Line
Count
Source
756
2.03M
DecomposePairImpl(F&& f, std::pair<std::tuple<K>, V> p) {
757
2.03M
    const auto& key = std::get<0>(p.first);
758
2.03M
    return std::forward<F>(f)(key, std::piecewise_construct, std::move(p.first),
759
2.03M
                              std::move(p.second));
760
2.03M
}
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.69k
    static Layout MakeLayout(size_t capacity) {
888
6.69k
        assert(IsValidCapacity(capacity));
889
6.69k
        return Layout(capacity + Group::kWidth + 1, capacity);
890
6.69k
    }
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.69k
    static Layout MakeLayout(size_t capacity) {
888
6.69k
        assert(IsValidCapacity(capacity));
889
6.69k
        return Layout(capacity + Group::kWidth + 1, capacity);
890
6.69k
    }
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
722k
        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
722k
        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
722k
        iterator& operator++() {
952
722k
            ++ctrl_;
953
722k
            ++slot_;
954
722k
            skip_empty_or_deleted();
955
722k
            return *this;
956
722k
        }
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
722k
        iterator& operator++() {
952
722k
            ++ctrl_;
953
722k
            ++slot_;
954
722k
            skip_empty_or_deleted();
955
722k
            return *this;
956
722k
        }
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
723k
        friend bool operator==(const iterator& a, const iterator& b) {
984
723k
            return a.ctrl_ == b.ctrl_;
985
723k
        }
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
722k
        friend bool operator==(const iterator& a, const iterator& b) {
984
722k
            return a.ctrl_ == b.ctrl_;
985
722k
        }
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
593
        friend bool operator==(const iterator& a, const iterator& b) {
984
593
            return a.ctrl_ == b.ctrl_;
985
593
        }
986
593
        friend bool operator!=(const iterator& a, const iterator& b) {
987
593
            return !(a == b);
988
593
        }
989
990
    private:
991
1.39k
        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.18k
        iterator(ctrl_t* ctrl) : ctrl_(ctrl) {}  // for end()
992
11.2M
        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.2M
        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
722k
        void skip_empty_or_deleted() {
995
722k
            PHMAP_IF_CONSTEXPR (!std_alloc_t::value) {
996
                // ctrl_ could be nullptr
997
                if (!ctrl_)
998
                    return;
999
            }
1000
1.00M
            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
283k
                uint32_t shift = Group{ctrl_}.CountLeadingEmptyOrDeleted();
1006
283k
                ctrl_ += shift;
1007
283k
                slot_ += shift;
1008
283k
            }
1009
722k
        }
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
722k
        void skip_empty_or_deleted() {
995
722k
            PHMAP_IF_CONSTEXPR (!std_alloc_t::value) {
996
                // ctrl_ could be nullptr
997
                if (!ctrl_)
998
                    return;
999
            }
1000
1.00M
            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
283k
                uint32_t shift = Group{ctrl_}.CountLeadingEmptyOrDeleted();
1006
283k
                ctrl_ += shift;
1007
283k
                slot_ += shift;
1008
283k
            }
1009
722k
        }
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
350
        const_iterator(iterator i) : inner_(std::move(i)) {}
1033
1034
722k
        reference operator*() const { return *inner_; }
1035
        pointer operator->() const { return inner_.operator->(); }
1036
1037
722k
        const_iterator& operator++() {
1038
722k
            ++inner_;
1039
722k
            return *this;
1040
722k
        }
1041
        const_iterator operator++(int) { return inner_++; }
1042
1043
722k
        friend bool operator==(const const_iterator& a, const const_iterator& b) {
1044
722k
            return a.inner_ == b.inner_;
1045
722k
        }
1046
722k
        friend bool operator!=(const const_iterator& a, const const_iterator& b) {
1047
722k
            return !(a == b);
1048
722k
        }
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.37k
        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.77k
        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
593
        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.37k
    ~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.77k
    ~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
593
    ~raw_hash_set() { destroy_slots(); }
1246
1247
768
    iterator begin() {
1248
768
        if (empty()) return end();
1249
143
        auto it = iterator_at(0);
1250
143
        it.skip_empty_or_deleted();
1251
143
        return it;
1252
768
    }
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
175
    iterator begin() {
1248
175
        if (empty()) return end();
1249
143
        auto it = iterator_at(0);
1250
143
        it.skip_empty_or_deleted();
1251
143
        return it;
1252
175
    }
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
593
    iterator begin() {
1248
593
        if (empty()) return end();
1249
0
        auto it = iterator_at(0);
1250
0
        it.skip_empty_or_deleted();
1251
0
        return it;
1252
593
    }
1253
    iterator end() 
1254
1.39k
    {
1255
#if 0 // PHMAP_BIDIRECTIONAL
1256
        return iterator_at(capacity_); 
1257
#else
1258
1.39k
        return {ctrl_ + capacity_};
1259
1.39k
#endif
1260
1.39k
    }
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.18k
    {
1255
#if 0 // PHMAP_BIDIRECTIONAL
1256
        return iterator_at(capacity_); 
1257
#else
1258
1.18k
        return {ctrl_ + capacity_};
1259
1.18k
#endif
1260
1.18k
    }
1261
1262
175
    const_iterator begin() const {
1263
175
        return const_cast<raw_hash_set*>(this)->begin();
1264
175
    }
1265
175
    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
768
    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
175
    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
593
    bool empty() const { return !size(); }
1270
4.59k
    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.00k
    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
593
    size_t size() const { return size_; }
1271
2.99k
    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.2M
    std::pair<iterator, bool> insert(T&& value) {
1304
11.2M
        return emplace(std::forward<T>(value));
1305
11.2M
    }
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.2M
    std::pair<iterator, bool> emplace(Args&&... args) {
1443
11.2M
        return PolicyTraits::apply(EmplaceDecomposable{*this},
1444
11.2M
                                   std::forward<Args>(args)...);
1445
11.2M
    }
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
593
         IsNoThrowSwappable<allocator_type>(typename AllocTraits::propagate_on_container_swap{}))) {
1679
593
        using std::swap;
1680
593
        swap(ctrl_, that.ctrl_);
1681
593
        swap(slots_, that.slots_);
1682
593
        swap(size_, that.size_);
1683
593
        swap(capacity_, that.capacity_);
1684
593
        swap(growth_left(), that.growth_left());
1685
593
        swap(hash_ref(), that.hash_ref());
1686
593
        swap(eq_ref(), that.eq_ref());
1687
593
        swap(infoz_, that.infoz_);
1688
593
        SwapAlloc(alloc_ref(), that.alloc_ref(), typename AllocTraits::propagate_on_container_swap{});
1689
593
    }
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
593
    friend bool operator==(const raw_hash_set& a, const raw_hash_set& b) {
1832
593
        if (a.size() != b.size()) return false;
1833
175
        const raw_hash_set* outer = &a;
1834
175
        const raw_hash_set* inner = &b;
1835
175
        if (outer->capacity() > inner->capacity()) 
1836
0
            std::swap(outer, inner);
1837
175
        for (const value_type& elem : *outer)
1838
722k
            if (!inner->has_element(elem)) return false;
1839
44
        return true;
1840
175
    }
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.2M
    size_t hash(const K& key) const {
1853
11.2M
        return HashElement{hash_ref()}(key);
1854
11.2M
    }
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.3M
        size_t operator()(const K& key, Args&&...) const {
1896
#if PHMAP_DISABLE_MIX
1897
            return h(key);
1898
#else
1899
13.3M
            return phmap_mix<sizeof(size_t)>()(h(key));
1900
13.3M
#endif
1901
13.3M
        }
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
2.03M
        size_t operator()(const K& key, Args&&...) const {
1896
#if PHMAP_DISABLE_MIX
1897
            return h(key);
1898
#else
1899
2.03M
            return phmap_mix<sizeof(size_t)>()(h(key));
1900
2.03M
#endif
1901
2.03M
        }
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.2M
        size_t operator()(const K& key, Args&&...) const {
1896
#if PHMAP_DISABLE_MIX
1897
            return h(key);
1898
#else
1899
11.2M
            return phmap_mix<sizeof(size_t)>()(h(key));
1900
11.2M
#endif
1901
11.2M
        }
1902
        const hasher& h;
1903
    };
1904
1905
    template <class K1>
1906
    struct EqualElement 
1907
    {
1908
        template <class K2, class... Args>
1909
12.5M
        bool operator()(const K2& lhs, Args&&...) const {
1910
12.5M
            return eq(lhs, rhs);
1911
12.5M
        }
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.2M
    {
1920
11.2M
        size_t offset = _find_key(key, hashval);
1921
11.2M
        if (offset == (size_t)-1) {
1922
738k
            offset = prepare_insert(hashval);
1923
738k
            emplace_at(offset, std::forward<Args>(args)...);
1924
738k
            this->set_ctrl(offset, H2(hashval));
1925
738k
            return {iterator_at(offset), true};
1926
738k
        }
1927
10.5M
        return {iterator_at(offset), false};
1928
11.2M
    }
1929
1930
    struct EmplaceDecomposable 
1931
    {
1932
        template <class K, class... Args>
1933
11.2M
        std::pair<iterator, bool> operator()(const K& key, Args&&... args) const {
1934
11.2M
            return s.emplace_decomposable(key, s.hash(key), std::forward<Args>(args)...);
1935
11.2M
        }
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.34k
    void initialize_slots(size_t new_capacity) {
2014
3.34k
        assert(new_capacity);
2015
3.34k
        if (std::is_same<SlotAlloc, std::allocator<slot_type>>::value && 
2016
3.34k
            slots_ == nullptr) {
2017
704
            infoz_ = Sample();
2018
704
        }
2019
2020
3.34k
        auto layout = MakeLayout(new_capacity);
2021
3.34k
        char* mem = static_cast<char*>(
2022
3.34k
            Allocate<Layout::Alignment()>(&alloc_ref(), layout.AllocSize()));
2023
3.34k
        ctrl_ = reinterpret_cast<ctrl_t*>(layout.template Pointer<0>(mem));
2024
3.34k
        slots_ = layout.template Pointer<1>(mem);
2025
3.34k
        reset_ctrl(new_capacity);
2026
3.34k
        reset_growth_left(new_capacity);
2027
3.34k
        infoz_.RecordStorageChanged(size_, new_capacity);
2028
3.34k
    }
2029
2030
2.37k
    void destroy_slots() {
2031
2.37k
        if (!capacity_)
2032
1.66k
            return;
2033
        
2034
704
        PHMAP_IF_CONSTEXPR((!std::is_trivially_destructible<typename PolicyTraits::value_type>::value ||
2035
704
                            std::is_same<typename Policy::is_flat, std::false_type>::value)) {
2036
            // node map, or not trivially destructible... we  need to iterate and destroy values one by one
2037
            // std::cout << "either this is a node map or " << type_name<typename PolicyTraits::value_type>()  << " is not trivially_destructible\n";
2038
0
            for (size_t i = 0, cnt = capacity_; i != cnt; ++i) {
2039
0
                if (IsFull(ctrl_[i])) {
2040
0
                    PolicyTraits::destroy(&alloc_ref(), slots_ + i);
2041
0
                }
2042
0
            }
2043
0
        } 
2044
704
        auto layout = MakeLayout(capacity_);
2045
        // Unpoison before returning the memory to the allocator.
2046
704
        SanitizerUnpoisonMemoryRegion(slots_, sizeof(slot_type) * capacity_);
2047
704
        Deallocate<Layout::Alignment()>(&alloc_ref(), ctrl_, layout.AllocSize());
2048
704
        ctrl_ = EmptyGroup<std_alloc_t>();
2049
704
        slots_ = nullptr;
2050
704
        size_ = 0;
2051
704
        capacity_ = 0;
2052
704
        growth_left() = 0;
2053
704
    }
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
2030
1.77k
    void destroy_slots() {
2031
1.77k
        if (!capacity_)
2032
1.07k
            return;
2033
        
2034
704
        PHMAP_IF_CONSTEXPR((!std::is_trivially_destructible<typename PolicyTraits::value_type>::value ||
2035
704
                            std::is_same<typename Policy::is_flat, std::false_type>::value)) {
2036
            // node map, or not trivially destructible... we  need to iterate and destroy values one by one
2037
            // std::cout << "either this is a node map or " << type_name<typename PolicyTraits::value_type>()  << " is not trivially_destructible\n";
2038
            for (size_t i = 0, cnt = capacity_; i != cnt; ++i) {
2039
                if (IsFull(ctrl_[i])) {
2040
                    PolicyTraits::destroy(&alloc_ref(), slots_ + i);
2041
                }
2042
            }
2043
        } 
2044
704
        auto layout = MakeLayout(capacity_);
2045
        // Unpoison before returning the memory to the allocator.
2046
704
        SanitizerUnpoisonMemoryRegion(slots_, sizeof(slot_type) * capacity_);
2047
704
        Deallocate<Layout::Alignment()>(&alloc_ref(), ctrl_, layout.AllocSize());
2048
704
        ctrl_ = EmptyGroup<std_alloc_t>();
2049
704
        slots_ = nullptr;
2050
704
        size_ = 0;
2051
704
        capacity_ = 0;
2052
704
        growth_left() = 0;
2053
704
    }
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
2030
593
    void destroy_slots() {
2031
593
        if (!capacity_)
2032
593
            return;
2033
        
2034
0
        PHMAP_IF_CONSTEXPR((!std::is_trivially_destructible<typename PolicyTraits::value_type>::value ||
2035
0
                            std::is_same<typename Policy::is_flat, std::false_type>::value)) {
2036
            // node map, or not trivially destructible... we  need to iterate and destroy values one by one
2037
            // std::cout << "either this is a node map or " << type_name<typename PolicyTraits::value_type>()  << " is not trivially_destructible\n";
2038
0
            for (size_t i = 0, cnt = capacity_; i != cnt; ++i) {
2039
0
                if (IsFull(ctrl_[i])) {
2040
0
                    PolicyTraits::destroy(&alloc_ref(), slots_ + i);
2041
0
                }
2042
0
            }
2043
0
        } 
2044
0
        auto layout = MakeLayout(capacity_);
2045
        // Unpoison before returning the memory to the allocator.
2046
0
        SanitizerUnpoisonMemoryRegion(slots_, sizeof(slot_type) * capacity_);
2047
0
        Deallocate<Layout::Alignment()>(&alloc_ref(), ctrl_, layout.AllocSize());
2048
0
        ctrl_ = EmptyGroup<std_alloc_t>();
2049
0
        slots_ = nullptr;
2050
0
        size_ = 0;
2051
0
        capacity_ = 0;
2052
0
        growth_left() = 0;
2053
0
    }
2054
2055
3.20k
    void resize(size_t new_capacity) {
2056
3.20k
        assert(IsValidCapacity(new_capacity));
2057
3.20k
        auto* old_ctrl = ctrl_;
2058
3.20k
        auto* old_slots = slots_;
2059
3.20k
        const size_t old_capacity = capacity_;
2060
3.20k
        initialize_slots(new_capacity);
2061
3.20k
        capacity_ = new_capacity;
2062
2063
1.49M
        for (size_t i = 0; i != old_capacity; ++i) {
2064
1.49M
            if (IsFull(old_ctrl[i])) {
2065
1.30M
                size_t hashval = PolicyTraits::apply(HashElement{hash_ref()},
2066
1.30M
                                                     PolicyTraits::element(old_slots + i));
2067
1.30M
                auto target = find_first_non_full(hashval);
2068
1.30M
                size_t new_i = target.offset;
2069
1.30M
                set_ctrl(new_i, H2(hashval));
2070
1.30M
                PolicyTraits::transfer(&alloc_ref(), slots_ + new_i, old_slots + i);
2071
1.30M
            }
2072
1.49M
        }
2073
3.20k
        if (old_capacity) {
2074
2.64k
            SanitizerUnpoisonMemoryRegion(old_slots,
2075
2.64k
                                          sizeof(slot_type) * old_capacity);
2076
2.64k
            auto layout = MakeLayout(old_capacity);
2077
2.64k
            Deallocate<Layout::Alignment()>(&alloc_ref(), old_ctrl,
2078
2.64k
                                            layout.AllocSize());
2079
2.64k
        }
2080
3.20k
    }
2081
2082
0
    void drop_deletes_without_resize() PHMAP_ATTRIBUTE_NOINLINE {
2083
0
        assert(IsValidCapacity(capacity_));
2084
0
        assert(!is_small());
2085
        // Algorithm:
2086
        // - mark all DELETED slots as EMPTY
2087
        // - mark all FULL slots as DELETED
2088
        // - for each slot marked as DELETED
2089
        //     hash = Hash(element)
2090
        //     target = find_first_non_full(hash)
2091
        //     if target is in the same group
2092
        //       mark slot as FULL
2093
        //     else if target is EMPTY
2094
        //       transfer element to target
2095
        //       mark slot as EMPTY
2096
        //       mark target as FULL
2097
        //     else if target is DELETED
2098
        //       swap current element with target element
2099
        //       mark target as FULL
2100
        //       repeat procedure for current slot with moved from element (target)
2101
0
        ConvertDeletedToEmptyAndFullToDeleted(ctrl_, capacity_);
2102
0
        typename phmap::aligned_storage<sizeof(slot_type), alignof(slot_type)>::type
2103
0
            raw;
2104
0
        slot_type* slot = reinterpret_cast<slot_type*>(&raw);
2105
0
        for (size_t i = 0; i != capacity_; ++i) {
2106
0
            if (!IsDeleted(ctrl_[i])) continue;
2107
0
            size_t hashval = PolicyTraits::apply(HashElement{hash_ref()},
2108
0
                                                 PolicyTraits::element(slots_ + i));
2109
0
            auto target = find_first_non_full(hashval);
2110
0
            size_t new_i = target.offset;
2111
2112
            // Verify if the old and new i fall within the same group wrt the hashval.
2113
            // If they do, we don't need to move the object as it falls already in the
2114
            // best probe we can.
2115
0
            const auto probe_index = [&](size_t pos) {
2116
0
                return ((pos - probe(hashval).offset()) & capacity_) / Group::kWidth;
2117
0
            };
2118
2119
            // Element doesn't move.
2120
0
            if (PHMAP_PREDICT_TRUE(probe_index(new_i) == probe_index(i))) {
2121
0
                set_ctrl(i, H2(hashval));
2122
0
                continue;
2123
0
            }
2124
0
            if (IsEmpty(ctrl_[new_i])) {
2125
                // Transfer element to the empty spot.
2126
                // set_ctrl poisons/unpoisons the slots so we have to call it at the
2127
                // right time.
2128
0
                set_ctrl(new_i, H2(hashval));
2129
0
                PolicyTraits::transfer(&alloc_ref(), slots_ + new_i, slots_ + i);
2130
0
                set_ctrl(i, kEmpty);
2131
0
            } else {
2132
0
                assert(IsDeleted(ctrl_[new_i]));
2133
0
                set_ctrl(new_i, H2(hashval));
2134
                // Until we are done rehashing, DELETED marks previously FULL slots.
2135
                // Swap i and new_i elements.
2136
0
                PolicyTraits::transfer(&alloc_ref(), slot, slots_ + i);
2137
0
                PolicyTraits::transfer(&alloc_ref(), slots_ + i, slots_ + new_i);
2138
0
                PolicyTraits::transfer(&alloc_ref(), slots_ + new_i, slot);
2139
0
                --i;  // repeat
2140
0
            }
2141
0
        }
2142
0
        reset_growth_left(capacity_);
2143
0
    }
2144
2145
3.20k
    void rehash_and_grow_if_necessary() {
2146
3.20k
        if (capacity_ == 0) {
2147
561
            resize(1);
2148
2.64k
        } else if (size() <= CapacityToGrowth(capacity()) / 2) {
2149
            // Squash DELETED without growing if there is enough capacity.
2150
0
            drop_deletes_without_resize();
2151
2.64k
        } else {
2152
            // Otherwise grow the container.
2153
2.64k
            resize(capacity_ * 2 + 1);
2154
2.64k
        }
2155
3.20k
    }
2156
2157
722k
    bool has_element(const value_type& PHMAP_RESTRICT elem, size_t hashval) const {
2158
722k
        PHMAP_IF_CONSTEXPR (!std_alloc_t::value) {
2159
            // ctrl_ could be nullptr
2160
            if (!ctrl_)
2161
                return false;
2162
        }
2163
722k
        auto seq = probe(hashval);
2164
725k
        while (true) {
2165
725k
            Group g{ctrl_ + seq.offset()};
2166
725k
            for (uint32_t i : g.Match((h2_t)H2(hashval))) {
2167
725k
                if (PHMAP_PREDICT_TRUE(PolicyTraits::element(slots_ + seq.offset((size_t)i)) ==
2168
725k
                                      elem))
2169
722k
                    return true;
2170
725k
            }
2171
2.91k
            if (PHMAP_PREDICT_TRUE(g.MatchEmpty())) return false;
2172
2.78k
            seq.next();
2173
2.78k
            assert(seq.getindex() < capacity_ && "full table!");
2174
2.78k
        }
2175
0
        return false;
2176
722k
    }
2177
2178
722k
    bool has_element(const value_type& elem) const {
2179
722k
        size_t hashval = PolicyTraits::apply(HashElement{hash_ref()}, elem);
2180
722k
        return has_element(elem, hashval);
2181
722k
    }
2182
2183
    // Probes the raw_hash_set with the probe sequence for hash and returns the
2184
    // pointer to the first empty or deleted slot.
2185
    // NOTE: this function must work with tables having both kEmpty and kDelete
2186
    // in one group. Such tables appears during drop_deletes_without_resize.
2187
    //
2188
    // This function is very useful when insertions happen and:
2189
    // - the input is already a set
2190
    // - there are enough slots
2191
    // - the element with the hash is not in the table
2192
    struct FindInfo 
2193
    {
2194
        size_t offset;
2195
        size_t probe_length;
2196
    };
2197
2.05M
    FindInfo find_first_non_full(size_t hashval) {
2198
2.05M
        auto seq = probe(hashval);
2199
2.16M
        while (true) {
2200
2.16M
            Group g{ctrl_ + seq.offset()};
2201
2.16M
            auto mask = g.MatchEmptyOrDeleted();
2202
2.16M
            if (mask) {
2203
2.05M
                return {seq.offset((size_t)mask.LowestBitSet()), seq.getindex()};
2204
2.05M
            }
2205
2.16M
            assert(seq.getindex() < capacity_ && "full table!");
2206
111k
            seq.next();
2207
111k
        }
2208
2.05M
    }
2209
2210
    // TODO(alkis): Optimize this assuming *this and that don't overlap.
2211
    raw_hash_set& move_assign(raw_hash_set&& that, std::true_type) {
2212
        raw_hash_set tmp(std::move(that));
2213
        swap(tmp);
2214
        return *this;
2215
    }
2216
    raw_hash_set& move_assign(raw_hash_set&& that, std::false_type) {
2217
        raw_hash_set tmp(std::move(that), alloc_ref());
2218
        swap(tmp);
2219
        return *this;
2220
    }
2221
2222
protected:
2223
    template <class K>
2224
11.2M
    size_t _find_key(const K& PHMAP_RESTRICT key, size_t hashval) {
2225
11.2M
        PHMAP_IF_CONSTEXPR (!std_alloc_t::value) {
2226
            // ctrl_ could be nullptr
2227
            if (!ctrl_)
2228
                return (size_t)-1;
2229
        }
2230
11.2M
        auto seq = probe(hashval);
2231
12.4M
        while (true) {
2232
12.4M
            Group g{ctrl_ + seq.offset()};
2233
12.5M
            for (uint32_t i : g.Match((h2_t)H2(hashval))) {
2234
12.5M
                if (PHMAP_PREDICT_TRUE(PolicyTraits::apply(
2235
12.5M
                                          EqualElement<K>{key, eq_ref()},
2236
12.5M
                                          PolicyTraits::element(slots_ + seq.offset((size_t)i)))))
2237
10.5M
                    return seq.offset((size_t)i);
2238
12.5M
            }
2239
1.94M
            if (PHMAP_PREDICT_TRUE(g.MatchEmpty())) break;
2240
1.20M
            seq.next();
2241
1.20M
        }
2242
738k
        return (size_t)-1;
2243
11.2M
    }
2244
2245
    template <class K>
2246
    std::pair<size_t, bool> find_or_prepare_insert(const K& key, size_t hashval) {
2247
        size_t offset = _find_key(key, hashval);
2248
        if (offset == (size_t)-1)
2249
            return {prepare_insert(hashval), true};
2250
        return {offset, false};
2251
    }
2252
2253
738k
    size_t prepare_insert(size_t hashval) PHMAP_ATTRIBUTE_NOINLINE {
2254
738k
        PHMAP_IF_CONSTEXPR (!std_alloc_t::value) {
2255
            // ctrl_ could be nullptr
2256
            if (!ctrl_)
2257
                rehash_and_grow_if_necessary();
2258
        }
2259
738k
        FindInfo target = find_first_non_full(hashval);
2260
738k
        if (PHMAP_PREDICT_FALSE(growth_left() == 0 &&
2261
738k
                               !IsDeleted(ctrl_[target.offset]))) {
2262
3.20k
            rehash_and_grow_if_necessary();
2263
3.20k
            target = find_first_non_full(hashval);
2264
3.20k
        }
2265
738k
        ++size_;
2266
738k
        growth_left() -= IsEmpty(ctrl_[target.offset]);
2267
        // set_ctrl(target.offset, H2(hashval));
2268
738k
        infoz_.RecordInsert(hashval, target.probe_length);
2269
738k
        return target.offset;
2270
738k
    }
2271
2272
    // Constructs the value in the space pointed by the iterator. This only works
2273
    // after an unsuccessful find_or_prepare_insert() and before any other
2274
    // modifications happen in the raw_hash_set.
2275
    //
2276
    // PRECONDITION: i is an index returned from find_or_prepare_insert(k), where
2277
    // k is the key decomposed from `forward<Args>(args)...`, and the bool
2278
    // returned by find_or_prepare_insert(k) was true.
2279
    // POSTCONDITION: *m.iterator_at(i) == value_type(forward<Args>(args)...).
2280
    template <class... Args>
2281
738k
    void emplace_at(size_t i, Args&&... args) {
2282
738k
        PolicyTraits::construct(&alloc_ref(), slots_ + i,
2283
738k
                                std::forward<Args>(args)...);
2284
        
2285
#ifdef PHMAP_CHECK_CONSTRUCTED_VALUE
2286
        // this check can be costly, so do it only when requested
2287
        assert(PolicyTraits::apply(FindElement{*this}, *iterator_at(i)) ==
2288
               iterator_at(i) &&
2289
               "constructed value does not match the lookup key");
2290
#endif
2291
738k
    }
2292
2293
11.2M
    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
2293
11.2M
    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)
2294
    const_iterator iterator_at(size_t i) const { return {ctrl_ + i, slots_ + i}; }
2295
2296
protected:
2297
    // Sets the control byte, and if `i < Group::kWidth`, set the cloned byte at
2298
    // the end too.
2299
2.04M
    void set_ctrl(size_t i, ctrl_t h) {
2300
2.04M
        assert(i < capacity_);
2301
2302
2.04M
        if (IsFull(h)) {
2303
2.04M
            SanitizerUnpoisonObject(slots_ + i);
2304
2.04M
        } else {
2305
0
            SanitizerPoisonObject(slots_ + i);
2306
0
        }
2307
2308
2.04M
        ctrl_[i] = h;
2309
2.04M
        ctrl_[((i - Group::kWidth) & capacity_) + 1 +
2310
2.04M
              ((Group::kWidth - 1) & capacity_)] = h;
2311
2.04M
    }
2312
2313
private:
2314
    friend struct RawHashSetTestOnlyAccess;
2315
2316
14.0M
    probe_seq<Group::kWidth> probe(size_t hashval) const {
2317
14.0M
        return probe_seq<Group::kWidth>(H1(hashval, ctrl_), capacity_);
2318
14.0M
    }
2319
2320
    // Reset all ctrl bytes back to kEmpty, except the sentinel.
2321
3.34k
    void reset_ctrl(size_t new_capacity) {
2322
3.34k
        std::memset(ctrl_, kEmpty, new_capacity + Group::kWidth);
2323
3.34k
        ctrl_[new_capacity] = kSentinel;
2324
3.34k
        SanitizerPoisonMemoryRegion(slots_, sizeof(slot_type) * new_capacity);
2325
3.34k
    }
2326
2327
3.34k
    void reset_growth_left(size_t new_capacity) {
2328
3.34k
        growth_left() = CapacityToGrowth(new_capacity) - size_;
2329
3.34k
    }
2330
2331
1.48M
    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
2331
1.48M
    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()
2332
2333
561
    const size_t& growth_left() const { return std::get<0>(settings_); }
2334
2335
    template <size_t N,
2336
              template <class, class, class, class> class RefSet,
2337
              class M, class P, class H, class E, class A>
2338
    friend class parallel_hash_set;
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_map;
2344
2345
    // The representation of the object has two modes:
2346
    //  - small: For capacities < kWidth-1
2347
    //  - large: For the rest.
2348
    //
2349
    // Differences:
2350
    //  - In small mode we are able to use the whole capacity. The extra control
2351
    //  bytes give us at least one "empty" control byte to stop the iteration.
2352
    //  This is important to make 1 a valid capacity.
2353
    //
2354
    //  - In small mode only the first `capacity()` control bytes after the
2355
    //  sentinel are valid. The rest contain dummy kEmpty values that do not
2356
    //  represent a real slot. This is important to take into account on
2357
    //  find_first_non_full(), where we never try ShouldInsertBackwards() for
2358
    //  small tables.
2359
0
    bool is_small() const { return capacity_ < Group::kWidth - 1; }
2360
2361
1.30M
    hasher& hash_ref() { return std::get<1>(settings_); }
2362
12.0M
    const hasher& hash_ref() const { return std::get<1>(settings_); }
2363
12.5M
    key_equal& eq_ref() { return std::get<2>(settings_); }
2364
    const key_equal& eq_ref() const { return std::get<2>(settings_); }
2365
2.05M
    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
2365
2.05M
    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()
2366
    const allocator_type& alloc_ref() const {
2367
        return std::get<3>(settings_);
2368
    }
2369
2370
    // TODO(alkis): Investigate removing some of these fields:
2371
    // - ctrl/slots can be derived from each other
2372
    // - size can be moved into the slot array
2373
    ctrl_t* ctrl_ = EmptyGroup<std_alloc_t>();    // [(capacity + 1) * ctrl_t]
2374
    slot_type* slots_ = nullptr;                  // [capacity * slot_type]
2375
    size_t size_ = 0;                             // number of full slots
2376
    size_t capacity_ = 0;                         // total number of slots
2377
    HashtablezInfoHandle infoz_;
2378
    std::tuple<size_t /* growth_left */, hasher, key_equal, allocator_type>
2379
        settings_{0, hasher{}, key_equal{}, allocator_type{}};
2380
};
2381
2382
2383
// --------------------------------------------------------------------------
2384
// --------------------------------------------------------------------------
2385
template <class Policy, class Hash, class Eq, class Alloc>
2386
class raw_hash_map : public raw_hash_set<Policy, Hash, Eq, Alloc> 
2387
{
2388
    // P is Policy. It's passed as a template argument to support maps that have
2389
    // incomplete types as values, as in unordered_map<K, IncompleteType>.
2390
    // MappedReference<> may be a non-reference type.
2391
    template <class P>
2392
    using MappedReference = decltype(P::value(
2393
               std::addressof(std::declval<typename raw_hash_map::reference>())));
2394
2395
    // MappedConstReference<> may be a non-reference type.
2396
    template <class P>
2397
    using MappedConstReference = decltype(P::value(
2398
               std::addressof(std::declval<typename raw_hash_map::const_reference>())));
2399
2400
    using KeyArgImpl =
2401
        KeyArg<IsTransparent<Eq>::value && IsTransparent<Hash>::value>;
2402
2403
    using Base = raw_hash_set<Policy, Hash, Eq, Alloc>;
2404
2405
public:
2406
    using key_type = typename Policy::key_type;
2407
    using mapped_type = typename Policy::mapped_type;
2408
    template <class K>
2409
    using key_arg = typename KeyArgImpl::template type<K, key_type>;
2410
2411
    static_assert(!std::is_reference<key_type>::value, "");
2412
2413
    // TODO(b/187807849): Evaluate whether to support reference mapped_type and
2414
    // remove this assertion if/when it is supported.
2415
     static_assert(!std::is_reference<mapped_type>::value, "");
2416
2417
    using iterator = typename raw_hash_map::raw_hash_set::iterator;
2418
    using const_iterator = typename raw_hash_map::raw_hash_set::const_iterator;
2419
2420
1.77k
    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
2420
1.18k
    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
2420
593
    raw_hash_map() {}
2421
    using Base::raw_hash_set; // use raw_hash_set constructor  
2422
2423
    // The last two template parameters ensure that both arguments are rvalues
2424
    // (lvalue arguments are handled by the overloads below). This is necessary
2425
    // for supporting bitfield arguments.
2426
    //
2427
    //   union { int n : 1; };
2428
    //   flat_hash_map<int, int> m;
2429
    //   m.insert_or_assign(n, n);
2430
    template <class K = key_type, class V = mapped_type, K* = nullptr,
2431
              V* = nullptr>
2432
    std::pair<iterator, bool> insert_or_assign(key_arg<K>&& k, V&& v) {
2433
        return insert_or_assign_impl(std::forward<K>(k), std::forward<V>(v));
2434
    }
2435
2436
    template <class K = key_type, class V = mapped_type, K* = nullptr>
2437
    std::pair<iterator, bool> insert_or_assign(key_arg<K>&& k, const V& v) {
2438
        return insert_or_assign_impl(std::forward<K>(k), v);
2439
    }
2440
2441
    template <class K = key_type, class V = mapped_type, V* = nullptr>
2442
    std::pair<iterator, bool> insert_or_assign(const key_arg<K>& k, V&& v) {
2443
        return insert_or_assign_impl(k, std::forward<V>(v));
2444
    }
2445
2446
    template <class K = key_type, class V = mapped_type>
2447
    std::pair<iterator, bool> insert_or_assign(const key_arg<K>& k, const V& v) {
2448
        return insert_or_assign_impl(k, v);
2449
    }
2450
2451
    template <class K = key_type, class V = mapped_type, K* = nullptr,
2452
              V* = nullptr>
2453
    iterator insert_or_assign(const_iterator, key_arg<K>&& k, V&& v) {
2454
        return insert_or_assign(std::forward<K>(k), std::forward<V>(v)).first;
2455
    }
2456
2457
    template <class K = key_type, class V = mapped_type, K* = nullptr>
2458
    iterator insert_or_assign(const_iterator, key_arg<K>&& k, const V& v) {
2459
        return insert_or_assign(std::forward<K>(k), v).first;
2460
    }
2461
2462
    template <class K = key_type, class V = mapped_type, V* = nullptr>
2463
    iterator insert_or_assign(const_iterator, const key_arg<K>& k, V&& v) {
2464
        return insert_or_assign(k, std::forward<V>(v)).first;
2465
    }
2466
2467
    template <class K = key_type, class V = mapped_type>
2468
    iterator insert_or_assign(const_iterator, const key_arg<K>& k, const V& v) {
2469
        return insert_or_assign(k, v).first;
2470
    }
2471
2472
    template <class K = key_type, class... Args,
2473
              typename std::enable_if<
2474
                  !std::is_convertible<K, const_iterator>::value, int>::type = 0,
2475
              K* = nullptr>
2476
    std::pair<iterator, bool> try_emplace(key_arg<K>&& k, Args&&... args) {
2477
        return try_emplace_impl(std::forward<K>(k), std::forward<Args>(args)...);
2478
    }
2479
2480
    template <class K = key_type, class... Args,
2481
              typename std::enable_if<
2482
                  !std::is_convertible<K, const_iterator>::value, int>::type = 0>
2483
    std::pair<iterator, bool> try_emplace(const key_arg<K>& k, Args&&... args) {
2484
        return try_emplace_impl(k, std::forward<Args>(args)...);
2485
    }
2486
2487
    template <class K = key_type, class... Args, K* = nullptr>
2488
    iterator try_emplace(const_iterator, key_arg<K>&& k, Args&&... args) {
2489
        return try_emplace(std::forward<K>(k), std::forward<Args>(args)...).first;
2490
    }
2491
2492
    template <class K = key_type, class... Args>
2493
    iterator try_emplace(const_iterator, const key_arg<K>& k, Args&&... args) {
2494
        return try_emplace(k, std::forward<Args>(args)...).first;
2495
    }
2496
2497
    template <class K = key_type, class P = Policy>
2498
    MappedReference<P> at(const key_arg<K>& key) {
2499
        auto it = this->find(key);
2500
        if (it == this->end()) 
2501
            phmap::base_internal::ThrowStdOutOfRange("phmap at(): lookup non-existent key");
2502
        return Policy::value(&*it);
2503
    }
2504
2505
    template <class K = key_type, class P = Policy>
2506
    MappedConstReference<P> at(const key_arg<K>& key) const {
2507
        auto it = this->find(key);
2508
        if (it == this->end())
2509
            phmap::base_internal::ThrowStdOutOfRange("phmap at(): lookup non-existent key");
2510
        return Policy::value(&*it);
2511
    }
2512
2513
    template <class K = key_type, class P = Policy, K* = nullptr>
2514
    MappedReference<P> operator[](key_arg<K>&& key) {
2515
        return Policy::value(&*try_emplace(std::forward<K>(key)).first);
2516
    }
2517
2518
    template <class K = key_type, class P = Policy>
2519
    MappedReference<P> operator[](const key_arg<K>& key) {
2520
        return Policy::value(&*try_emplace(key).first);
2521
    }
2522
2523
private:
2524
    template <class K, class V>
2525
    std::pair<iterator, bool> insert_or_assign_impl(K&& k, V&& v) {
2526
        size_t hashval = this->hash(k);
2527
        size_t offset = this->_find_key(k, hashval);
2528
        if (offset == (size_t)-1) {
2529
            offset = this->prepare_insert(hashval);
2530
            this->emplace_at(offset, std::forward<K>(k), std::forward<V>(v));
2531
            this->set_ctrl(offset, H2(hashval));
2532
            return {this->iterator_at(offset), true};
2533
        } 
2534
        Policy::value(&*this->iterator_at(offset)) = std::forward<V>(v);
2535
        return {this->iterator_at(offset), false};
2536
    }
2537
2538
    template <class K = key_type, class... Args>
2539
    std::pair<iterator, bool> try_emplace_impl(K&& k, Args&&... args) {
2540
        size_t hashval = this->hash(k);
2541
        size_t offset = this->_find_key(k, hashval);
2542
        if (offset == (size_t)-1) {
2543
            offset = this->prepare_insert(hashval);
2544
            this->emplace_at(offset, std::piecewise_construct,
2545
                             std::forward_as_tuple(std::forward<K>(k)),
2546
                             std::forward_as_tuple(std::forward<Args>(args)...));
2547
            this->set_ctrl(offset, H2(hashval));
2548
            return {this->iterator_at(offset), true};
2549
        }
2550
        return {this->iterator_at(offset), false};
2551
    }
2552
};
2553
2554
// ----------------------------------------------------------------------------
2555
// ----------------------------------------------------------------------------
2556
// Returns "random" seed.
2557
inline size_t RandomSeed() 
2558
0
{
2559
0
#if PHMAP_HAVE_THREAD_LOCAL
2560
0
    static thread_local size_t counter = 0;
2561
0
    size_t value = ++counter;
2562
0
#else   // PHMAP_HAVE_THREAD_LOCAL
2563
0
    static std::atomic<size_t> counter(0);
2564
0
    size_t value = counter.fetch_add(1, std::memory_order_relaxed);
2565
0
#endif  // PHMAP_HAVE_THREAD_LOCAL
2566
0
    return value ^ static_cast<size_t>(reinterpret_cast<uintptr_t>(&counter));
2567
0
}
2568
2569
// ----------------------------------------------------------------------------
2570
// ----------------------------------------------------------------------------
2571
template <size_t N,
2572
          template <class, class, class, class> class RefSet,
2573
          class Mtx_,
2574
          class Policy, class Hash, class Eq, class Alloc>
2575
class parallel_hash_set 
2576
{
2577
    using PolicyTraits = hash_policy_traits<Policy>;
2578
    using KeyArgImpl =
2579
        KeyArg<IsTransparent<Eq>::value && IsTransparent<Hash>::value>;
2580
2581
    static_assert(N <= 12, "N = 12 means 4096 hash tables!");
2582
    constexpr static size_t num_tables = 1 << N;
2583
    constexpr static size_t mask = num_tables - 1;
2584
2585
public:
2586
    using EmbeddedSet     = RefSet<Policy, Hash, Eq, Alloc>;
2587
    using EmbeddedIterator= typename EmbeddedSet::iterator;
2588
    using EmbeddedConstIterator= typename EmbeddedSet::const_iterator;
2589
    using constructor     = typename EmbeddedSet::constructor;
2590
    using init_type       = typename PolicyTraits::init_type;
2591
    using key_type        = typename PolicyTraits::key_type;
2592
    using slot_type       = typename PolicyTraits::slot_type;
2593
    using allocator_type  = Alloc;
2594
    using size_type       = size_t;
2595
    using difference_type = ptrdiff_t;
2596
    using hasher          = Hash;
2597
    using key_equal       = Eq;
2598
    using policy_type     = Policy;
2599
    using value_type      = typename PolicyTraits::value_type;
2600
    using reference       = value_type&;
2601
    using const_reference = const value_type&;
2602
    using pointer         = typename phmap::allocator_traits<
2603
        allocator_type>::template rebind_traits<value_type>::pointer;
2604
    using const_pointer   = typename phmap::allocator_traits<
2605
        allocator_type>::template rebind_traits<value_type>::const_pointer;
2606
2607
    // Alias used for heterogeneous lookup functions.
2608
    // `key_arg<K>` evaluates to `K` when the functors are transparent and to
2609
    // `key_type` otherwise. It permits template argument deduction on `K` for the
2610
    // transparent case.
2611
    // --------------------------------------------------------------------
2612
    template <class K>
2613
    using key_arg         = typename KeyArgImpl::template type<K, key_type>;
2614
2615
protected:
2616
    using Lockable      = phmap::LockableImpl<Mtx_>;
2617
    using UniqueLock    = typename Lockable::UniqueLock;
2618
    using SharedLock    = typename Lockable::SharedLock;
2619
    using ReadWriteLock = typename Lockable::ReadWriteLock;
2620
2621
    // --------------------------------------------------------------------
2622
    struct Inner : public Lockable
2623
    {
2624
        struct Params
2625
        {
2626
            size_t bucket_cnt;
2627
            const hasher& hashfn;
2628
            const key_equal& eq;
2629
            const allocator_type& alloc;
2630
        };
2631
2632
        Inner() {}
2633
2634
        Inner(Params const &p) : set_(p.bucket_cnt, p.hashfn, p.eq, p.alloc)
2635
        {}
2636
2637
        bool operator==(const Inner& o) const
2638
        {
2639
            typename Lockable::SharedLocks l(const_cast<Inner &>(*this), const_cast<Inner &>(o));
2640
            return set_ == o.set_;
2641
        }
2642
2643
        EmbeddedSet set_;
2644
    };
2645
2646
private:
2647
    // Give an early error when key_type is not hashable/eq.
2648
    // --------------------------------------------------------------------
2649
    auto KeyTypeCanBeHashed(const Hash& h, const key_type& k) -> decltype(h(k));
2650
    auto KeyTypeCanBeEq(const Eq& eq, const key_type& k)      -> decltype(eq(k, k));
2651
2652
    using AllocTraits     = phmap::allocator_traits<allocator_type>;
2653
2654
    static_assert(std::is_lvalue_reference<reference>::value,
2655
                  "Policy::element() must return a reference");
2656
2657
    template <typename T>
2658
    struct SameAsElementReference : std::is_same<
2659
        typename std::remove_cv<typename std::remove_reference<reference>::type>::type,
2660
        typename std::remove_cv<typename std::remove_reference<T>::type>::type> {};
2661
2662
    // An enabler for insert(T&&): T must be convertible to init_type or be the
2663
    // same as [cv] value_type [ref].
2664
    // Note: we separate SameAsElementReference into its own type to avoid using
2665
    // reference unless we need to. MSVC doesn't seem to like it in some
2666
    // cases.
2667
    // --------------------------------------------------------------------
2668
    template <class T>
2669
    using RequiresInsertable = typename std::enable_if<
2670
        phmap::disjunction<std::is_convertible<T, init_type>, SameAsElementReference<T>>::value, int>::type;
2671
2672
    // RequiresNotInit is a workaround for gcc prior to 7.1.
2673
    // See https://godbolt.org/g/Y4xsUh.
2674
    template <class T>
2675
    using RequiresNotInit =
2676
        typename std::enable_if<!std::is_same<T, init_type>::value, int>::type;
2677
2678
    template <class... Ts>
2679
    using IsDecomposable = IsDecomposable<void, PolicyTraits, Hash, Eq, Ts...>;
2680
2681
public:
2682
    static_assert(std::is_same<pointer, value_type*>::value,
2683
                  "Allocators with custom pointer types are not supported");
2684
    static_assert(std::is_same<const_pointer, const value_type*>::value,
2685
                  "Allocators with custom pointer types are not supported");
2686
2687
    // --------------------- i t e r a t o r ------------------------------
2688
    class iterator 
2689
    {
2690
        friend class parallel_hash_set;
2691
2692
    public:
2693
        using iterator_category = std::forward_iterator_tag;
2694
        using value_type        = typename parallel_hash_set::value_type;
2695
        using reference         =
2696
            phmap::conditional_t<PolicyTraits::constant_iterators::value,
2697
                                const value_type&, value_type&>;
2698
        using pointer           = phmap::remove_reference_t<reference>*;
2699
        using difference_type   = typename parallel_hash_set::difference_type;
2700
        using Inner             = typename parallel_hash_set::Inner;
2701
        using EmbeddedSet       = typename parallel_hash_set::EmbeddedSet;
2702
        using EmbeddedIterator  = typename EmbeddedSet::iterator;
2703
2704
        iterator() {}
2705
2706
        reference operator*()  const { return *it_; }
2707
        pointer   operator->() const { return &operator*(); }
2708
2709
        iterator& operator++() {
2710
            assert(inner_); // null inner means we are already at the end
2711
            ++it_;
2712
            skip_empty();
2713
            return *this;
2714
        }
2715
    
2716
        iterator operator++(int) {
2717
            assert(inner_);  // null inner means we are already at the end
2718
            auto tmp = *this;
2719
            ++*this;
2720
            return tmp;
2721
        }
2722
2723
        friend bool operator==(const iterator& a, const iterator& b) {
2724
            return a.inner_ == b.inner_ && (!a.inner_ || a.it_ == b.it_);
2725
        }
2726
2727
        friend bool operator!=(const iterator& a, const iterator& b) {
2728
            return !(a == b);
2729
        }
2730
2731
    private:
2732
        iterator(Inner *inner, Inner *inner_end, const EmbeddedIterator& it) : 
2733
            inner_(inner), inner_end_(inner_end), it_(it)  {  // for begin() and end()
2734
            if (inner)
2735
                it_end_ = inner->set_.end();
2736
        }
2737
2738
        void skip_empty() {
2739
            while (it_ == it_end_) {
2740
                ++inner_;
2741
                if (inner_ == inner_end_) {
2742
                    inner_ = nullptr; // marks end()
2743
                    break;
2744
                }
2745
                else {
2746
                    it_ = inner_->set_.begin();
2747
                    it_end_ = inner_->set_.end();
2748
                }
2749
            }
2750
        }
2751
2752
        Inner *inner_      = nullptr;
2753
        Inner *inner_end_  = nullptr;
2754
        EmbeddedIterator it_, it_end_;
2755
    };
2756
2757
    // --------------------- c o n s t   i t e r a t o r -----------------
2758
    class const_iterator 
2759
    {
2760
        friend class parallel_hash_set;
2761
2762
    public:
2763
        using iterator_category = typename iterator::iterator_category;
2764
        using value_type        = typename parallel_hash_set::value_type;
2765
        using reference         = typename parallel_hash_set::const_reference;
2766
        using pointer           = typename parallel_hash_set::const_pointer;
2767
        using difference_type   = typename parallel_hash_set::difference_type;
2768
        using Inner             = typename parallel_hash_set::Inner;
2769
2770
        const_iterator() {}
2771
        // Implicit construction from iterator.
2772
        const_iterator(iterator i) : iter_(std::move(i)) {}
2773
2774
        reference operator*()  const { return *(iter_); }
2775
        pointer   operator->() const { return iter_.operator->(); }
2776
2777
        const_iterator& operator++() {
2778
            ++iter_;
2779
            return *this;
2780
        }
2781
        const_iterator operator++(int) { return iter_++; }
2782
2783
        friend bool operator==(const const_iterator& a, const const_iterator& b) {
2784
            return a.iter_ == b.iter_;
2785
        }
2786
        friend bool operator!=(const const_iterator& a, const const_iterator& b) {
2787
            return !(a == b);
2788
        }
2789
2790
    private:
2791
        const_iterator(const Inner *inner, const Inner *inner_end, const EmbeddedIterator& it)
2792
            : iter_(const_cast<Inner**>(inner), 
2793
                    const_cast<Inner**>(inner_end),
2794
                    const_cast<EmbeddedIterator*>(it)) {}
2795
2796
        iterator iter_;
2797
    };
2798
2799
    using node_type = node_handle<Policy, hash_policy_traits<Policy>, Alloc>;
2800
    using insert_return_type = InsertReturnType<iterator, node_type>;
2801
2802
    // ------------------------- c o n s t r u c t o r s ------------------
2803
2804
    parallel_hash_set() noexcept(
2805
        std::is_nothrow_default_constructible<hasher>::value&&
2806
        std::is_nothrow_default_constructible<key_equal>::value&&
2807
        std::is_nothrow_default_constructible<allocator_type>::value) {}
2808
2809
#if  (__cplusplus >= 201703L || _MSVC_LANG >= 201402) && (defined(_MSC_VER) || defined(__clang__) || (defined(__GNUC__) && __GNUC__ > 6))
2810
    explicit parallel_hash_set(size_t bucket_cnt, 
2811
                               const hasher& hash_param    = hasher(),
2812
                               const key_equal& eq         = key_equal(),
2813
                               const allocator_type& alloc = allocator_type()) :
2814
        parallel_hash_set(typename Inner::Params{bucket_cnt, hash_param, eq, alloc}, 
2815
                          phmap::make_index_sequence<num_tables>{})
2816
    {}
2817
2818
    template <std::size_t... i>
2819
    parallel_hash_set(typename Inner::Params const &p,
2820
                      phmap::index_sequence<i...>) : sets_{((void)i, p)...}
2821
    {}
2822
#else
2823
    explicit parallel_hash_set(size_t bucket_cnt, 
2824
                               const hasher& hash_param    = hasher(),
2825
                               const key_equal& eq         = key_equal(),
2826
                               const allocator_type& alloc = allocator_type()) {
2827
        for (auto& inner : sets_)
2828
            inner.set_ = EmbeddedSet(bucket_cnt / N, hash_param, eq, alloc);
2829
    }
2830
#endif
2831
2832
    parallel_hash_set(size_t bucket_cnt, 
2833
                      const hasher& hash_param,
2834
                      const allocator_type& alloc)
2835
        : parallel_hash_set(bucket_cnt, hash_param, key_equal(), alloc) {}
2836
2837
    parallel_hash_set(size_t bucket_cnt, const allocator_type& alloc)
2838
        : parallel_hash_set(bucket_cnt, hasher(), key_equal(), alloc) {}
2839
2840
    explicit parallel_hash_set(const allocator_type& alloc)
2841
        : parallel_hash_set(0, hasher(), key_equal(), alloc) {}
2842
2843
    template <class InputIter>
2844
    parallel_hash_set(InputIter first, InputIter last, size_t bucket_cnt = 0,
2845
                      const hasher& hash_param = hasher(), const key_equal& eq = key_equal(),
2846
                      const allocator_type& alloc = allocator_type())
2847
        : parallel_hash_set(bucket_cnt, hash_param, eq, alloc) {
2848
        insert(first, last);
2849
    }
2850
2851
    template <class InputIter>
2852
    parallel_hash_set(InputIter first, InputIter last, size_t bucket_cnt,
2853
                      const hasher& hash_param, const allocator_type& alloc)
2854
        : parallel_hash_set(first, last, bucket_cnt, hash_param, key_equal(), alloc) {}
2855
2856
    template <class InputIter>
2857
    parallel_hash_set(InputIter first, InputIter last, size_t bucket_cnt,
2858
                      const allocator_type& alloc)
2859
        : parallel_hash_set(first, last, bucket_cnt, hasher(), key_equal(), alloc) {}
2860
2861
    template <class InputIter>
2862
    parallel_hash_set(InputIter first, InputIter last, const allocator_type& alloc)
2863
        : parallel_hash_set(first, last, 0, hasher(), key_equal(), alloc) {}
2864
2865
    // Instead of accepting std::initializer_list<value_type> as the first
2866
    // argument like std::unordered_set<value_type> does, we have two overloads
2867
    // that accept std::initializer_list<T> and std::initializer_list<init_type>.
2868
    // This is advantageous for performance.
2869
    //
2870
    //   // Turns {"abc", "def"} into std::initializer_list<std::string>, then copies
2871
    //   // the strings into the set.
2872
    //   std::unordered_set<std::string> s = {"abc", "def"};
2873
    //
2874
    //   // Turns {"abc", "def"} into std::initializer_list<const char*>, then
2875
    //   // copies the strings into the set.
2876
    //   phmap::flat_hash_set<std::string> s = {"abc", "def"};
2877
    //
2878
    // The same trick is used in insert().
2879
    //
2880
    // The enabler is necessary to prevent this constructor from triggering where
2881
    // the copy constructor is meant to be called.
2882
    //
2883
    //   phmap::flat_hash_set<int> a, b{a};
2884
    //
2885
    // RequiresNotInit<T> is a workaround for gcc prior to 7.1.
2886
    // --------------------------------------------------------------------
2887
    template <class T, RequiresNotInit<T> = 0, RequiresInsertable<T> = 0>
2888
    parallel_hash_set(std::initializer_list<T> init, size_t bucket_cnt = 0,
2889
                      const hasher& hash_param = hasher(), const key_equal& eq = key_equal(),
2890
                      const allocator_type& alloc = allocator_type())
2891
        : parallel_hash_set(init.begin(), init.end(), bucket_cnt, hash_param, eq, alloc) {}
2892
2893
    parallel_hash_set(std::initializer_list<init_type> 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
    template <class T, RequiresNotInit<T> = 0, RequiresInsertable<T> = 0>
2899
    parallel_hash_set(std::initializer_list<T> init, size_t bucket_cnt,
2900
                      const hasher& hash_param, const allocator_type& alloc)
2901
        : parallel_hash_set(init, bucket_cnt, hash_param, key_equal(), alloc) {}
2902
2903
    parallel_hash_set(std::initializer_list<init_type> init, size_t bucket_cnt,
2904
                      const hasher& hash_param, const allocator_type& alloc)
2905
        : parallel_hash_set(init, bucket_cnt, hash_param, key_equal(), alloc) {}
2906
2907
    template <class T, RequiresNotInit<T> = 0, RequiresInsertable<T> = 0>
2908
    parallel_hash_set(std::initializer_list<T> init, size_t bucket_cnt,
2909
                      const allocator_type& alloc)
2910
        : parallel_hash_set(init, bucket_cnt, hasher(), key_equal(), alloc) {}
2911
2912
    parallel_hash_set(std::initializer_list<init_type> init, size_t bucket_cnt,
2913
                      const allocator_type& alloc)
2914
        : parallel_hash_set(init, bucket_cnt, hasher(), key_equal(), alloc) {}
2915
2916
    template <class T, RequiresNotInit<T> = 0, RequiresInsertable<T> = 0>
2917
    parallel_hash_set(std::initializer_list<T> init, const allocator_type& alloc)
2918
        : parallel_hash_set(init, 0, hasher(), key_equal(), alloc) {}
2919
  
2920
    parallel_hash_set(std::initializer_list<init_type> init,
2921
                      const allocator_type& alloc)
2922
        : parallel_hash_set(init, 0, hasher(), key_equal(), alloc) {}
2923
2924
    parallel_hash_set(const parallel_hash_set& that)
2925
        : parallel_hash_set(that, AllocTraits::select_on_container_copy_construction(
2926
                                that.alloc_ref())) {}
2927
2928
    parallel_hash_set(const parallel_hash_set& that, const allocator_type& a)
2929
        : parallel_hash_set(0, that.hash_ref(), that.eq_ref(), a) {
2930
        for (size_t i=0; i<num_tables; ++i)
2931
            sets_[i].set_ = { that.sets_[i].set_, a };
2932
    }
2933
  
2934
    parallel_hash_set(parallel_hash_set&& that) noexcept(
2935
        std::is_nothrow_copy_constructible<hasher>::value&&
2936
        std::is_nothrow_copy_constructible<key_equal>::value&&
2937
        std::is_nothrow_copy_constructible<allocator_type>::value)
2938
        : parallel_hash_set(std::move(that), that.alloc_ref()) {
2939
    }
2940
2941
    parallel_hash_set(parallel_hash_set&& that, const allocator_type& a)
2942
    {
2943
        for (size_t i=0; i<num_tables; ++i)
2944
            sets_[i].set_ = { std::move(that.sets_[i]).set_, a };
2945
    }
2946
2947
    parallel_hash_set& operator=(const parallel_hash_set& that) {
2948
        for (size_t i=0; i<num_tables; ++i)
2949
            sets_[i].set_ = that.sets_[i].set_;
2950
        return *this;
2951
    }
2952
2953
    parallel_hash_set& operator=(parallel_hash_set&& that) noexcept(
2954
        phmap::allocator_traits<allocator_type>::is_always_equal::value &&
2955
        std::is_nothrow_move_assignable<hasher>::value &&
2956
        std::is_nothrow_move_assignable<key_equal>::value) {
2957
        for (size_t i=0; i<num_tables; ++i)
2958
            sets_[i].set_ = std::move(that.sets_[i].set_);
2959
        return *this;
2960
    }
2961
2962
    ~parallel_hash_set() {}
2963
2964
    iterator begin() {
2965
        auto it = iterator(&sets_[0], &sets_[0] + num_tables, sets_[0].set_.begin());
2966
        it.skip_empty();
2967
        return it;
2968
    }
2969
2970
    iterator       end()          { return iterator(); }
2971
    const_iterator begin()  const { return const_cast<parallel_hash_set *>(this)->begin(); }
2972
    const_iterator end()    const { return const_cast<parallel_hash_set *>(this)->end(); }
2973
    const_iterator cbegin() const { return begin(); }
2974
    const_iterator cend()   const { return end(); }
2975
2976
    bool empty() const { return !size(); }
2977
2978
    size_t size() const { 
2979
        size_t sz = 0;
2980
        for (const auto& inner : sets_)
2981
            sz += inner.set_.size();
2982
        return sz; 
2983
    }
2984
  
2985
    size_t capacity() const { 
2986
        size_t c = 0;
2987
        for (const auto& inner : sets_)
2988
            c += inner.set_.capacity();
2989
        return c; 
2990
    }
2991
2992
    size_t max_size() const { return (std::numeric_limits<size_t>::max)(); }
2993
2994
    PHMAP_ATTRIBUTE_REINITIALIZES void clear() {
2995
        for (auto& inner : sets_)
2996
        {
2997
            UniqueLock m(inner);
2998
            inner.set_.clear();
2999
        }
3000
    }
3001
3002
    // extension - clears only soecified submap
3003
    // ----------------------------------------
3004
    void clear(std::size_t submap_index) {
3005
        Inner& inner = sets_[submap_index];
3006
        UniqueLock m(inner);
3007
        inner.set_.clear();
3008
    }
3009
3010
    // This overload kicks in when the argument is an rvalue of insertable and
3011
    // decomposable type other than init_type.
3012
    //
3013
    //   flat_hash_map<std::string, int> m;
3014
    //   m.insert(std::make_pair("abc", 42));
3015
    // --------------------------------------------------------------------
3016
    template <class T, RequiresInsertable<T> = 0,
3017
              typename std::enable_if<IsDecomposable<T>::value, int>::type = 0,
3018
              T* = nullptr>
3019
    std::pair<iterator, bool> insert(T&& value) {
3020
        return emplace(std::forward<T>(value));
3021
    }
3022
3023
    // This overload kicks in when the argument is a bitfield or an lvalue of
3024
    // insertable and decomposable type.
3025
    //
3026
    //   union { int n : 1; };
3027
    //   flat_hash_set<int> s;
3028
    //   s.insert(n);
3029
    //
3030
    //   flat_hash_set<std::string> s;
3031
    //   const char* p = "hello";
3032
    //   s.insert(p);
3033
    //
3034
    // TODO(romanp): Once we stop supporting gcc 5.1 and below, replace
3035
    // RequiresInsertable<T> with RequiresInsertable<const T&>.
3036
    // We are hitting this bug: https://godbolt.org/g/1Vht4f.
3037
    // --------------------------------------------------------------------
3038
    template <
3039
        class T, RequiresInsertable<T> = 0,
3040
        typename std::enable_if<IsDecomposable<const T&>::value, int>::type = 0>
3041
    std::pair<iterator, bool> insert(const T& value) {
3042
        return emplace(value);
3043
    }
3044
3045
    // This overload kicks in when the argument is an rvalue of init_type. Its
3046
    // purpose is to handle brace-init-list arguments.
3047
    //
3048
    //   flat_hash_set<std::pair<std::string, int>> s;
3049
    //   s.insert({"abc", 42});
3050
    // --------------------------------------------------------------------
3051
    std::pair<iterator, bool> insert(init_type&& value) {
3052
        return emplace(std::move(value));
3053
    }
3054
3055
    template <class T, RequiresInsertable<T> = 0,
3056
              typename std::enable_if<IsDecomposable<T>::value, int>::type = 0,
3057
              T* = nullptr>
3058
    iterator insert(const_iterator, T&& value) {
3059
        return insert(std::forward<T>(value)).first;
3060
    }
3061
3062
    // TODO(romanp): Once we stop supporting gcc 5.1 and below, replace
3063
    // RequiresInsertable<T> with RequiresInsertable<const T&>.
3064
    // We are hitting this bug: https://godbolt.org/g/1Vht4f.
3065
    // --------------------------------------------------------------------
3066
    template <
3067
        class T, RequiresInsertable<T> = 0,
3068
        typename std::enable_if<IsDecomposable<const T&>::value, int>::type = 0>
3069
    iterator insert(const_iterator, const T& value) {
3070
        return insert(value).first;
3071
    }
3072
3073
    iterator insert(const_iterator, init_type&& value) {
3074
        return insert(std::move(value)).first;
3075
    }
3076
3077
    template <class InputIt>
3078
    void insert(InputIt first, InputIt last) {
3079
        for (; first != last; ++first) insert(*first);
3080
    }
3081
3082
    template <class T, RequiresNotInit<T> = 0, RequiresInsertable<const T&> = 0>
3083
    void insert(std::initializer_list<T> ilist) {
3084
        insert(ilist.begin(), ilist.end());
3085
    }
3086
3087
    void insert(std::initializer_list<init_type> ilist) {
3088
        insert(ilist.begin(), ilist.end());
3089
    }
3090
3091
    insert_return_type insert(node_type&& node) {
3092
        if (!node) 
3093
            return {end(), false, node_type()};
3094
        auto& key      = node.key();
3095
        size_t hashval = this->hash(key);
3096
        Inner& inner   = sets_[subidx(hashval)];
3097
        auto&  set     = inner.set_;
3098
3099
        UniqueLock m(inner);
3100
        auto   res  = set.insert(std::move(node), hashval);
3101
        return { make_iterator(&inner, res.position),
3102
                 res.inserted,
3103
                 res.inserted ? node_type() : std::move(res.node) };
3104
    }
3105
3106
    iterator insert(const_iterator, node_type&& node) {
3107
        return insert(std::move(node)).first;
3108
    }
3109
3110
    struct ReturnKey_ 
3111
    {
3112
        template <class Key, class... Args>
3113
        Key operator()(Key&& k, const Args&...) const {
3114
            return std::forward<Key>(k);
3115
        }
3116
    };
3117
3118
    // --------------------------------------------------------------------
3119
    // phmap extension: emplace_with_hash
3120
    // ----------------------------------
3121
    // same as emplace, but hashval is provided
3122
    // --------------------------------------------------------------------
3123
    struct EmplaceDecomposableHashval 
3124
    {
3125
        template <class K, class... Args>
3126
        std::pair<iterator, bool> operator()(const K& key, Args&&... args) const {
3127
            return s.emplace_decomposable_with_hash(key, hashval, std::forward<Args>(args)...);
3128
        }
3129
        parallel_hash_set& s;
3130
        size_t hashval;
3131
    };
3132
3133
    // This overload kicks in if we can deduce the key from args. This enables us
3134
    // to avoid constructing value_type if an entry with the same key already
3135
    // exists.
3136
    //
3137
    // For example:
3138
    //
3139
    //   flat_hash_map<std::string, std::string> m = {{"abc", "def"}};
3140
    //   // Creates no std::string copies and makes no heap allocations.
3141
    //   m.emplace("abc", "xyz");
3142
    // --------------------------------------------------------------------
3143
    template <class... Args, typename std::enable_if<IsDecomposable<Args...>::value, int>::type = 0>
3144
    std::pair<iterator, bool> emplace_with_hash(size_t hashval, Args&&... args) {
3145
        return PolicyTraits::apply(EmplaceDecomposableHashval{*this, hashval},
3146
                                   std::forward<Args>(args)...);
3147
    }
3148
3149
    // This overload kicks in if we cannot deduce the key from args. It constructs
3150
    // value_type unconditionally and then either moves it into the table or
3151
    // destroys.
3152
    // --------------------------------------------------------------------
3153
    template <class... Args, typename std::enable_if<!IsDecomposable<Args...>::value, int>::type = 0>
3154
    std::pair<iterator, bool> emplace_with_hash(size_t hashval, Args&&... args) {
3155
        typename phmap::aligned_storage<sizeof(slot_type), alignof(slot_type)>::type raw;
3156
        slot_type* slot = reinterpret_cast<slot_type*>(&raw);
3157
3158
        PolicyTraits::construct(&alloc_ref(), slot, std::forward<Args>(args)...);
3159
        const auto& elem = PolicyTraits::element(slot);
3160
        Inner& inner    = sets_[subidx(hashval)];
3161
        auto&  set      = inner.set_;
3162
        UniqueLock m(inner);
3163
        typename EmbeddedSet::template InsertSlotWithHash<true> f { inner.set_, std::move(*slot), hashval };
3164
        return make_rv(&inner, PolicyTraits::apply(std::move(f), elem));
3165
    }
3166
3167
    template <class... Args>
3168
    iterator emplace_hint_with_hash(size_t hashval, const_iterator, Args&&... args) {
3169
        return emplace_with_hash(hashval, std::forward<Args>(args)...).first;
3170
    }
3171
3172
    // --------------------------------------------------------------------
3173
    // end of phmap expension
3174
    // --------------------------------------------------------------------
3175
3176
    template <class K, class... Args>
3177
    std::pair<iterator, bool> emplace_decomposable_with_hash(const K& key, size_t hashval, Args&&... args)
3178
    {
3179
        Inner& inner   = sets_[subidx(hashval)];
3180
        auto&  set     = inner.set_;
3181
        UniqueLock m(inner);
3182
        
3183
        size_t offset = set._find_key(key, hashval);
3184
        if (offset == (size_t)-1) {
3185
            offset = set.prepare_insert(hashval);
3186
            set.emplace_at(offset, std::forward<Args>(args)...);
3187
            set.set_ctrl(offset, H2(hashval));
3188
            return make_rv(&inner, {set.iterator_at(offset), true});
3189
        }
3190
        return make_rv(&inner, {set.iterator_at(offset), false});
3191
    }
3192
3193
    template <class K, class... Args>
3194
    std::pair<iterator, bool> emplace_decomposable(const K& key, Args&&... args)
3195
    {
3196
        return emplace_decomposable_with_hash(key, this->hash(key), std::forward<Args>(args)...);
3197
    }
3198
3199
    struct EmplaceDecomposable 
3200
    {
3201
        template <class K, class... Args>
3202
        std::pair<iterator, bool> operator()(const K& key, Args&&... args) const {
3203
            return s.emplace_decomposable(key, std::forward<Args>(args)...);
3204
        }
3205
        parallel_hash_set& s;
3206
    };
3207
3208
    // This overload kicks in if we can deduce the key from args. This enables us
3209
    // to avoid constructing value_type if an entry with the same key already
3210
    // exists.
3211
    //
3212
    // For example:
3213
    //
3214
    //   flat_hash_map<std::string, std::string> m = {{"abc", "def"}};
3215
    //   // Creates no std::string copies and makes no heap allocations.
3216
    //   m.emplace("abc", "xyz");
3217
    // --------------------------------------------------------------------
3218
    template <class... Args, typename std::enable_if<IsDecomposable<Args...>::value, int>::type = 0>
3219
    std::pair<iterator, bool> emplace(Args&&... args) {
3220
        return PolicyTraits::apply(EmplaceDecomposable{*this}, std::forward<Args>(args)...);
3221
    }
3222
3223
    // This overload kicks in if we cannot deduce the key from args. It constructs
3224
    // value_type unconditionally and then either moves it into the table or
3225
    // destroys.
3226
    // --------------------------------------------------------------------
3227
    template <class... Args, typename std::enable_if<!IsDecomposable<Args...>::value, int>::type = 0>
3228
    std::pair<iterator, bool> emplace(Args&&... args) {
3229
        typename phmap::aligned_storage<sizeof(slot_type), alignof(slot_type)>::type raw;
3230
        slot_type* slot = reinterpret_cast<slot_type*>(&raw);
3231
        PolicyTraits::construct(&alloc_ref(), slot, std::forward<Args>(args)...);
3232
3233
        const auto& elem = PolicyTraits::element(slot);
3234
        size_t hashval   = this->hash(PolicyTraits::key(slot));
3235
        Inner& inner     = sets_[subidx(hashval)];
3236
        auto&  set       = inner.set_;
3237
        UniqueLock m(inner);
3238
        typename EmbeddedSet::template InsertSlotWithHash<true> f { inner.set_, std::move(*slot), hashval };
3239
        return make_rv(&inner, PolicyTraits::apply(std::move(f), elem));
3240
    }
3241
3242
    template <class... Args>
3243
    iterator emplace_hint(const_iterator, Args&&... args) {
3244
        return emplace(std::forward<Args>(args)...).first;
3245
    }
3246
3247
    iterator make_iterator(Inner* inner, const EmbeddedIterator it)
3248
    {
3249
        if (it == inner->set_.end())
3250
            return iterator();
3251
        return iterator(inner, &sets_[0] + num_tables, it);
3252
    }
3253
3254
    std::pair<iterator, bool> make_rv(Inner* inner, 
3255
                                      const std::pair<EmbeddedIterator, bool>& res)
3256
    {
3257
        return {iterator(inner, &sets_[0] + num_tables, res.first), res.second};
3258
    }
3259
3260
    // lazy_emplace
3261
    // ------------
3262
    template <class K = key_type, class F>
3263
    iterator lazy_emplace_with_hash(const key_arg<K>& key, size_t hashval, F&& f) {
3264
        Inner& inner = sets_[subidx(hashval)];
3265
        auto&  set   = inner.set_;
3266
        UniqueLock m(inner);
3267
        size_t offset = set._find_key(key, hashval);
3268
        if (offset == (size_t)-1) {
3269
            offset = set.prepare_insert(hashval);
3270
            set.lazy_emplace_at(offset, std::forward<F>(f));
3271
            set.set_ctrl(offset, H2(hashval));
3272
        }
3273
        return make_iterator(&inner, set.iterator_at(offset));
3274
    }
3275
3276
    template <class K = key_type, class F>
3277
    iterator lazy_emplace(const key_arg<K>& key, F&& f) {
3278
        return lazy_emplace_with_hash(key, this->hash(key), std::forward<F>(f));
3279
    }
3280
    
3281
    // emplace_single
3282
    // --------------
3283
    template <class K = key_type, class F>
3284
    void emplace_single_with_hash(const key_arg<K>& key, size_t hashval, F&& f) {
3285
        Inner& inner = sets_[subidx(hashval)];
3286
        auto&  set   = inner.set_;
3287
        UniqueLock m(inner);
3288
        set.emplace_single_with_hash(key, hashval, std::forward<F>(f));
3289
    }
3290
3291
    template <class K = key_type, class F>
3292
    void emplace_single(const key_arg<K>& key, F&& f) {
3293
        emplace_single_with_hash<K, F>(key, this->hash(key), std::forward<F>(f));
3294
    }
3295
3296
    // if set contains key, lambda is called with the value_type (under read lock protection),
3297
    // and if_contains returns true. This is a const API and lambda should not modify the value
3298
    // -----------------------------------------------------------------------------------------
3299
    template <class K = key_type, class F>
3300
    bool if_contains(const key_arg<K>& key, F&& f) const {
3301
        return const_cast<parallel_hash_set*>(this)->template 
3302
            modify_if_impl<K, F, SharedLock>(key, std::forward<F>(f));
3303
    }
3304
3305
    // if set contains key, lambda is called with the value_type  without read lock protection,
3306
    // and if_contains_unsafe returns true. This is a const API and lambda should not modify the value
3307
    // This should be used only if we know that no other thread may be mutating the set at the time.
3308
    // -----------------------------------------------------------------------------------------
3309
    template <class K = key_type, class F>
3310
    bool if_contains_unsafe(const key_arg<K>& key, F&& f) const {
3311
        return const_cast<parallel_hash_set*>(this)->template 
3312
            modify_if_impl<K, F, LockableBaseImpl<phmap::NullMutex>::DoNothing>(key, std::forward<F>(f));
3313
    }
3314
3315
    // if map contains key, lambda is called with the value_type  (under write lock protection),
3316
    // and modify_if returns true. This is a non-const API and lambda is allowed to modify the mapped value
3317
    // ----------------------------------------------------------------------------------------------------
3318
    template <class K = key_type, class F>
3319
    bool modify_if(const key_arg<K>& key, F&& f) {
3320
        return modify_if_impl<K, F, UniqueLock>(key, std::forward<F>(f));
3321
    }
3322
3323
    // -----------------------------------------------------------------------------------------
3324
    template <class K = key_type, class F, class L>
3325
    bool modify_if_impl(const key_arg<K>& key, F&& f) {
3326
#if __cplusplus >= 201703L
3327
        static_assert(std::is_invocable<F, value_type&>::value);
3328
#endif
3329
        L m;
3330
        auto ptr = this->template find_ptr<K, L>(key, this->hash(key), m);
3331
        if (ptr == nullptr)
3332
            return false;
3333
        std::forward<F>(f)(*ptr);
3334
        return true;
3335
    }
3336
3337
    // if map contains key, lambda is called with the mapped value  (under write lock protection).
3338
    // If the lambda returns true, the key is subsequently erased from the map (the write lock
3339
    // is only released after erase).
3340
    // returns true if key was erased, false otherwise.
3341
    // ----------------------------------------------------------------------------------------------------
3342
    template <class K = key_type, class F>
3343
    bool erase_if(const key_arg<K>& key, F&& f) {
3344
        return !!erase_if_impl<K, F, ReadWriteLock>(key, std::forward<F>(f));
3345
    }
3346
3347
    template <class K = key_type, class F, class L>
3348
    size_type erase_if_impl(const key_arg<K>& key, F&& f) {
3349
#if __cplusplus >= 201703L
3350
        static_assert(std::is_invocable<F, value_type&>::value);
3351
#endif
3352
        auto hashval = this->hash(key);
3353
        Inner& inner = sets_[subidx(hashval)];
3354
        auto& set = inner.set_;
3355
        L m(inner);
3356
        auto it = set.find(key, hashval);
3357
        if (it == set.end())
3358
            return 0;
3359
        if (m.switch_to_unique()) {
3360
            // we did an unlock/lock, need to call `find()` again
3361
            it = set.find(key, hashval);
3362
            if (it == set.end())
3363
                return 0;
3364
        }
3365
        if (std::forward<F>(f)(const_cast<value_type &>(*it)))
3366
        {
3367
            set._erase(it);
3368
            return 1;
3369
        }
3370
        return 0;
3371
    }
3372
3373
    // if map already  contains key, the first lambda is called with the mapped value (under 
3374
    // write lock protection) and can update the mapped value.
3375
    // if map does not contains key, the second lambda is called and it should invoke the 
3376
    // passed constructor to construct the value
3377
    // returns true if key was not already present, false otherwise.
3378
    // ---------------------------------------------------------------------------------------
3379
    template <class K = key_type, class FExists, class FEmplace>
3380
    bool lazy_emplace_l(const key_arg<K>& key, FExists&& fExists, FEmplace&& fEmplace) {
3381
        size_t hashval = this->hash(key);
3382
        UniqueLock m;
3383
        auto res = this->find_or_prepare_insert_with_hash(hashval, key, m);
3384
        Inner* inner = std::get<0>(res);
3385
        if (std::get<2>(res)) {
3386
            // key not found. call fEmplace lambda which should invoke passed constructor
3387
            inner->set_.lazy_emplace_at(std::get<1>(res), std::forward<FEmplace>(fEmplace));
3388
            inner->set_.set_ctrl(std::get<1>(res), H2(hashval));
3389
        } else {
3390
            // key found. Call fExists lambda. In case of the set, non "key" part of value_type can be changed
3391
            auto it = this->iterator_at(inner, inner->set_.iterator_at(std::get<1>(res)));
3392
            std::forward<FExists>(fExists)(const_cast<value_type &>(*it)); 
3393
        }
3394
        return std::get<2>(res);
3395
    }
3396
3397
    // Extension API: support iterating over all values
3398
    //
3399
    // flat_hash_set<std::string> s;
3400
    // s.insert(...);
3401
    // s.for_each([](auto const & key) {
3402
    //    // Safely iterates over all the keys
3403
    // });
3404
    template <class F>
3405
    void for_each(F&& fCallback) const {
3406
        for (auto const& inner : sets_) {
3407
            SharedLock m(const_cast<Inner&>(inner));
3408
            std::for_each(inner.set_.begin(), inner.set_.end(), fCallback);
3409
        }
3410
    }
3411
3412
    // this version allows to modify the values
3413
    template <class F>
3414
    void for_each_m(F&& fCallback) {
3415
        for (auto& inner : sets_) {
3416
            UniqueLock m(inner);
3417
            std::for_each(inner.set_.begin(), inner.set_.end(), fCallback);
3418
        }
3419
    }
3420
3421
#if __cplusplus >= 201703L
3422
    template <class ExecutionPolicy, class F>
3423
    void for_each(ExecutionPolicy&& policy, F&& fCallback) const {
3424
        std::for_each(
3425
            std::forward<ExecutionPolicy>(policy), sets_.begin(), sets_.end(),
3426
            [&](auto const& inner) {
3427
                SharedLock m(const_cast<Inner&>(inner));
3428
                std::for_each(inner.set_.begin(), inner.set_.end(), fCallback);
3429
            }
3430
        );
3431
    }
3432
3433
    template <class ExecutionPolicy, class F>
3434
    void for_each_m(ExecutionPolicy&& policy, F&& fCallback) {
3435
        std::for_each(
3436
            std::forward<ExecutionPolicy>(policy), sets_.begin(), sets_.end(),
3437
            [&](auto& inner) {
3438
                UniqueLock m(inner);
3439
                std::for_each(inner.set_.begin(), inner.set_.end(), fCallback);
3440
            }
3441
        );
3442
    }
3443
#endif
3444
3445
    // Extension API: access internal submaps by index
3446
    // under lock protection
3447
    // ex: m.with_submap(i, [&](const Map::EmbeddedSet& set) {
3448
    //        for (auto& p : set) { ...; }});
3449
    // -------------------------------------------------
3450
    template <class F>
3451
    void with_submap(size_t idx, F&& fCallback) const {
3452
        const Inner& inner     = sets_[idx];
3453
        const auto&  set = inner.set_;
3454
        SharedLock m(const_cast<Inner&>(inner));
3455
        fCallback(set);
3456
    }
3457
3458
    template <class F>
3459
    void with_submap_m(size_t idx, F&& fCallback) {
3460
        Inner& inner   = sets_[idx];
3461
        auto&  set     = inner.set_;
3462
        UniqueLock m(inner);
3463
        fCallback(set);
3464
    }
3465
3466
    // unsafe, for internal use only
3467
    Inner& get_inner(size_t idx) {
3468
        return  sets_[idx];
3469
    }
3470
3471
    const Inner& get_inner(size_t idx) const {
3472
        return  sets_[idx];
3473
    }
3474
3475
    // Extension API: support for heterogeneous keys.
3476
    //
3477
    //   std::unordered_set<std::string> s;
3478
    //   // Turns "abc" into std::string.
3479
    //   s.erase("abc");
3480
    //
3481
    //   flat_hash_set<std::string> s;
3482
    //   // Uses "abc" directly without copying it into std::string.
3483
    //   s.erase("abc");
3484
    //
3485
    // --------------------------------------------------------------------
3486
    template <class K = key_type>
3487
    size_type erase(const key_arg<K>& key) {
3488
        auto always_erase =  [](const value_type&){ return true; };
3489
        return erase_if_impl<K, decltype(always_erase), ReadWriteLock>(key, std::move(always_erase));
3490
    }
3491
3492
    // --------------------------------------------------------------------
3493
    iterator erase(const_iterator cit) { return erase(cit.iter_); }
3494
3495
    // Erases the element pointed to by `it`.  Unlike `std::unordered_set::erase`,
3496
    // this method returns void to reduce algorithmic complexity to O(1).  In
3497
    // order to erase while iterating across a map, use the following idiom (which
3498
    // also works for standard containers):
3499
    //
3500
    // for (auto it = m.begin(), end = m.end(); it != end;) {
3501
    //   if (<pred>) {
3502
    //     m._erase(it++);
3503
    //   } else {
3504
    //     ++it;
3505
    //   }
3506
    // }
3507
    //
3508
    // Do not use erase APIs taking iterators when accessing the map concurrently
3509
    // --------------------------------------------------------------------
3510
    void _erase(iterator it) {
3511
        Inner* inner = it.inner_;
3512
        assert(inner != nullptr);
3513
        auto&  set   = inner->set_;
3514
        // UniqueLock m(*inner); // don't lock here 
3515
        
3516
        set._erase(it.it_);
3517
    }
3518
    void _erase(const_iterator cit) { _erase(cit.iter_); }
3519
3520
    // This overload is necessary because otherwise erase<K>(const K&) would be
3521
    // a better match if non-const iterator is passed as an argument.
3522
    // Do not use erase APIs taking iterators when accessing the map concurrently
3523
    // --------------------------------------------------------------------
3524
    iterator erase(iterator it) { _erase(it++); return it; }
3525
3526
    iterator erase(const_iterator first, const_iterator last) {
3527
        while (first != last) {
3528
            _erase(first++);
3529
        }
3530
        return last.iter_;
3531
    }
3532
3533
    // Moves elements from `src` into `this`.
3534
    // If the element already exists in `this`, it is left unmodified in `src`.
3535
    // Do not use erase APIs taking iterators when accessing the map concurrently
3536
    // --------------------------------------------------------------------
3537
    template <typename E = Eq>
3538
    void merge(parallel_hash_set<N, RefSet, Mtx_, Policy, Hash, E, Alloc>& src) {  // NOLINT
3539
        assert(this != &src);
3540
        if (this != &src)
3541
        {
3542
            for (size_t i=0; i<num_tables; ++i)
3543
            {
3544
                typename Lockable::UniqueLocks l(sets_[i], src.sets_[i]);
3545
                sets_[i].set_.merge(src.sets_[i].set_);
3546
            }
3547
        }
3548
    }
3549
3550
    template <typename E = Eq>
3551
    void merge(parallel_hash_set<N, RefSet, Mtx_, Policy, Hash, E, Alloc>&& src) {
3552
        merge(src);
3553
    }
3554
3555
    node_type extract(const_iterator position) {
3556
        return position.iter_.inner_->set_.extract(EmbeddedConstIterator(position.iter_.it_));
3557
    }
3558
3559
    template <
3560
        class K = key_type,
3561
        typename std::enable_if<!std::is_same<K, iterator>::value, int>::type = 0>
3562
    node_type extract(const key_arg<K>& key) {
3563
        UniqueLock m;
3564
        auto it = this->template find<K, UniqueLock>(key, this->hash(key), m);
3565
        return it == end() ? node_type() : extract(const_iterator{it});
3566
    }
3567
3568
    template<class Mtx2_>
3569
    void swap(parallel_hash_set<N, RefSet, Mtx2_, Policy, Hash, Eq, Alloc>& that)
3570
        noexcept(IsNoThrowSwappable<EmbeddedSet>() &&
3571
                 (!AllocTraits::propagate_on_container_swap::value ||
3572
                  IsNoThrowSwappable<allocator_type>(typename AllocTraits::propagate_on_container_swap{})))
3573
    {
3574
        using std::swap;
3575
        using Lockable2 = phmap::LockableImpl<Mtx2_>;
3576
         
3577
        for (size_t i=0; i<num_tables; ++i)
3578
        {
3579
            typename Lockable::UniqueLock l(sets_[i]);
3580
            typename Lockable2::UniqueLock l2(that.get_inner(i));
3581
            swap(sets_[i].set_, that.get_inner(i).set_);
3582
        }
3583
    }
3584
3585
    void rehash(size_t n) {
3586
        size_t nn = n / num_tables;
3587
        for (auto& inner : sets_)
3588
        {
3589
            UniqueLock m(inner);
3590
            inner.set_.rehash(nn);
3591
        }
3592
    }
3593
3594
    void reserve(size_t n) 
3595
    {
3596
        if (n <= capacity())
3597
            return;
3598
        size_t target = GrowthToLowerboundCapacity(n);
3599
        size_t normalized = num_tables * NormalizeCapacity(n / num_tables);
3600
        rehash(normalized > target ? normalized : target); 
3601
    }
3602
3603
    // Extension API: support for heterogeneous keys.
3604
    //
3605
    //   std::unordered_set<std::string> s;
3606
    //   // Turns "abc" into std::string.
3607
    //   s.count("abc");
3608
    //
3609
    //   ch_set<std::string> s;
3610
    //   // Uses "abc" directly without copying it into std::string.
3611
    //   s.count("abc");
3612
    // --------------------------------------------------------------------
3613
    template <class K = key_type>
3614
    size_t count(const key_arg<K>& key) const {
3615
        return find(key) == end() ? 0 : 1;
3616
    }
3617
3618
    // Issues CPU prefetch instructions for the memory needed to find or insert
3619
    // a key.  Like all lookup functions, this support heterogeneous keys.
3620
    //
3621
    // NOTE: This is a very low level operation and should not be used without
3622
    // specific benchmarks indicating its importance.
3623
    // --------------------------------------------------------------------
3624
    void prefetch_hash(size_t hashval) const {
3625
        const Inner& inner = sets_[subidx(hashval)];
3626
        const auto&  set   = inner.set_;
3627
        SharedLock m(const_cast<Inner&>(inner));
3628
        set.prefetch_hash(hashval);
3629
    }
3630
3631
    template <class K = key_type>
3632
    void prefetch(const key_arg<K>& key) const {
3633
        prefetch_hash(this->hash(key));
3634
    }
3635
3636
    // The API of find() has two extensions.
3637
    //
3638
    // 1. The hash can be passed by the user. It must be equal to the hash of the
3639
    // key.
3640
    //
3641
    // 2. The type of the key argument doesn't have to be key_type. This is so
3642
    // called heterogeneous key support.
3643
    // --------------------------------------------------------------------
3644
    template <class K = key_type>
3645
    iterator find(const key_arg<K>& key, size_t hashval) {
3646
        SharedLock m;
3647
        return find(key, hashval, m);
3648
    }
3649
3650
    template <class K = key_type>
3651
    iterator find(const key_arg<K>& key) {
3652
        return find(key, this->hash(key));
3653
    }
3654
3655
    template <class K = key_type>
3656
    const_iterator find(const key_arg<K>& key, size_t hashval) const {
3657
        return const_cast<parallel_hash_set*>(this)->find(key, hashval);
3658
    }
3659
3660
    template <class K = key_type>
3661
    const_iterator find(const key_arg<K>& key) const {
3662
        return find(key, this->hash(key));
3663
    }
3664
3665
    template <class K = key_type>
3666
    bool contains(const key_arg<K>& key) const {
3667
        return find(key) != end();
3668
    }
3669
3670
    template <class K = key_type>
3671
    bool contains(const key_arg<K>& key, size_t hashval) const {
3672
        return find(key, hashval) != end();
3673
    }
3674
3675
    template <class K = key_type>
3676
    std::pair<iterator, iterator> equal_range(const key_arg<K>& key) {
3677
        auto it = find(key);
3678
        if (it != end()) return {it, std::next(it)};
3679
        return {it, it};
3680
    }
3681
3682
    template <class K = key_type>
3683
    std::pair<const_iterator, const_iterator> equal_range(
3684
        const key_arg<K>& key) const {
3685
        auto it = find(key);
3686
        if (it != end()) return {it, std::next(it)};
3687
        return {it, it};
3688
    }
3689
3690
    size_t bucket_count() const {
3691
        size_t sz = 0;
3692
        for (const auto& inner : sets_)
3693
        {
3694
            SharedLock m(const_cast<Inner&>(inner));
3695
            sz += inner.set_.bucket_count();
3696
        }
3697
        return sz; 
3698
    }
3699
3700
    float load_factor() const {
3701
        size_t _capacity = bucket_count();
3702
        return _capacity ? static_cast<float>(static_cast<double>(size()) / _capacity) : 0;
3703
    }
3704
3705
    float max_load_factor() const { return 1.0f; }
3706
    void max_load_factor(float) {
3707
        // Does nothing.
3708
    }
3709
3710
    hasher hash_function() const { return hash_ref(); }  // warning: doesn't match internal hash - use hash() member function
3711
    key_equal key_eq() const { return eq_ref(); }
3712
    allocator_type get_allocator() const { return alloc_ref(); }
3713
3714
    friend bool operator==(const parallel_hash_set& a, const parallel_hash_set& b) {
3715
        return std::equal(a.sets_.begin(), a.sets_.end(), b.sets_.begin());
3716
    }
3717
3718
    friend bool operator!=(const parallel_hash_set& a, const parallel_hash_set& b) {
3719
        return !(a == b);
3720
    }
3721
3722
    template<class Mtx2_>
3723
    friend void swap(parallel_hash_set& a,
3724
                     parallel_hash_set<N, RefSet, Mtx2_, Policy, Hash, Eq, Alloc>& b)
3725
        noexcept(noexcept(a.swap(b)))
3726
    {
3727
        a.swap(b);
3728
    }
3729
3730
    template <class K>
3731
    size_t hash(const K& key) const {
3732
        return HashElement{hash_ref()}(key);
3733
    }
3734
3735
#if !defined(PHMAP_NON_DETERMINISTIC)
3736
    template<typename OutputArchive>
3737
    bool phmap_dump(OutputArchive& ar) const;
3738
3739
    template<typename InputArchive>
3740
    bool phmap_load(InputArchive& ar);
3741
#endif
3742
3743
private:
3744
    template <class Container, typename Enabler>
3745
    friend struct phmap::priv::hashtable_debug_internal::HashtableDebugAccess;
3746
3747
    struct FindElement 
3748
    {
3749
        template <class K, class... Args>
3750
        const_iterator operator()(const K& key, Args&&...) const {
3751
            return s.find(key);
3752
        }
3753
        const parallel_hash_set& s;
3754
    };
3755
3756
    struct HashElement 
3757
    {
3758
        template <class K, class... Args>
3759
        size_t operator()(const K& key, Args&&...) const {
3760
#if PHMAP_DISABLE_MIX
3761
            return h(key);
3762
#else
3763
            return phmap_mix<sizeof(size_t)>()(h(key));
3764
#endif
3765
        }
3766
        const hasher& h;
3767
    };
3768
3769
    template <class K1>
3770
    struct EqualElement 
3771
    {
3772
        template <class K2, class... Args>
3773
        bool operator()(const K2& lhs, Args&&...) const {
3774
            return eq(lhs, rhs);
3775
        }
3776
        const K1& rhs;
3777
        const key_equal& eq;
3778
    };
3779
3780
    // "erases" the object from the container, except that it doesn't actually
3781
    // destroy the object. It only updates all the metadata of the class.
3782
    // This can be used in conjunction with Policy::transfer to move the object to
3783
    // another place.
3784
    // --------------------------------------------------------------------
3785
    void erase_meta_only(const_iterator cit) {
3786
        auto &it = cit.iter_;
3787
        assert(it.set_ != nullptr);
3788
        it.set_.erase_meta_only(const_iterator(it.it_));
3789
    }
3790
3791
    void drop_deletes_without_resize() PHMAP_ATTRIBUTE_NOINLINE {
3792
        for (auto& inner : sets_)
3793
        {
3794
            UniqueLock m(inner);
3795
            inner.set_.drop_deletes_without_resize();
3796
        }
3797
    }
3798
3799
    bool has_element(const value_type& elem) const {
3800
        size_t hashval = PolicyTraits::apply(HashElement{hash_ref()}, elem);
3801
        Inner& inner   = sets_[subidx(hashval)];
3802
        auto&  set     = inner.set_;
3803
        SharedLock m(const_cast<Inner&>(inner));
3804
        return set.has_element(elem, hashval);
3805
    }
3806
3807
    // TODO(alkis): Optimize this assuming *this and that don't overlap.
3808
    // --------------------------------------------------------------------
3809
    template<class Mtx2_>
3810
    parallel_hash_set& move_assign(parallel_hash_set<N, RefSet, Mtx2_, Policy, Hash, Eq, Alloc>&& that, std::true_type) {
3811
        parallel_hash_set<N, RefSet, Mtx2_, Policy, Hash, Eq, Alloc> tmp(std::move(that));
3812
        swap(tmp);
3813
        return *this;
3814
    }
3815
3816
    template<class Mtx2_>
3817
    parallel_hash_set& move_assign(parallel_hash_set<N, RefSet, Mtx2_, Policy, Hash, Eq, Alloc>&& that, std::false_type) {
3818
        parallel_hash_set<N, RefSet, Mtx2_, Policy, Hash, Eq, Alloc> tmp(std::move(that), alloc_ref());
3819
        swap(tmp);
3820
        return *this;
3821
    }
3822
3823
protected:
3824
    template <class K = key_type, class L = SharedLock>
3825
    pointer find_ptr(const key_arg<K>& key, size_t hashval, L& mutexlock)
3826
    {
3827
        Inner& inner = sets_[subidx(hashval)];
3828
        auto& set = inner.set_;
3829
        mutexlock = std::move(L(inner));
3830
        return set.find_ptr(key, hashval);
3831
    }
3832
3833
    template <class K = key_type, class L = SharedLock>
3834
    iterator find(const key_arg<K>& key, size_t hashval, L& mutexlock) {
3835
        Inner& inner = sets_[subidx(hashval)];
3836
        auto& set = inner.set_;
3837
        mutexlock = std::move(L(inner));
3838
        return make_iterator(&inner, set.find(key, hashval));
3839
    }
3840
3841
    template <class K>
3842
    std::tuple<Inner*, size_t, bool> 
3843
    find_or_prepare_insert_with_hash(size_t hashval, const K& key, UniqueLock &mutexlock) {
3844
        Inner& inner = sets_[subidx(hashval)];
3845
        auto&  set   = inner.set_;
3846
        mutexlock    = std::move(UniqueLock(inner));
3847
        size_t offset = set._find_key(key, hashval);
3848
        if (offset == (size_t)-1) {
3849
            offset = set.prepare_insert(hashval);
3850
            return std::make_tuple(&inner, offset, true);
3851
        }
3852
        return std::make_tuple(&inner, offset, false);
3853
    }
3854
3855
    template <class K>
3856
    std::tuple<Inner*, size_t, bool> 
3857
    find_or_prepare_insert(const K& key, UniqueLock &mutexlock) {
3858
        return find_or_prepare_insert_with_hash<K>(this->hash(key), key, mutexlock);
3859
    }
3860
3861
    iterator iterator_at(Inner *inner, 
3862
                         const EmbeddedIterator& it) { 
3863
        return {inner, &sets_[0] + num_tables, it}; 
3864
    }
3865
    const_iterator iterator_at(Inner *inner, 
3866
                               const EmbeddedIterator& it) const { 
3867
        return {inner, &sets_[0] + num_tables, it}; 
3868
    }
3869
3870
    static size_t subidx(size_t hashval) {
3871
        return ((hashval >> 8) ^ (hashval >> 16) ^ (hashval >> 24)) & mask;
3872
    }
3873
3874
    static size_t subcnt() {
3875
        return num_tables;
3876
    }
3877
3878
private:
3879
    friend struct RawHashSetTestOnlyAccess;
3880
3881
    size_t growth_left() { 
3882
        size_t sz = 0;
3883
        for (const auto& set : sets_)
3884
            sz += set.growth_left();
3885
        return sz; 
3886
    }
3887
3888
    hasher&       hash_ref()        { return sets_[0].set_.hash_ref(); }
3889
    const hasher& hash_ref() const  { return sets_[0].set_.hash_ref(); }
3890
    key_equal&       eq_ref()       { return sets_[0].set_.eq_ref(); }
3891
    const key_equal& eq_ref() const { return sets_[0].set_.eq_ref(); }
3892
    allocator_type&  alloc_ref()    { return sets_[0].set_.alloc_ref(); }
3893
    const allocator_type& alloc_ref() const { 
3894
        return sets_[0].set_.alloc_ref();
3895
    }
3896
3897
protected:       // protected in case users want to derive fromm this
3898
    std::array<Inner, num_tables> sets_;
3899
};
3900
3901
// --------------------------------------------------------------------------
3902
// --------------------------------------------------------------------------
3903
template <size_t N,
3904
          template <class, class, class, class> class RefSet,
3905
          class Mtx_,
3906
          class Policy, class Hash, class Eq, class Alloc>
3907
class parallel_hash_map : public parallel_hash_set<N, RefSet, Mtx_, Policy, Hash, Eq, Alloc> 
3908
{
3909
    // P is Policy. It's passed as a template argument to support maps that have
3910
    // incomplete types as values, as in unordered_map<K, IncompleteType>.
3911
    // MappedReference<> may be a non-reference type.
3912
    template <class P>
3913
    using MappedReference = decltype(P::value(
3914
            std::addressof(std::declval<typename parallel_hash_map::reference>())));
3915
3916
    // MappedConstReference<> may be a non-reference type.
3917
    template <class P>
3918
    using MappedConstReference = decltype(P::value(
3919
            std::addressof(std::declval<typename parallel_hash_map::const_reference>())));
3920
3921
    using KeyArgImpl =
3922
        KeyArg<IsTransparent<Eq>::value && IsTransparent<Hash>::value>;
3923
3924
    using Base = typename parallel_hash_map::parallel_hash_set;
3925
    using Lockable      = phmap::LockableImpl<Mtx_>;
3926
    using UniqueLock    = typename Lockable::UniqueLock;
3927
    using SharedLock    = typename Lockable::SharedLock;
3928
    using ReadWriteLock = typename Lockable::ReadWriteLock;
3929
3930
public:
3931
    using key_type    = typename Policy::key_type;
3932
    using mapped_type = typename Policy::mapped_type;
3933
    using value_type  = typename Base::value_type;
3934
    template <class K>
3935
    using key_arg = typename KeyArgImpl::template type<K, key_type>;
3936
3937
    static_assert(!std::is_reference<key_type>::value, "");
3938
    // TODO(alkis): remove this assertion and verify that reference mapped_type is
3939
    // supported.
3940
    static_assert(!std::is_reference<mapped_type>::value, "");
3941
3942
    using iterator = typename parallel_hash_map::parallel_hash_set::iterator;
3943
    using const_iterator = typename parallel_hash_map::parallel_hash_set::const_iterator;
3944
3945
    parallel_hash_map() {}
3946
3947
#ifdef __INTEL_COMPILER
3948
    using Base::parallel_hash_set;
3949
#else
3950
    using parallel_hash_map::parallel_hash_set::parallel_hash_set;
3951
#endif
3952
3953
    // The last two template parameters ensure that both arguments are rvalues
3954
    // (lvalue arguments are handled by the overloads below). This is necessary
3955
    // for supporting bitfield arguments.
3956
    //
3957
    //   union { int n : 1; };
3958
    //   flat_hash_map<int, int> m;
3959
    //   m.insert_or_assign(n, n);
3960
    template <class K = key_type, class V = mapped_type, K* = nullptr,
3961
              V* = nullptr>
3962
    std::pair<iterator, bool> insert_or_assign(key_arg<K>&& k, V&& v) {
3963
        return insert_or_assign_impl(std::forward<K>(k), std::forward<V>(v));
3964
    }
3965
3966
    template <class K = key_type, class V = mapped_type, K* = nullptr>
3967
    std::pair<iterator, bool> insert_or_assign(key_arg<K>&& k, const V& v) {
3968
        return insert_or_assign_impl(std::forward<K>(k), v);
3969
    }
3970
3971
    template <class K = key_type, class V = mapped_type, V* = nullptr>
3972
    std::pair<iterator, bool> insert_or_assign(const key_arg<K>& k, V&& v) {
3973
        return insert_or_assign_impl(k, std::forward<V>(v));
3974
    }
3975
3976
    template <class K = key_type, class V = mapped_type>
3977
    std::pair<iterator, bool> insert_or_assign(const key_arg<K>& k, const V& v) {
3978
        return insert_or_assign_impl(k, v);
3979
    }
3980
3981
    template <class K = key_type, class V = mapped_type, K* = nullptr,
3982
              V* = nullptr>
3983
    iterator insert_or_assign(const_iterator, key_arg<K>&& k, V&& v) {
3984
        return insert_or_assign(std::forward<K>(k), std::forward<V>(v)).first;
3985
    }
3986
3987
    template <class K = key_type, class V = mapped_type, K* = nullptr>
3988
    iterator insert_or_assign(const_iterator, key_arg<K>&& k, const V& v) {
3989
        return insert_or_assign(std::forward<K>(k), v).first;
3990
    }
3991
3992
    template <class K = key_type, class V = mapped_type, V* = nullptr>
3993
    iterator insert_or_assign(const_iterator, const key_arg<K>& k, V&& v) {
3994
        return insert_or_assign(k, std::forward<V>(v)).first;
3995
    }
3996
3997
    template <class K = key_type, class V = mapped_type>
3998
    iterator insert_or_assign(const_iterator, const key_arg<K>& k, const V& v) {
3999
        return insert_or_assign(k, v).first;
4000
    }
4001
4002
    template <class K = key_type, class... Args,
4003
              typename std::enable_if<
4004
                  !std::is_convertible<K, const_iterator>::value, int>::type = 0,
4005
              K* = nullptr>
4006
    std::pair<iterator, bool> try_emplace(key_arg<K>&& k, Args&&... args) {
4007
        return try_emplace_impl(std::forward<K>(k), std::forward<Args>(args)...);
4008
    }
4009
4010
    template <class K = key_type, class... Args,
4011
              typename std::enable_if<
4012
                  !std::is_convertible<K, const_iterator>::value, int>::type = 0>
4013
    std::pair<iterator, bool> try_emplace(const key_arg<K>& k, Args&&... args) {
4014
        return try_emplace_impl(k, std::forward<Args>(args)...);
4015
    }
4016
4017
    template <class K = key_type, class... Args, K* = nullptr>
4018
    iterator try_emplace(const_iterator, key_arg<K>&& k, Args&&... args) {
4019
        return try_emplace(std::forward<K>(k), std::forward<Args>(args)...).first;
4020
    }
4021
4022
    template <class K = key_type, class... Args>
4023
    iterator try_emplace(const_iterator, const key_arg<K>& k, Args&&... args) {
4024
        return try_emplace(k, std::forward<Args>(args)...).first;
4025
    }
4026
4027
    template <class K = key_type, class P = Policy>
4028
    MappedReference<P> at(const key_arg<K>& key) {
4029
        auto it = this->find(key);
4030
        if (it == this->end()) 
4031
            phmap::base_internal::ThrowStdOutOfRange("phmap at(): lookup non-existent key");
4032
        return Policy::value(&*it);
4033
    }
4034
4035
    template <class K = key_type, class P = Policy>
4036
    MappedConstReference<P> at(const key_arg<K>& key) const {
4037
        auto it = this->find(key);
4038
        if (it == this->end()) 
4039
            phmap::base_internal::ThrowStdOutOfRange("phmap at(): lookup non-existent key");
4040
        return Policy::value(&*it);
4041
    }
4042
4043
    // ----------- phmap extensions --------------------------
4044
4045
    template <class K = key_type, class... Args,
4046
              typename std::enable_if<
4047
                  !std::is_convertible<K, const_iterator>::value, int>::type = 0,
4048
              K* = nullptr>
4049
    std::pair<iterator, bool> try_emplace_with_hash(size_t hashval, key_arg<K>&& k, Args&&... args) {
4050
        return try_emplace_impl_with_hash(hashval, std::forward<K>(k), std::forward<Args>(args)...);
4051
    }
4052
4053
    template <class K = key_type, class... Args,
4054
              typename std::enable_if<
4055
                  !std::is_convertible<K, const_iterator>::value, int>::type = 0>
4056
    std::pair<iterator, bool> try_emplace_with_hash(size_t hashval, const key_arg<K>& k, Args&&... args) {
4057
        return try_emplace_impl_with_hash(hashval, k, std::forward<Args>(args)...);
4058
    }
4059
4060
    template <class K = key_type, class... Args, K* = nullptr>
4061
    iterator try_emplace_with_hash(size_t hashval, const_iterator, key_arg<K>&& k, Args&&... args) {
4062
        return try_emplace_with_hash(hashval, std::forward<K>(k), std::forward<Args>(args)...).first;
4063
    }
4064
4065
    template <class K = key_type, class... Args>
4066
    iterator try_emplace_with_hash(size_t hashval, const_iterator, const key_arg<K>& k, Args&&... args) {
4067
        return try_emplace_with_hash(hashval, k, std::forward<Args>(args)...).first;
4068
    }
4069
4070
    // if map does not contains key, it is inserted and the mapped value is value-constructed 
4071
    // with the provided arguments (if any), as with try_emplace. 
4072
    // if map already  contains key, then the lambda is called with the mapped value (under 
4073
    // write lock protection) and can update the mapped value.
4074
    // returns true if key was not already present, false otherwise.
4075
    // ---------------------------------------------------------------------------------------
4076
    template <class K = key_type, class F, class... Args>
4077
    bool try_emplace_l(K&& k, F&& f, Args&&... args) {
4078
        size_t hashval = this->hash(k);
4079
        UniqueLock m;
4080
        auto res = this->find_or_prepare_insert_with_hash(hashval, k, m);
4081
        typename Base::Inner *inner = std::get<0>(res);
4082
        if (std::get<2>(res)) {
4083
            inner->set_.emplace_at(std::get<1>(res), std::piecewise_construct,
4084
                                   std::forward_as_tuple(std::forward<K>(k)),
4085
                                   std::forward_as_tuple(std::forward<Args>(args)...));
4086
            inner->set_.set_ctrl(std::get<1>(res), H2(hashval));
4087
        } else {
4088
            auto it = this->iterator_at(inner, inner->set_.iterator_at(std::get<1>(res)));
4089
            // call lambda. in case of the set, non "key" part of value_type can be changed
4090
            std::forward<F>(f)(const_cast<value_type &>(*it));
4091
        }
4092
        return std::get<2>(res);
4093
    }
4094
4095
    // returns {pointer, bool} instead of {iterator, bool} per try_emplace.
4096
    // useful for node-based containers, since the pointer is not invalidated by concurrent insert etc.
4097
    template <class K = key_type, class... Args>
4098
    std::pair<typename parallel_hash_map::parallel_hash_set::pointer, bool> try_emplace_p(K&& k, Args&&... args) {
4099
        size_t hashval = this->hash(k);
4100
        UniqueLock m;
4101
        auto res = this->find_or_prepare_insert_with_hash(hashval, k, m);
4102
        typename Base::Inner *inner = std::get<0>(res);
4103
        if (std::get<2>(res)) {
4104
            inner->set_.emplace_at(std::get<1>(res), std::piecewise_construct,
4105
                                   std::forward_as_tuple(std::forward<K>(k)),
4106
                                   std::forward_as_tuple(std::forward<Args>(args)...));
4107
            inner->set_.set_ctrl(std::get<1>(res), H2(hashval));
4108
        }
4109
        auto it = this->iterator_at(inner, inner->set_.iterator_at(std::get<1>(res)));
4110
        return {&*it, std::get<2>(res)};
4111
    }
4112
4113
    // ----------- end of phmap extensions --------------------------
4114
4115
    template <class K = key_type, class P = Policy, K* = nullptr>
4116
    MappedReference<P> operator[](key_arg<K>&& key) {
4117
        return Policy::value(&*try_emplace(std::forward<K>(key)).first);
4118
    }
4119
4120
    template <class K = key_type, class P = Policy>
4121
    MappedReference<P> operator[](const key_arg<K>& key) {
4122
        return Policy::value(&*try_emplace(key).first);
4123
    }
4124
4125
private:
4126
4127
    template <class K, class V>
4128
    std::pair<iterator, bool> insert_or_assign_impl(K&& k, V&& v) {
4129
        size_t hashval = this->hash(k);
4130
        UniqueLock m;
4131
        auto res = this->find_or_prepare_insert_with_hash(hashval, k, m);
4132
        typename Base::Inner *inner = std::get<0>(res);
4133
        if (std::get<2>(res)) {
4134
            inner->set_.emplace_at(std::get<1>(res), std::forward<K>(k), std::forward<V>(v));
4135
            inner->set_.set_ctrl(std::get<1>(res), H2(hashval));
4136
        } else
4137
            Policy::value(&*inner->set_.iterator_at(std::get<1>(res))) = std::forward<V>(v);
4138
        return {this->iterator_at(inner, inner->set_.iterator_at(std::get<1>(res))), 
4139
                std::get<2>(res)};
4140
    }
4141
4142
    template <class K = key_type, class... Args>
4143
    std::pair<iterator, bool> try_emplace_impl(K&& k, Args&&... args) {
4144
        return try_emplace_impl_with_hash(this->hash(k), std::forward<K>(k),
4145
                                          std::forward<Args>(args)...);
4146
    }
4147
4148
    template <class K = key_type, class... Args>
4149
    std::pair<iterator, bool> try_emplace_impl_with_hash(size_t hashval, K&& k, Args&&... args) {
4150
        UniqueLock m;
4151
        auto res = this->find_or_prepare_insert_with_hash(hashval, k, m);
4152
        typename Base::Inner *inner = std::get<0>(res);
4153
        if (std::get<2>(res)) {
4154
            inner->set_.emplace_at(std::get<1>(res), std::piecewise_construct,
4155
                                   std::forward_as_tuple(std::forward<K>(k)),
4156
                                   std::forward_as_tuple(std::forward<Args>(args)...));
4157
            inner->set_.set_ctrl(std::get<1>(res), H2(hashval));
4158
        }
4159
        return {this->iterator_at(inner, inner->set_.iterator_at(std::get<1>(res))), 
4160
                std::get<2>(res)};
4161
    }
4162
4163
    
4164
};
4165
4166
4167
// Constructs T into uninitialized storage pointed by `ptr` using the args
4168
// specified in the tuple.
4169
// ----------------------------------------------------------------------------
4170
template <class Alloc, class T, class Tuple>
4171
void ConstructFromTuple(Alloc* alloc, T* ptr, Tuple&& t) {
4172
    memory_internal::ConstructFromTupleImpl(
4173
        alloc, ptr, std::forward<Tuple>(t),
4174
        phmap::make_index_sequence<
4175
        std::tuple_size<typename std::decay<Tuple>::type>::value>());
4176
}
4177
4178
// Constructs T using the args specified in the tuple and calls F with the
4179
// constructed value.
4180
// ----------------------------------------------------------------------------
4181
template <class T, class Tuple, class F>
4182
decltype(std::declval<F>()(std::declval<T>())) WithConstructed(
4183
    Tuple&& t, F&& f) {
4184
    return memory_internal::WithConstructedImpl<T>(
4185
        std::forward<Tuple>(t),
4186
        phmap::make_index_sequence<
4187
        std::tuple_size<typename std::decay<Tuple>::type>::value>(),
4188
        std::forward<F>(f));
4189
}
4190
4191
// ----------------------------------------------------------------------------
4192
// Given arguments of an std::pair's consructor, PairArgs() returns a pair of
4193
// tuples with references to the passed arguments. The tuples contain
4194
// constructor arguments for the first and the second elements of the pair.
4195
//
4196
// The following two snippets are equivalent.
4197
//
4198
// 1. std::pair<F, S> p(args...);
4199
//
4200
// 2. auto a = PairArgs(args...);
4201
//    std::pair<F, S> p(std::piecewise_construct,
4202
//                      std::move(p.first), std::move(p.second));
4203
// ----------------------------------------------------------------------------
4204
0
inline std::pair<std::tuple<>, std::tuple<>> PairArgs() { return {}; }
4205
4206
template <class F, class S>
4207
25.8M
std::pair<std::tuple<F&&>, std::tuple<S&&>> PairArgs(F&& f, S&& s) {
4208
25.8M
  return {std::piecewise_construct, std::forward_as_tuple(std::forward<F>(f)),
4209
25.8M
          std::forward_as_tuple(std::forward<S>(s))};
4210
25.8M
}
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
4207
14.5M
std::pair<std::tuple<F&&>, std::tuple<S&&>> PairArgs(F&& f, S&& s) {
4208
14.5M
  return {std::piecewise_construct, std::forward_as_tuple(std::forward<F>(f)),
4209
14.5M
          std::forward_as_tuple(std::forward<S>(s))};
4210
14.5M
}
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
4207
11.2M
std::pair<std::tuple<F&&>, std::tuple<S&&>> PairArgs(F&& f, S&& s) {
4208
11.2M
  return {std::piecewise_construct, std::forward_as_tuple(std::forward<F>(f)),
4209
11.2M
          std::forward_as_tuple(std::forward<S>(s))};
4210
11.2M
}
4211
4212
template <class F, class S>
4213
std::pair<std::tuple<const F&>, std::tuple<const S&>> PairArgs(
4214
14.5M
    const std::pair<F, S>& p) {
4215
14.5M
    return PairArgs(p.first, p.second);
4216
14.5M
}
4217
4218
template <class F, class S>
4219
11.2M
std::pair<std::tuple<F&&>, std::tuple<S&&>> PairArgs(std::pair<F, S>&& p) {
4220
11.2M
    return PairArgs(std::forward<F>(p.first), std::forward<S>(p.second));
4221
11.2M
}
4222
4223
template <class F, class S>
4224
auto PairArgs(std::piecewise_construct_t, F&& f, S&& s)
4225
    -> decltype(std::make_pair(memory_internal::TupleRef(std::forward<F>(f)),
4226
                               memory_internal::TupleRef(std::forward<S>(s)))) {
4227
    return std::make_pair(memory_internal::TupleRef(std::forward<F>(f)),
4228
                          memory_internal::TupleRef(std::forward<S>(s)));
4229
}
4230
4231
// A helper function for implementing apply() in map policies.
4232
// ----------------------------------------------------------------------------
4233
template <class F, class... Args>
4234
auto DecomposePair(F&& f, Args&&... args)
4235
    -> decltype(memory_internal::DecomposePairImpl(
4236
25.8M
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...))) {
4237
25.8M
    return memory_internal::DecomposePairImpl(
4238
25.8M
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...));
4239
25.8M
}
_ZN5phmap4priv13DecomposePairINS0_12raw_hash_setINS0_17FlatHashMapPolicyIjiEENS_4HashIjEENS_7EqualToIjEENSt3__19allocatorINS9_4pairIKjiEEEEE19EmplaceDecomposableEJSD_EEEDTclsr15memory_internalE17DecomposePairImplclsr3stdE7forwardIT_Efp_Ecl8PairArgsspclsr3stdE7forwardIT0_Efp0_EEEEOSH_DpOSI_
Line
Count
Source
4236
11.2M
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...))) {
4237
11.2M
    return memory_internal::DecomposePairImpl(
4238
11.2M
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...));
4239
11.2M
}
_ZN5phmap4priv13DecomposePairINS0_12raw_hash_setINS0_17FlatHashMapPolicyIjiEENS_4HashIjEENS_7EqualToIjEENSt3__19allocatorINS9_4pairIKjiEEEEE12EqualElementIjEEJRSD_EEEDTclsr15memory_internalE17DecomposePairImplclsr3stdE7forwardIT_Efp_Ecl8PairArgsspclsr3stdE7forwardIT0_Efp0_EEEEOSJ_DpOSK_
Line
Count
Source
4236
12.5M
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...))) {
4237
12.5M
    return memory_internal::DecomposePairImpl(
4238
12.5M
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...));
4239
12.5M
}
_ZN5phmap4priv13DecomposePairINS0_12raw_hash_setINS0_17FlatHashMapPolicyIjiEENS_4HashIjEENS_7EqualToIjEENSt3__19allocatorINS9_4pairIKjiEEEEE11HashElementEJRSD_EEEDTclsr15memory_internalE17DecomposePairImplclsr3stdE7forwardIT_Efp_Ecl8PairArgsspclsr3stdE7forwardIT0_Efp0_EEEEOSI_DpOSJ_
Line
Count
Source
4236
1.30M
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...))) {
4237
1.30M
    return memory_internal::DecomposePairImpl(
4238
1.30M
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...));
4239
1.30M
}
_ZN5phmap4priv13DecomposePairINS0_12raw_hash_setINS0_17FlatHashMapPolicyIjiEENS_4HashIjEENS_7EqualToIjEENSt3__19allocatorINS9_4pairIKjiEEEEE11HashElementEJRKSD_EEEDTclsr15memory_internalE17DecomposePairImplclsr3stdE7forwardIT_Efp_Ecl8PairArgsspclsr3stdE7forwardIT0_Efp0_EEEEOSJ_DpOSK_
Line
Count
Source
4236
722k
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...))) {
4237
722k
    return memory_internal::DecomposePairImpl(
4238
722k
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...));
4239
722k
}
4240
4241
// A helper function for implementing apply() in set policies.
4242
// ----------------------------------------------------------------------------
4243
template <class F, class Arg>
4244
decltype(std::declval<F>()(std::declval<const Arg&>(), std::declval<Arg>()))
4245
DecomposeValue(F&& f, Arg&& arg) {
4246
    const auto& key = arg;
4247
    return std::forward<F>(f)(key, std::forward<Arg>(arg));
4248
}
4249
4250
4251
// --------------------------------------------------------------------------
4252
// Policy: a policy defines how to perform different operations on
4253
// the slots of the hashtable (see hash_policy_traits.h for the full interface
4254
// of policy).
4255
//
4256
// Hash: a (possibly polymorphic) functor that hashes keys of the hashtable. The
4257
// functor should accept a key and return size_t as hash. For best performance
4258
// it is important that the hash function provides high entropy across all bits
4259
// of the hash.
4260
//
4261
// Eq: a (possibly polymorphic) functor that compares two keys for equality. It
4262
// should accept two (of possibly different type) keys and return a bool: true
4263
// if they are equal, false if they are not. If two keys compare equal, then
4264
// their hash values as defined by Hash MUST be equal.
4265
//
4266
// Allocator: an Allocator [https://devdocs.io/cpp/concept/allocator] with which
4267
// the storage of the hashtable will be allocated and the elements will be
4268
// constructed and destroyed.
4269
// --------------------------------------------------------------------------
4270
template <class T>
4271
struct FlatHashSetPolicy 
4272
{
4273
    using slot_type = T;
4274
    using key_type = T;
4275
    using init_type = T;
4276
    using constant_iterators = std::true_type;
4277
    using is_flat = std::true_type;
4278
4279
    template <class Allocator, class... Args>
4280
    static void construct(Allocator* alloc, slot_type* slot, Args&&... args) {
4281
        phmap::allocator_traits<Allocator>::construct(*alloc, slot,
4282
                                                      std::forward<Args>(args)...);
4283
    }
4284
4285
    template <class Allocator>
4286
    static void destroy(Allocator* alloc, slot_type* slot) {
4287
        phmap::allocator_traits<Allocator>::destroy(*alloc, slot);
4288
    }
4289
4290
    template <class Allocator>
4291
    static void transfer(Allocator* alloc, slot_type* new_slot,
4292
                         slot_type* old_slot) {
4293
        construct(alloc, new_slot, std::move(*old_slot));
4294
        destroy(alloc, old_slot);
4295
    }
4296
4297
    static T& element(slot_type* slot) { return *slot; }
4298
4299
    template <class F, class... Args>
4300
    static decltype(phmap::priv::DecomposeValue(
4301
                        std::declval<F>(), std::declval<Args>()...))
4302
    apply(F&& f, Args&&... args) {
4303
        return phmap::priv::DecomposeValue(
4304
            std::forward<F>(f), std::forward<Args>(args)...);
4305
    }
4306
4307
    static size_t space_used(const T*) { return 0; }
4308
};
4309
4310
// --------------------------------------------------------------------------
4311
// --------------------------------------------------------------------------
4312
template <class K, class V>
4313
struct FlatHashMapPolicy 
4314
{
4315
    using slot_policy = priv::map_slot_policy<K, V>;
4316
    using slot_type = typename slot_policy::slot_type;
4317
    using key_type = K;
4318
    using mapped_type = V;
4319
    using init_type = std::pair</*non const*/ key_type, mapped_type>;
4320
    using is_flat = std::true_type;
4321
4322
    template <class Allocator, class... Args>
4323
738k
    static void construct(Allocator* alloc, slot_type* slot, Args&&... args) {
4324
738k
        slot_policy::construct(alloc, slot, std::forward<Args>(args)...);
4325
738k
    }
4326
4327
    template <class Allocator>
4328
0
    static void destroy(Allocator* alloc, slot_type* slot) {
4329
0
        slot_policy::destroy(alloc, slot);
4330
0
    }
4331
4332
    template <class Allocator>
4333
    static void transfer(Allocator* alloc, slot_type* new_slot,
4334
1.30M
                         slot_type* old_slot) {
4335
1.30M
        slot_policy::transfer(alloc, new_slot, old_slot);
4336
1.30M
    }
4337
4338
    template <class F, class... Args>
4339
    static decltype(phmap::priv::DecomposePair(
4340
                        std::declval<F>(), std::declval<Args>()...))
4341
25.8M
    apply(F&& f, Args&&... args) {
4342
25.8M
        return phmap::priv::DecomposePair(std::forward<F>(f),
4343
25.8M
                                                        std::forward<Args>(args)...);
4344
25.8M
    }
_ZN5phmap4priv17FlatHashMapPolicyIjiE5applyINS0_12raw_hash_setIS2_NS_4HashIjEENS_7EqualToIjEENSt3__19allocatorINS9_4pairIKjiEEEEE19EmplaceDecomposableEJSD_EEEDTclsr5phmap4privE13DecomposePairclsr3stdE7declvalIT_EEspclsr3stdE7declvalIT0_EEEEOSH_DpOSI_
Line
Count
Source
4341
11.2M
    apply(F&& f, Args&&... args) {
4342
11.2M
        return phmap::priv::DecomposePair(std::forward<F>(f),
4343
11.2M
                                                        std::forward<Args>(args)...);
4344
11.2M
    }
_ZN5phmap4priv17FlatHashMapPolicyIjiE5applyINS0_12raw_hash_setIS2_NS_4HashIjEENS_7EqualToIjEENSt3__19allocatorINS9_4pairIKjiEEEEE12EqualElementIjEEJRSD_EEEDTclsr5phmap4privE13DecomposePairclsr3stdE7declvalIT_EEspclsr3stdE7declvalIT0_EEEEOSJ_DpOSK_
Line
Count
Source
4341
12.5M
    apply(F&& f, Args&&... args) {
4342
12.5M
        return phmap::priv::DecomposePair(std::forward<F>(f),
4343
12.5M
                                                        std::forward<Args>(args)...);
4344
12.5M
    }
_ZN5phmap4priv17FlatHashMapPolicyIjiE5applyINS0_12raw_hash_setIS2_NS_4HashIjEENS_7EqualToIjEENSt3__19allocatorINS9_4pairIKjiEEEEE11HashElementEJRSD_EEEDTclsr5phmap4privE13DecomposePairclsr3stdE7declvalIT_EEspclsr3stdE7declvalIT0_EEEEOSI_DpOSJ_
Line
Count
Source
4341
1.30M
    apply(F&& f, Args&&... args) {
4342
1.30M
        return phmap::priv::DecomposePair(std::forward<F>(f),
4343
1.30M
                                                        std::forward<Args>(args)...);
4344
1.30M
    }
_ZN5phmap4priv17FlatHashMapPolicyIjiE5applyINS0_12raw_hash_setIS2_NS_4HashIjEENS_7EqualToIjEENSt3__19allocatorINS9_4pairIKjiEEEEE11HashElementEJRKSD_EEEDTclsr5phmap4privE13DecomposePairclsr3stdE7declvalIT_EEspclsr3stdE7declvalIT0_EEEEOSJ_DpOSK_
Line
Count
Source
4341
722k
    apply(F&& f, Args&&... args) {
4342
722k
        return phmap::priv::DecomposePair(std::forward<F>(f),
4343
722k
                                                        std::forward<Args>(args)...);
4344
722k
    }
4345
4346
    static size_t space_used(const slot_type*) { return 0; }
4347
4348
15.3M
    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
4348
15.3M
    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> > >*)
4349
4350
    static V& value(std::pair<const K, V>* kv) { return kv->second; }
4351
    static const V& value(const std::pair<const K, V>* kv) { return kv->second; }
4352
};
4353
4354
template <class Reference, class Policy>
4355
struct node_hash_policy {
4356
    static_assert(std::is_lvalue_reference<Reference>::value, "");
4357
4358
    using slot_type = typename std::remove_cv<
4359
        typename std::remove_reference<Reference>::type>::type*;
4360
4361
    template <class Alloc, class... Args>
4362
    static void construct(Alloc* alloc, slot_type* slot, Args&&... args) {
4363
        *slot = Policy::new_element(alloc, std::forward<Args>(args)...);
4364
    }
4365
4366
    template <class Alloc>
4367
    static void destroy(Alloc* alloc, slot_type* slot) {
4368
        Policy::delete_element(alloc, *slot);
4369
    }
4370
4371
    template <class Alloc>
4372
    static void transfer(Alloc*, slot_type* new_slot, slot_type* old_slot) {
4373
        *new_slot = *old_slot;
4374
    }
4375
4376
    static size_t space_used(const slot_type* slot) {
4377
        if (slot == nullptr) return Policy::element_space_used(nullptr);
4378
        return Policy::element_space_used(*slot);
4379
    }
4380
4381
    static Reference element(slot_type* slot) { return **slot; }
4382
4383
    template <class T, class P = Policy>
4384
    static auto value(T* elem) -> decltype(P::value(elem)) {
4385
        return P::value(elem);
4386
    }
4387
4388
    template <class... Ts, class P = Policy>
4389
    static auto apply(Ts&&... ts) -> decltype(P::apply(std::forward<Ts>(ts)...)) {
4390
        return P::apply(std::forward<Ts>(ts)...);
4391
    }
4392
};
4393
4394
// --------------------------------------------------------------------------
4395
// --------------------------------------------------------------------------
4396
template <class T>
4397
struct NodeHashSetPolicy
4398
    : phmap::priv::node_hash_policy<T&, NodeHashSetPolicy<T>> 
4399
{
4400
    using key_type = T;
4401
    using init_type = T;
4402
    using constant_iterators = std::true_type;
4403
    using is_flat = std::false_type;
4404
4405
    template <class Allocator, class... Args>
4406
        static T* new_element(Allocator* alloc, Args&&... args) {
4407
        using ValueAlloc =
4408
            typename phmap::allocator_traits<Allocator>::template rebind_alloc<T>;
4409
        ValueAlloc value_alloc(*alloc);
4410
        T* res = phmap::allocator_traits<ValueAlloc>::allocate(value_alloc, 1);
4411
        phmap::allocator_traits<ValueAlloc>::construct(value_alloc, res,
4412
                                                       std::forward<Args>(args)...);
4413
        return res;
4414
    }
4415
4416
    template <class Allocator>
4417
        static void delete_element(Allocator* alloc, T* elem) {
4418
        using ValueAlloc =
4419
            typename phmap::allocator_traits<Allocator>::template rebind_alloc<T>;
4420
        ValueAlloc value_alloc(*alloc);
4421
        phmap::allocator_traits<ValueAlloc>::destroy(value_alloc, elem);
4422
        phmap::allocator_traits<ValueAlloc>::deallocate(value_alloc, elem, 1);
4423
    }
4424
4425
    template <class F, class... Args>
4426
        static decltype(phmap::priv::DecomposeValue(
4427
                            std::declval<F>(), std::declval<Args>()...))
4428
        apply(F&& f, Args&&... args) {
4429
        return phmap::priv::DecomposeValue(
4430
            std::forward<F>(f), std::forward<Args>(args)...);
4431
    }
4432
4433
    static size_t element_space_used(const T*) { return sizeof(T); }
4434
};
4435
4436
// --------------------------------------------------------------------------
4437
// --------------------------------------------------------------------------
4438
template <class Key, class Value>
4439
class NodeHashMapPolicy
4440
    : public phmap::priv::node_hash_policy<
4441
          std::pair<const Key, Value>&, NodeHashMapPolicy<Key, Value>> 
4442
{
4443
    using value_type = std::pair<const Key, Value>;
4444
4445
public:
4446
    using key_type = Key;
4447
    using mapped_type = Value;
4448
    using init_type = std::pair</*non const*/ key_type, mapped_type>;
4449
    using is_flat = std::false_type;
4450
4451
    template <class Allocator, class... Args>
4452
        static value_type* new_element(Allocator* alloc, Args&&... args) {
4453
        using PairAlloc = typename phmap::allocator_traits<
4454
            Allocator>::template rebind_alloc<value_type>;
4455
        PairAlloc pair_alloc(*alloc);
4456
        value_type* res =
4457
            phmap::allocator_traits<PairAlloc>::allocate(pair_alloc, 1);
4458
        phmap::allocator_traits<PairAlloc>::construct(pair_alloc, res,
4459
                                                      std::forward<Args>(args)...);
4460
        return res;
4461
    }
4462
4463
    template <class Allocator>
4464
        static void delete_element(Allocator* alloc, value_type* pair) {
4465
        using PairAlloc = typename phmap::allocator_traits<
4466
            Allocator>::template rebind_alloc<value_type>;
4467
        PairAlloc pair_alloc(*alloc);
4468
        phmap::allocator_traits<PairAlloc>::destroy(pair_alloc, pair);
4469
        phmap::allocator_traits<PairAlloc>::deallocate(pair_alloc, pair, 1);
4470
    }
4471
4472
    template <class F, class... Args>
4473
        static decltype(phmap::priv::DecomposePair(
4474
                            std::declval<F>(), std::declval<Args>()...))
4475
        apply(F&& f, Args&&... args) {
4476
        return phmap::priv::DecomposePair(std::forward<F>(f),
4477
                                                        std::forward<Args>(args)...);
4478
    }
4479
4480
    static size_t element_space_used(const value_type*) {
4481
        return sizeof(value_type);
4482
    }
4483
4484
    static Value& value(value_type* elem) { return elem->second; }
4485
    static const Value& value(const value_type* elem) { return elem->second; }
4486
};
4487
4488
4489
// --------------------------------------------------------------------------
4490
//  hash_default
4491
// --------------------------------------------------------------------------
4492
4493
#if PHMAP_HAVE_STD_STRING_VIEW
4494
4495
// Supports heterogeneous lookup for basic_string<T>-like elements.
4496
template<class CharT> 
4497
struct StringHashEqT
4498
{
4499
    struct Hash 
4500
    {
4501
        using is_transparent = void;
4502
        
4503
        size_t operator()(std::basic_string_view<CharT> v) const {
4504
            std::string_view bv{
4505
                reinterpret_cast<const char*>(v.data()), v.size() * sizeof(CharT)};
4506
            return std::hash<std::string_view>()(bv);
4507
        }
4508
    };
4509
4510
    struct Eq {
4511
        using is_transparent = void;
4512
4513
        bool operator()(std::basic_string_view<CharT> lhs,
4514
                        std::basic_string_view<CharT> rhs) const {
4515
            return lhs == rhs;
4516
        }
4517
    };
4518
};
4519
4520
template <>
4521
struct HashEq<std::string> : StringHashEqT<char> {};
4522
4523
template <>
4524
struct HashEq<std::string_view> : StringHashEqT<char> {};
4525
4526
// char16_t
4527
template <>
4528
struct HashEq<std::u16string> : StringHashEqT<char16_t> {};
4529
4530
template <>
4531
struct HashEq<std::u16string_view> : StringHashEqT<char16_t> {};
4532
4533
// wchar_t
4534
template <>
4535
struct HashEq<std::wstring> : StringHashEqT<wchar_t> {};
4536
4537
template <>
4538
struct HashEq<std::wstring_view> : StringHashEqT<wchar_t> {};
4539
4540
#endif
4541
4542
// Supports heterogeneous lookup for pointers and smart pointers.
4543
// -------------------------------------------------------------
4544
template <class T>
4545
struct HashEq<T*> 
4546
{
4547
    struct Hash {
4548
        using is_transparent = void;
4549
        template <class U>
4550
        size_t operator()(const U& ptr) const {
4551
            // we want phmap::Hash<T*> and not phmap::Hash<const T*>
4552
            // so "struct std::hash<T*> " override works
4553
            return phmap::Hash<T*>{}((T*)(uintptr_t)HashEq::ToPtr(ptr));
4554
        }
4555
    };
4556
4557
    struct Eq {
4558
        using is_transparent = void;
4559
        template <class A, class B>
4560
        bool operator()(const A& a, const B& b) const {
4561
            return HashEq::ToPtr(a) == HashEq::ToPtr(b);
4562
        }
4563
    };
4564
4565
private:
4566
    static const T* ToPtr(const T* ptr) { return ptr; }
4567
4568
    template <class U, class D>
4569
    static const T* ToPtr(const std::unique_ptr<U, D>& ptr) {
4570
        return ptr.get();
4571
    }
4572
4573
    template <class U>
4574
    static const T* ToPtr(const std::shared_ptr<U>& ptr) {
4575
        return ptr.get();
4576
    }
4577
};
4578
4579
template <class T, class D>
4580
struct HashEq<std::unique_ptr<T, D>> : HashEq<T*> {};
4581
4582
template <class T>
4583
struct HashEq<std::shared_ptr<T>> : HashEq<T*> {};
4584
4585
namespace hashtable_debug_internal {
4586
4587
// --------------------------------------------------------------------------
4588
// --------------------------------------------------------------------------
4589
4590
template<typename, typename = void >
4591
struct has_member_type_raw_hash_set : std::false_type
4592
{};
4593
template<typename T>
4594
struct has_member_type_raw_hash_set<T, phmap::void_t<typename T::raw_hash_set>> : std::true_type
4595
{};
4596
4597
template <typename Set>
4598
struct HashtableDebugAccess<Set, typename std::enable_if<has_member_type_raw_hash_set<Set>::value>::type>
4599
{
4600
    using Traits = typename Set::PolicyTraits;
4601
    using Slot = typename Traits::slot_type;
4602
4603
    static size_t GetNumProbes(const Set& set,
4604
                               const typename Set::key_type& key) {
4605
        if (!set.ctrl_)
4606
            return 0;
4607
        size_t num_probes = 0;
4608
        size_t hashval = set.hash(key); 
4609
        auto seq = set.probe(hashval);
4610
        while (true) {
4611
            priv::Group g{set.ctrl_ + seq.offset()};
4612
            for (uint32_t i : g.Match((h2_t)priv::H2(hashval))) {
4613
                if (Traits::apply(
4614
                        typename Set::template EqualElement<typename Set::key_type>{
4615
                            key, set.eq_ref()},
4616
                        Traits::element(set.slots_ + seq.offset((size_t)i))))
4617
                    return num_probes;
4618
                ++num_probes;
4619
            }
4620
            if (g.MatchEmpty()) return num_probes;
4621
            seq.next();
4622
            ++num_probes;
4623
        }
4624
    }
4625
4626
    static size_t AllocatedByteSize(const Set& c) {
4627
        size_t capacity = c.capacity_;
4628
        if (capacity == 0) return 0;
4629
        auto layout = Set::MakeLayout(capacity);
4630
        size_t m = layout.AllocSize();
4631
4632
        size_t per_slot = Traits::space_used(static_cast<const Slot*>(nullptr));
4633
        if (per_slot != ~size_t{}) {
4634
            m += per_slot * c.size();
4635
        } else {
4636
            for (size_t i = 0; i != capacity; ++i) {
4637
                if (priv::IsFull(c.ctrl_[i])) {
4638
                    m += Traits::space_used(c.slots_ + i);
4639
                }
4640
            }
4641
        }
4642
        return m;
4643
    }
4644
4645
    static size_t LowerBoundAllocatedByteSize(size_t size) {
4646
        size_t capacity = GrowthToLowerboundCapacity(size);
4647
        if (capacity == 0) return 0;
4648
        auto layout = Set::MakeLayout(NormalizeCapacity(capacity));
4649
        size_t m = layout.AllocSize();
4650
        size_t per_slot = Traits::space_used(static_cast<const Slot*>(nullptr));
4651
        if (per_slot != ~size_t{}) {
4652
            m += per_slot * size;
4653
        }
4654
        return m;
4655
    }
4656
};
4657
4658
4659
template<typename, typename = void >
4660
struct has_member_type_EmbeddedSet : std::false_type
4661
{};
4662
template<typename T>
4663
struct has_member_type_EmbeddedSet<T, phmap::void_t<typename T::EmbeddedSet>> : std::true_type
4664
{};
4665
4666
template <typename Set>
4667
struct HashtableDebugAccess<Set, typename std::enable_if<has_member_type_EmbeddedSet<Set>::value>::type> {
4668
    using Traits = typename Set::PolicyTraits;
4669
    using Slot = typename Traits::slot_type;
4670
    using EmbeddedSet = typename Set::EmbeddedSet;
4671
4672
    static size_t GetNumProbes(const Set& set, const typename Set::key_type& key) {
4673
        size_t hashval = set.hash(key);
4674
        auto& inner = set.sets_[set.subidx(hashval)];
4675
        auto& inner_set = inner.set_;
4676
        return HashtableDebugAccess<EmbeddedSet>::GetNumProbes(inner_set, key);
4677
    }
4678
};
4679
4680
}  // namespace hashtable_debug_internal
4681
}  // namespace priv
4682
4683
// -----------------------------------------------------------------------------
4684
// phmap::flat_hash_set
4685
// -----------------------------------------------------------------------------
4686
// An `phmap::flat_hash_set<T>` is an unordered associative container which has
4687
// been optimized for both speed and memory footprint in most common use cases.
4688
// Its interface is similar to that of `std::unordered_set<T>` with the
4689
// following notable differences:
4690
//
4691
// * Supports heterogeneous lookup, through `find()`, `operator[]()` and
4692
//   `insert()`, provided that the set is provided a compatible heterogeneous
4693
//   hashing function and equality operator.
4694
// * Invalidates any references and pointers to elements within the table after
4695
//   `rehash()`.
4696
// * Contains a `capacity()` member function indicating the number of element
4697
//   slots (open, deleted, and empty) within the hash set.
4698
// * Returns `void` from the `_erase(iterator)` overload.
4699
// -----------------------------------------------------------------------------
4700
template <class T, class Hash, class Eq, class Alloc> // default values in phmap_fwd_decl.h
4701
class flat_hash_set
4702
    : public phmap::priv::raw_hash_set<
4703
          phmap::priv::FlatHashSetPolicy<T>, Hash, Eq, Alloc> 
4704
{
4705
    using Base = typename flat_hash_set::raw_hash_set;
4706
4707
public:
4708
    flat_hash_set() {}
4709
#ifdef __INTEL_COMPILER
4710
    using Base::raw_hash_set;
4711
#else
4712
    using Base::Base;
4713
#endif
4714
    using Base::begin;
4715
    using Base::cbegin;
4716
    using Base::cend;
4717
    using Base::end;
4718
    using Base::capacity;
4719
    using Base::empty;
4720
    using Base::max_size;
4721
    using Base::size;
4722
    using Base::clear; // may shrink - To avoid shrinking `erase(begin(), end())`
4723
    using Base::erase;
4724
    using Base::insert;
4725
    using Base::emplace;
4726
    using Base::emplace_hint; 
4727
    using Base::extract;
4728
    using Base::merge;
4729
    using Base::swap;
4730
    using Base::rehash;
4731
    using Base::reserve;
4732
    using Base::contains;
4733
    using Base::count;
4734
    using Base::equal_range;
4735
    using Base::find;
4736
    using Base::bucket_count;
4737
    using Base::load_factor;
4738
    using Base::max_load_factor;
4739
    using Base::get_allocator;
4740
    using Base::hash_function;
4741
    using Base::hash;
4742
    using Base::key_eq;
4743
};
4744
4745
// -----------------------------------------------------------------------------
4746
// phmap::flat_hash_map
4747
// -----------------------------------------------------------------------------
4748
//
4749
// An `phmap::flat_hash_map<K, V>` is an unordered associative container which
4750
// has been optimized for both speed and memory footprint in most common use
4751
// cases. Its interface is similar to that of `std::unordered_map<K, V>` with
4752
// the following notable differences:
4753
//
4754
// * Supports heterogeneous lookup, through `find()`, `operator[]()` and
4755
//   `insert()`, provided that the map is provided a compatible heterogeneous
4756
//   hashing function and equality operator.
4757
// * Invalidates any references and pointers to elements within the table after
4758
//   `rehash()`.
4759
// * Contains a `capacity()` member function indicating the number of element
4760
//   slots (open, deleted, and empty) within the hash map.
4761
// * Returns `void` from the `_erase(iterator)` overload.
4762
// -----------------------------------------------------------------------------
4763
template <class K, class V, class Hash, class Eq, class Alloc> // default values in phmap_fwd_decl.h
4764
class flat_hash_map : public phmap::priv::raw_hash_map<
4765
                          phmap::priv::FlatHashMapPolicy<K, V>,
4766
                          Hash, Eq, Alloc> {
4767
    using Base = typename flat_hash_map::raw_hash_map;
4768
4769
public:
4770
1.77k
    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
4770
1.18k
    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
4770
593
    flat_hash_map() {}
4771
#ifdef __INTEL_COMPILER
4772
    using Base::raw_hash_map;
4773
#else
4774
    using Base::Base;
4775
#endif
4776
    using Base::begin;
4777
    using Base::cbegin;
4778
    using Base::cend;
4779
    using Base::end;
4780
    using Base::capacity;
4781
    using Base::empty;
4782
    using Base::max_size;
4783
    using Base::size;
4784
    using Base::clear;
4785
    using Base::erase;
4786
    using Base::insert;
4787
    using Base::insert_or_assign;
4788
    using Base::emplace;
4789
    using Base::emplace_hint;
4790
    using Base::try_emplace;
4791
    using Base::extract;
4792
    using Base::merge;
4793
    using Base::swap;
4794
    using Base::rehash;
4795
    using Base::reserve;
4796
    using Base::at;
4797
    using Base::contains;
4798
    using Base::count;
4799
    using Base::equal_range;
4800
    using Base::find;
4801
    using Base::operator[];
4802
    using Base::bucket_count;
4803
    using Base::load_factor;
4804
    using Base::max_load_factor;
4805
    using Base::get_allocator;
4806
    using Base::hash_function;
4807
    using Base::hash;
4808
    using Base::key_eq;
4809
};
4810
4811
// -----------------------------------------------------------------------------
4812
// phmap::node_hash_set
4813
// -----------------------------------------------------------------------------
4814
// An `phmap::node_hash_set<T>` is an unordered associative container which
4815
// has been optimized for both speed and memory footprint in most common use
4816
// cases. Its interface is similar to that of `std::unordered_set<T>` with the
4817
// following notable differences:
4818
//
4819
// * Supports heterogeneous lookup, through `find()`, `operator[]()` and
4820
//   `insert()`, provided that the map is provided a compatible heterogeneous
4821
//   hashing function and equality operator.
4822
// * Contains a `capacity()` member function indicating the number of element
4823
//   slots (open, deleted, and empty) within the hash set.
4824
// * Returns `void` from the `_erase(iterator)` overload.
4825
// -----------------------------------------------------------------------------
4826
template <class T, class Hash, class Eq, class Alloc> // default values in phmap_fwd_decl.h
4827
class node_hash_set
4828
    : public phmap::priv::raw_hash_set<
4829
          phmap::priv::NodeHashSetPolicy<T>, Hash, Eq, Alloc> 
4830
{
4831
    using Base = typename node_hash_set::raw_hash_set;
4832
4833
public:
4834
    node_hash_set() {}
4835
#ifdef __INTEL_COMPILER
4836
    using Base::raw_hash_set;
4837
#else
4838
    using Base::Base;
4839
#endif
4840
    using Base::begin;
4841
    using Base::cbegin;
4842
    using Base::cend;
4843
    using Base::end;
4844
    using Base::capacity;
4845
    using Base::empty;
4846
    using Base::max_size;
4847
    using Base::size;
4848
    using Base::clear;
4849
    using Base::erase;
4850
    using Base::insert;
4851
    using Base::emplace;
4852
    using Base::emplace_hint;
4853
    using Base::emplace_with_hash;
4854
    using Base::emplace_hint_with_hash;
4855
    using Base::extract;
4856
    using Base::merge;
4857
    using Base::swap;
4858
    using Base::rehash;
4859
    using Base::reserve;
4860
    using Base::contains;
4861
    using Base::count;
4862
    using Base::equal_range;
4863
    using Base::find;
4864
    using Base::bucket_count;
4865
    using Base::load_factor;
4866
    using Base::max_load_factor;
4867
    using Base::get_allocator;
4868
    using Base::hash_function;
4869
    using Base::hash;
4870
    using Base::key_eq;
4871
    typename Base::hasher hash_funct() { return this->hash_function(); }
4872
    void resize(typename Base::size_type hint) { this->rehash(hint); }
4873
};
4874
4875
// -----------------------------------------------------------------------------
4876
// phmap::node_hash_map
4877
// -----------------------------------------------------------------------------
4878
//
4879
// An `phmap::node_hash_map<K, V>` is an unordered associative container which
4880
// has been optimized for both speed and memory footprint in most common use
4881
// cases. Its interface is similar to that of `std::unordered_map<K, V>` with
4882
// the following notable differences:
4883
//
4884
// * Supports heterogeneous lookup, through `find()`, `operator[]()` and
4885
//   `insert()`, provided that the map is provided a compatible heterogeneous
4886
//   hashing function and equality operator.
4887
// * Contains a `capacity()` member function indicating the number of element
4888
//   slots (open, deleted, and empty) within the hash map.
4889
// * Returns `void` from the `_erase(iterator)` overload.
4890
// -----------------------------------------------------------------------------
4891
template <class Key, class Value, class Hash, class Eq, class Alloc>  // default values in phmap_fwd_decl.h
4892
class node_hash_map
4893
    : public phmap::priv::raw_hash_map<
4894
          phmap::priv::NodeHashMapPolicy<Key, Value>, Hash, Eq,
4895
          Alloc> 
4896
{
4897
    using Base = typename node_hash_map::raw_hash_map;
4898
4899
public:
4900
    node_hash_map() {}
4901
#ifdef __INTEL_COMPILER
4902
    using Base::raw_hash_map;
4903
#else
4904
    using Base::Base;
4905
#endif
4906
    using Base::begin;
4907
    using Base::cbegin;
4908
    using Base::cend;
4909
    using Base::end;
4910
    using Base::capacity;
4911
    using Base::empty;
4912
    using Base::max_size;
4913
    using Base::size;
4914
    using Base::clear;
4915
    using Base::erase;
4916
    using Base::insert;
4917
    using Base::insert_or_assign;
4918
    using Base::emplace;
4919
    using Base::emplace_hint;
4920
    using Base::try_emplace;
4921
    using Base::extract;
4922
    using Base::merge;
4923
    using Base::swap;
4924
    using Base::rehash;
4925
    using Base::reserve;
4926
    using Base::at;
4927
    using Base::contains;
4928
    using Base::count;
4929
    using Base::equal_range;
4930
    using Base::find;
4931
    using Base::operator[];
4932
    using Base::bucket_count;
4933
    using Base::load_factor;
4934
    using Base::max_load_factor;
4935
    using Base::get_allocator;
4936
    using Base::hash_function;
4937
    using Base::hash;
4938
    using Base::key_eq;
4939
    typename Base::hasher hash_funct() { return this->hash_function(); }
4940
    void resize(typename Base::size_type hint) { this->rehash(hint); }
4941
};
4942
4943
// -----------------------------------------------------------------------------
4944
// phmap::parallel_flat_hash_set
4945
// -----------------------------------------------------------------------------
4946
template <class T, class Hash, class Eq, class Alloc, size_t N, class Mtx_> // default values in phmap_fwd_decl.h
4947
class parallel_flat_hash_set
4948
    : public phmap::priv::parallel_hash_set<
4949
         N, phmap::priv::raw_hash_set, Mtx_,
4950
         phmap::priv::FlatHashSetPolicy<T>, 
4951
         Hash, Eq, Alloc> 
4952
{
4953
    using Base = typename parallel_flat_hash_set::parallel_hash_set;
4954
4955
public:
4956
    parallel_flat_hash_set() {}
4957
#ifdef __INTEL_COMPILER
4958
    using Base::parallel_hash_set;
4959
#else
4960
    using Base::Base;
4961
#endif
4962
    using Base::hash;
4963
    using Base::subidx;
4964
    using Base::subcnt;
4965
    using Base::begin;
4966
    using Base::cbegin;
4967
    using Base::cend;
4968
    using Base::end;
4969
    using Base::capacity;
4970
    using Base::empty;
4971
    using Base::max_size;
4972
    using Base::size;
4973
    using Base::clear;
4974
    using Base::erase;
4975
    using Base::insert;
4976
    using Base::emplace;
4977
    using Base::emplace_hint;
4978
    using Base::emplace_with_hash;
4979
    using Base::emplace_hint_with_hash;
4980
    using Base::extract;
4981
    using Base::merge;
4982
    using Base::swap;
4983
    using Base::rehash;
4984
    using Base::reserve;
4985
    using Base::contains;
4986
    using Base::count;
4987
    using Base::equal_range;
4988
    using Base::find;
4989
    using Base::bucket_count;
4990
    using Base::load_factor;
4991
    using Base::max_load_factor;
4992
    using Base::get_allocator;
4993
    using Base::hash_function;
4994
    using Base::key_eq;
4995
};
4996
4997
// -----------------------------------------------------------------------------
4998
// phmap::parallel_flat_hash_map - default values in phmap_fwd_decl.h
4999
// -----------------------------------------------------------------------------
5000
template <class K, class V, class Hash, class Eq, class Alloc, size_t N, class Mtx_>
5001
class parallel_flat_hash_map : public phmap::priv::parallel_hash_map<
5002
                N, phmap::priv::raw_hash_set, Mtx_,
5003
                phmap::priv::FlatHashMapPolicy<K, V>,
5004
                Hash, Eq, Alloc> 
5005
{
5006
    using Base = typename parallel_flat_hash_map::parallel_hash_map;
5007
5008
public:
5009
    parallel_flat_hash_map() {}
5010
#ifdef __INTEL_COMPILER
5011
    using Base::parallel_hash_map;
5012
#else
5013
    using Base::Base;
5014
#endif
5015
    using Base::hash;
5016
    using Base::subidx;
5017
    using Base::subcnt;
5018
    using Base::begin;
5019
    using Base::cbegin;
5020
    using Base::cend;
5021
    using Base::end;
5022
    using Base::capacity;
5023
    using Base::empty;
5024
    using Base::max_size;
5025
    using Base::size;
5026
    using Base::clear;
5027
    using Base::erase;
5028
    using Base::insert;
5029
    using Base::insert_or_assign;
5030
    using Base::emplace;
5031
    using Base::emplace_hint;
5032
    using Base::try_emplace;
5033
    using Base::emplace_with_hash;
5034
    using Base::emplace_hint_with_hash;
5035
    using Base::try_emplace_with_hash;
5036
    using Base::extract;
5037
    using Base::merge;
5038
    using Base::swap;
5039
    using Base::rehash;
5040
    using Base::reserve;
5041
    using Base::at;
5042
    using Base::contains;
5043
    using Base::count;
5044
    using Base::equal_range;
5045
    using Base::find;
5046
    using Base::operator[];
5047
    using Base::bucket_count;
5048
    using Base::load_factor;
5049
    using Base::max_load_factor;
5050
    using Base::get_allocator;
5051
    using Base::hash_function;
5052
    using Base::key_eq;
5053
};
5054
5055
// -----------------------------------------------------------------------------
5056
// phmap::parallel_node_hash_set
5057
// -----------------------------------------------------------------------------
5058
template <class T, class Hash, class Eq, class Alloc, size_t N, class Mtx_>
5059
class parallel_node_hash_set
5060
    : public phmap::priv::parallel_hash_set<
5061
             N, phmap::priv::raw_hash_set, Mtx_,
5062
             phmap::priv::NodeHashSetPolicy<T>, Hash, Eq, Alloc> 
5063
{
5064
    using Base = typename parallel_node_hash_set::parallel_hash_set;
5065
5066
public:
5067
    parallel_node_hash_set() {}
5068
#ifdef __INTEL_COMPILER
5069
    using Base::parallel_hash_set;
5070
#else
5071
    using Base::Base;
5072
#endif
5073
    using Base::hash;
5074
    using Base::subidx;
5075
    using Base::subcnt;
5076
    using Base::begin;
5077
    using Base::cbegin;
5078
    using Base::cend;
5079
    using Base::end;
5080
    using Base::capacity;
5081
    using Base::empty;
5082
    using Base::max_size;
5083
    using Base::size;
5084
    using Base::clear;
5085
    using Base::erase;
5086
    using Base::insert;
5087
    using Base::emplace;
5088
    using Base::emplace_hint;
5089
    using Base::emplace_with_hash;
5090
    using Base::emplace_hint_with_hash;
5091
    using Base::extract;
5092
    using Base::merge;
5093
    using Base::swap;
5094
    using Base::rehash;
5095
    using Base::reserve;
5096
    using Base::contains;
5097
    using Base::count;
5098
    using Base::equal_range;
5099
    using Base::find;
5100
    using Base::bucket_count;
5101
    using Base::load_factor;
5102
    using Base::max_load_factor;
5103
    using Base::get_allocator;
5104
    using Base::hash_function;
5105
    using Base::key_eq;
5106
    typename Base::hasher hash_funct() { return this->hash_function(); }
5107
    void resize(typename Base::size_type hint) { this->rehash(hint); }
5108
};
5109
5110
// -----------------------------------------------------------------------------
5111
// phmap::parallel_node_hash_map
5112
// -----------------------------------------------------------------------------
5113
template <class Key, class Value, class Hash, class Eq, class Alloc, size_t N, class Mtx_>
5114
class parallel_node_hash_map
5115
    : public phmap::priv::parallel_hash_map<
5116
          N, phmap::priv::raw_hash_set, Mtx_,
5117
          phmap::priv::NodeHashMapPolicy<Key, Value>, Hash, Eq,
5118
          Alloc> 
5119
{
5120
    using Base = typename parallel_node_hash_map::parallel_hash_map;
5121
5122
public:
5123
    parallel_node_hash_map() {}
5124
#ifdef __INTEL_COMPILER
5125
    using Base::parallel_hash_map;
5126
#else
5127
    using Base::Base;
5128
#endif
5129
    using Base::hash;
5130
    using Base::subidx;
5131
    using Base::subcnt;
5132
    using Base::begin;
5133
    using Base::cbegin;
5134
    using Base::cend;
5135
    using Base::end;
5136
    using Base::capacity;
5137
    using Base::empty;
5138
    using Base::max_size;
5139
    using Base::size;
5140
    using Base::clear;
5141
    using Base::erase;
5142
    using Base::insert;
5143
    using Base::insert_or_assign;
5144
    using Base::emplace;
5145
    using Base::emplace_hint;
5146
    using Base::try_emplace;
5147
    using Base::emplace_with_hash;
5148
    using Base::emplace_hint_with_hash;
5149
    using Base::try_emplace_with_hash;
5150
    using Base::extract;
5151
    using Base::merge;
5152
    using Base::swap;
5153
    using Base::rehash;
5154
    using Base::reserve;
5155
    using Base::at;
5156
    using Base::contains;
5157
    using Base::count;
5158
    using Base::equal_range;
5159
    using Base::find;
5160
    using Base::operator[];
5161
    using Base::bucket_count;
5162
    using Base::load_factor;
5163
    using Base::max_load_factor;
5164
    using Base::get_allocator;
5165
    using Base::hash_function;
5166
    using Base::key_eq;
5167
    typename Base::hasher hash_funct() { return this->hash_function(); }
5168
    void resize(typename Base::size_type hint) { this->rehash(hint); }
5169
};
5170
5171
}  // namespace phmap
5172
5173
5174
namespace phmap {
5175
    namespace priv {
5176
        template <class C, class Pred> 
5177
        std::size_t erase_if(C &c, Pred pred) {
5178
            auto old_size = c.size();
5179
            for (auto i = c.begin(), last = c.end(); i != last; ) {
5180
                if (pred(*i)) {
5181
                    i = c.erase(i);
5182
                } else {
5183
                    ++i;
5184
                }
5185
            }
5186
            return old_size - c.size();
5187
        }
5188
    } // priv
5189
5190
    // ======== erase_if for phmap set containers ==================================
5191
    template <class T, class Hash, class Eq, class Alloc, class Pred> 
5192
    std::size_t erase_if(phmap::flat_hash_set<T, Hash, Eq, Alloc>& c, Pred pred) {
5193
        return phmap::priv::erase_if(c, std::move(pred));
5194
    }
5195
5196
    template <class T, class Hash, class Eq, class Alloc, class Pred> 
5197
    std::size_t erase_if(phmap::node_hash_set<T, Hash, Eq, Alloc>& c, Pred pred) {
5198
        return phmap::priv::erase_if(c, std::move(pred));
5199
    }
5200
5201
    template <class T, class Hash, class Eq, class Alloc, size_t N, class Mtx_, class Pred> 
5202
    std::size_t erase_if(phmap::parallel_flat_hash_set<T, Hash, Eq, Alloc, N, Mtx_>& c, Pred pred) {
5203
        return phmap::priv::erase_if(c, std::move(pred));
5204
    }
5205
5206
    template <class T, class Hash, class Eq, class Alloc, size_t N, class Mtx_, class Pred> 
5207
    std::size_t erase_if(phmap::parallel_node_hash_set<T, Hash, Eq, Alloc, N, Mtx_>& c, Pred pred) {
5208
        return phmap::priv::erase_if(c, std::move(pred));
5209
    }
5210
5211
    // ======== erase_if for phmap map containers ==================================
5212
    template <class K, class V, class Hash, class Eq, class Alloc, class Pred> 
5213
    std::size_t erase_if(phmap::flat_hash_map<K, V, Hash, Eq, Alloc>& c, Pred pred) {
5214
        return phmap::priv::erase_if(c, std::move(pred));
5215
    }
5216
5217
    template <class K, class V, class Hash, class Eq, class Alloc, class Pred> 
5218
    std::size_t erase_if(phmap::node_hash_map<K, V, Hash, Eq, Alloc>& c, Pred pred) {
5219
        return phmap::priv::erase_if(c, std::move(pred));
5220
    }
5221
5222
    template <class K, class V, class Hash, class Eq, class Alloc, size_t N, class Mtx_, class Pred> 
5223
    std::size_t erase_if(phmap::parallel_flat_hash_map<K, V, Hash, Eq, Alloc, N, Mtx_>& c, Pred pred) {
5224
        return phmap::priv::erase_if(c, std::move(pred));
5225
    }
5226
5227
    template <class K, class V, class Hash, class Eq, class Alloc, size_t N, class Mtx_, class Pred> 
5228
    std::size_t erase_if(phmap::parallel_node_hash_map<K, V, Hash, Eq, Alloc, N, Mtx_>& c, Pred pred) {
5229
        return phmap::priv::erase_if(c, std::move(pred));
5230
    }
5231
5232
} // phmap
5233
5234
#ifdef _MSC_VER
5235
     #pragma warning(pop)  
5236
#endif
5237
5238
5239
#endif // phmap_h_guard_