Coverage Report

Created: 2026-04-12 07:02

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
584
               std::false_type /* propagate_on_container_swap */) {}
142
143
// --------------------------------------------------------------------------
144
template <size_t Width>
145
class probe_seq 
146
{
147
public:
148
12.0M
    probe_seq(size_t hashval, size_t mask) {
149
12.0M
        assert(((mask + 1) & mask) == 0 && "not a mask");
150
12.0M
        mask_ = mask;
151
12.0M
        offset_ = hashval & mask_;
152
12.0M
    }
153
13.2M
    size_t offset() const { return offset_; }
154
22.4M
    size_t offset(size_t i) const { return (offset_ + i) & mask_; }
155
156
1.22M
    void next() {
157
1.22M
        index_ += Width;
158
1.22M
        offset_ += index_;
159
1.22M
        offset_ &= mask_;
160
1.22M
    }
161
    // 0-based probe index. The i-th probe in the probe sequence.
162
1.68M
    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
13.3M
uint32_t TrailingZeros(T x) {
209
13.3M
    uint32_t res;
210
13.3M
    PHMAP_IF_CONSTEXPR(sizeof(T) == 8)
211
        res = base_internal::CountTrailingZerosNonZero64(static_cast<uint64_t>(x));
212
    else
213
13.3M
        res = base_internal::CountTrailingZerosNonZero32(static_cast<uint32_t>(x));
214
13.3M
    return res;
215
13.3M
}
unsigned int phmap::priv::TrailingZeros<unsigned int>(unsigned int)
Line
Count
Source
208
13.3M
uint32_t TrailingZeros(T x) {
209
13.3M
    uint32_t res;
210
13.3M
    PHMAP_IF_CONSTEXPR(sizeof(T) == 8)
211
        res = base_internal::CountTrailingZerosNonZero64(static_cast<uint64_t>(x));
212
    else
213
13.3M
        res = base_internal::CountTrailingZerosNonZero32(static_cast<uint32_t>(x));
214
13.3M
    return res;
215
13.3M
}
Unexecuted instantiation: unsigned int phmap::priv::TrailingZeros<unsigned long>(unsigned long)
216
217
// --------------------------------------------------------------------------
218
template <typename T>
219
0
uint32_t LeadingZeros(T x) {
220
0
    uint32_t res;
221
0
    PHMAP_IF_CONSTEXPR(sizeof(T) == 8)
222
0
        res = base_internal::CountLeadingZeros64(static_cast<uint64_t>(x));
223
0
    else
224
0
        res = base_internal::CountLeadingZeros32(static_cast<uint32_t>(x));
225
0
    return res;
226
0
}
227
228
// --------------------------------------------------------------------------
229
// An abstraction over a bitmask. It provides an easy way to iterate through the
230
// indexes of the set bits of a bitmask.  When Shift=0 (platforms with SSE),
231
// this is a true bitmask.  On non-SSE, platforms the arithematic used to
232
// emulate the SSE behavior works in bytes (Shift=3) and leaves each bytes as
233
// either 0x00 or 0x80.
234
//
235
// For example:
236
//   for (int i : BitMask<uint32_t, 16>(0x5)) -> yields 0, 2
237
//   for (int i : BitMask<uint64_t, 8, 3>(0x0000000080800000)) -> yields 2, 3
238
// --------------------------------------------------------------------------
239
template <class T, int SignificantBits, int Shift = 0>
240
class BitMask 
241
{
242
    static_assert(std::is_unsigned<T>::value, "");
243
    static_assert(Shift == 0 || Shift == 3, "");
244
245
public:
246
    // These are useful for unit tests (gunit).
247
    using value_type = int;
248
    using iterator = BitMask;
249
    using const_iterator = BitMask;
250
251
26.4M
    explicit BitMask(T mask) : mask_(mask) {}
252
253
1.71M
    BitMask& operator++() {    // ++iterator
254
1.71M
        mask_ &= (mask_ - 1);  // clear the least significant bit set
255
1.71M
        return *this;
256
1.71M
    }
257
258
3.38M
    explicit operator bool() const { return mask_ != 0; }
259
11.5M
    uint32_t operator*() const { return LowestBitSet(); }
260
261
13.1M
    uint32_t LowestBitSet() const {
262
13.1M
        return priv::TrailingZeros(mask_) >> Shift;
263
13.1M
    }
264
265
    uint32_t HighestBitSet() const {
266
        return (sizeof(T) * CHAR_BIT - priv::LeadingZeros(mask_) - 1) >> Shift;
267
    }
268
269
11.5M
    BitMask begin() const { return *this; }
270
11.5M
    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
13.2M
    friend bool operator!=(const BitMask& a, const BitMask& b) {
287
13.2M
        return a.mask_ != b.mask_;
288
13.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.02k
inline ctrl_t* EmptyGroup() {
334
3.02k
  PHMAP_IF_CONSTEXPR (std_alloc_t::value) {
335
3.02k
      alignas(16) static constexpr ctrl_t empty_group[] = {
336
3.02k
          kSentinel, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty,
337
3.02k
          kEmpty,    kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty};
338
339
3.02k
      return const_cast<ctrl_t*>(empty_group);
340
  } else {
341
       return nullptr;
342
  }
343
3.02k
}
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.44k
inline ctrl_t* EmptyGroup() {
334
2.44k
  PHMAP_IF_CONSTEXPR (std_alloc_t::value) {
335
2.44k
      alignas(16) static constexpr ctrl_t empty_group[] = {
336
2.44k
          kSentinel, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty,
337
2.44k
          kEmpty,    kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty};
338
339
2.44k
      return const_cast<ctrl_t*>(empty_group);
340
  } else {
341
       return nullptr;
342
  }
343
2.44k
}
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
584
inline ctrl_t* EmptyGroup() {
334
584
  PHMAP_IF_CONSTEXPR (std_alloc_t::value) {
335
584
      alignas(16) static constexpr ctrl_t empty_group[] = {
336
584
          kSentinel, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty,
337
584
          kEmpty,    kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty};
338
339
584
      return const_cast<ctrl_t*>(empty_group);
340
  } else {
341
       return nullptr;
342
  }
343
584
}
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
12.0M
inline size_t H1(size_t hashval, const ctrl_t* ) {
364
12.0M
    return (hashval >> 7);
365
12.0M
}
366
367
#endif
368
369
370
13.1M
inline ctrl_t H2(size_t hashval)       { return (ctrl_t)(hashval & 0x7F); }
371
372
576k
inline bool IsEmpty(ctrl_t c)          { return c == kEmpty; }
373
2.74M
inline bool IsFull(ctrl_t c)           { return c >= static_cast<ctrl_t>(0); }
374
3.12k
inline bool IsDeleted(ctrl_t c)        { return c == kDeleted; }
375
772k
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
1.89M
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
1.89M
  return _mm_cmpgt_epi8(a, b);
405
1.89M
}
406
407
// --------------------------------------------------------------------------
408
// --------------------------------------------------------------------------
409
struct GroupSse2Impl 
410
{
411
    enum { kWidth = 16 };  // the number of slots per group
412
413
13.4M
    explicit GroupSse2Impl(const ctrl_t* pos) {
414
13.4M
        ctrl = _mm_loadu_si128(reinterpret_cast<const __m128i*>(pos));
415
13.4M
    }
416
417
    // Returns a bitmask representing the positions of slots that match hash.
418
    // ----------------------------------------------------------------------
419
13.2M
    BitMask<uint32_t, kWidth> Match(h2_t hash) const {
420
13.2M
        auto match = _mm_set1_epi8((char)hash);
421
13.2M
        return BitMask<uint32_t, kWidth>(
422
13.2M
            static_cast<uint32_t>(_mm_movemask_epi8(_mm_cmpeq_epi8(match, ctrl))));
423
13.2M
    }
424
425
    // Returns a bitmask representing the positions of empty slots.
426
    // ------------------------------------------------------------
427
1.70M
    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.70M
        return Match(static_cast<h2_t>(kEmpty));
434
1.70M
#endif
435
1.70M
    }
436
437
    // Returns a bitmask representing the positions of empty or deleted slots.
438
    // -----------------------------------------------------------------------
439
1.68M
    BitMask<uint32_t, kWidth> MatchEmptyOrDeleted() const {
440
1.68M
        auto special = _mm_set1_epi8(static_cast<char>(kSentinel));
441
1.68M
        return BitMask<uint32_t, kWidth>(
442
1.68M
            static_cast<uint32_t>(_mm_movemask_epi8(_mm_cmpgt_epi8_fixed(special, ctrl))));
443
1.68M
    }
444
445
    // Returns the number of trailing empty or deleted elements in the group.
446
    // ----------------------------------------------------------------------
447
213k
    uint32_t CountLeadingEmptyOrDeleted() const {
448
213k
        auto special = _mm_set1_epi8(static_cast<char>(kSentinel));
449
213k
        return TrailingZeros(
450
213k
            static_cast<uint32_t>(_mm_movemask_epi8(_mm_cmpgt_epi8_fixed(special, ctrl)) + 1));
451
213k
    }
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.4k
inline bool IsValidCapacity(size_t n) { return ((n + 1) & n) == 0 && n > 0; }
546
547
// --------------------------------------------------------------------------
548
// PRECONDITION:
549
//   IsValidCapacity(capacity)
550
//   ctrl[capacity] == kSentinel
551
//   ctrl[i] != kSentinel for all i < capacity
552
// Applies mapping for every byte in ctrl:
553
//   DELETED -> EMPTY
554
//   EMPTY -> EMPTY
555
//   FULL -> DELETED
556
// --------------------------------------------------------------------------
557
inline void ConvertDeletedToEmptyAndFullToDeleted(
558
    ctrl_t* PHMAP_RESTRICT ctrl, size_t capacity) 
559
0
{
560
0
    assert(ctrl[capacity] == kSentinel);
561
0
    assert(IsValidCapacity(capacity));
562
0
    for (ctrl_t* pos = ctrl; pos != ctrl + capacity + 1; pos += Group::kWidth) {
563
0
        Group{pos}.ConvertSpecialToEmptyAndFullToDeleted(pos);
564
0
    }
565
    // Copy the cloned ctrl bytes.
566
0
    std::memcpy(ctrl + capacity + 1, ctrl, Group::kWidth);
567
0
    ctrl[capacity] = kSentinel;
568
0
}
569
570
// --------------------------------------------------------------------------
571
// Rounds up the capacity to the next power of 2 minus 1, with a minimum of 1.
572
// --------------------------------------------------------------------------
573
inline size_t NormalizeCapacity(size_t n) 
574
0
{
575
0
    return n ? ~size_t{} >> LeadingZeros(n) : 1;
576
0
}
577
578
// --------------------------------------------------------------------------
579
// We use 7/8th as maximum load factor.
580
// For 16-wide groups, that gives an average of two empty slots per group.
581
// --------------------------------------------------------------------------
582
inline size_t CapacityToGrowth(size_t capacity) 
583
5.82k
{
584
5.82k
    assert(IsValidCapacity(capacity));
585
    // `capacity*7/8`
586
5.82k
    PHMAP_IF_CONSTEXPR (Group::kWidth == 8) {
587
5.82k
        if (capacity == 7) {
588
            // x-x/8 does not work when x==7.
589
            return 6;
590
        }
591
    }
592
5.82k
    return capacity - capacity / 8;
593
5.82k
}
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.25k
    inline void RecordStorageChanged(size_t , size_t ) {}
677
0
    inline void RecordRehash(size_t ) {}
678
576k
    inline void RecordInsert(size_t , size_t ) {}
679
0
    inline void RecordErase() {}
680
    friend inline void swap(HashtablezInfoHandle& ,
681
584
                            HashtablezInfoHandle& ) noexcept {}
682
};
683
684
689
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
22.4M
DecomposePairImpl(F&& f, std::pair<std::tuple<K>, V> p) {
757
22.4M
    const auto& key = std::get<0>(p.first);
758
22.4M
    return std::forward<F>(f)(key, std::piecewise_construct, std::move(p.first),
759
22.4M
                              std::move(p.second));
760
22.4M
}
_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
9.85M
DecomposePairImpl(F&& f, std::pair<std::tuple<K>, V> p) {
757
9.85M
    const auto& key = std::get<0>(p.first);
758
9.85M
    return std::forward<F>(f)(key, std::piecewise_construct, std::move(p.first),
759
9.85M
                              std::move(p.second));
760
9.85M
}
_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
10.9M
DecomposePairImpl(F&& f, std::pair<std::tuple<K>, V> p) {
757
10.9M
    const auto& key = std::get<0>(p.first);
758
10.9M
    return std::forward<F>(f)(key, std::piecewise_construct, std::move(p.first),
759
10.9M
                              std::move(p.second));
760
10.9M
}
_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
1.57M
DecomposePairImpl(F&& f, std::pair<std::tuple<K>, V> p) {
757
1.57M
    const auto& key = std::get<0>(p.first);
758
1.57M
    return std::forward<F>(f)(key, std::piecewise_construct, std::move(p.first),
759
1.57M
                              std::move(p.second));
760
1.57M
}
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.51k
    static Layout MakeLayout(size_t capacity) {
888
6.51k
        assert(IsValidCapacity(capacity));
889
6.51k
        return Layout(capacity + Group::kWidth + 1, capacity);
890
6.51k
    }
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.51k
    static Layout MakeLayout(size_t capacity) {
888
6.51k
        assert(IsValidCapacity(capacity));
889
6.51k
        return Layout(capacity + Group::kWidth + 1, capacity);
890
6.51k
    }
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
559k
        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
559k
        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
559k
        iterator& operator++() {
952
559k
            ++ctrl_;
953
559k
            ++slot_;
954
559k
            skip_empty_or_deleted();
955
559k
            return *this;
956
559k
        }
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
559k
        iterator& operator++() {
952
559k
            ++ctrl_;
953
559k
            ++slot_;
954
559k
            skip_empty_or_deleted();
955
559k
            return *this;
956
559k
        }
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
559k
        friend bool operator==(const iterator& a, const iterator& b) {
984
559k
            return a.ctrl_ == b.ctrl_;
985
559k
        }
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
559k
        friend bool operator==(const iterator& a, const iterator& b) {
984
559k
            return a.ctrl_ == b.ctrl_;
985
559k
        }
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
584
        friend bool operator==(const iterator& a, const iterator& b) {
984
584
            return a.ctrl_ == b.ctrl_;
985
584
        }
986
584
        friend bool operator!=(const iterator& a, const iterator& b) {
987
584
            return !(a == b);
988
584
        }
989
990
    private:
991
1.36k
        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
198
        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.16k
        iterator(ctrl_t* ctrl) : ctrl_(ctrl) {}  // for end()
992
9.85M
        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
9.85M
        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
559k
        void skip_empty_or_deleted() {
995
559k
            PHMAP_IF_CONSTEXPR (!std_alloc_t::value) {
996
                // ctrl_ could be nullptr
997
                if (!ctrl_)
998
                    return;
999
            }
1000
772k
            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
213k
                uint32_t shift = Group{ctrl_}.CountLeadingEmptyOrDeleted();
1006
213k
                ctrl_ += shift;
1007
213k
                slot_ += shift;
1008
213k
            }
1009
559k
        }
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
559k
        void skip_empty_or_deleted() {
995
559k
            PHMAP_IF_CONSTEXPR (!std_alloc_t::value) {
996
                // ctrl_ could be nullptr
997
                if (!ctrl_)
998
                    return;
999
            }
1000
772k
            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
213k
                uint32_t shift = Group{ctrl_}.CountLeadingEmptyOrDeleted();
1006
213k
                ctrl_ += shift;
1007
213k
                slot_ += shift;
1008
213k
            }
1009
559k
        }
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
334
        const_iterator(iterator i) : inner_(std::move(i)) {}
1033
1034
559k
        reference operator*() const { return *inner_; }
1035
        pointer operator->() const { return inner_.operator->(); }
1036
1037
559k
        const_iterator& operator++() {
1038
559k
            ++inner_;
1039
559k
            return *this;
1040
559k
        }
1041
        const_iterator operator++(int) { return inner_++; }
1042
1043
559k
        friend bool operator==(const const_iterator& a, const const_iterator& b) {
1044
559k
            return a.inner_ == b.inner_;
1045
559k
        }
1046
559k
        friend bool operator!=(const const_iterator& a, const const_iterator& b) {
1047
559k
            return !(a == b);
1048
559k
        }
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.33k
        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.75k
        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
584
        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.33k
    ~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.75k
    ~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
584
    ~raw_hash_set() { destroy_slots(); }
1246
1247
751
    iterator begin() {
1248
751
        if (empty()) return end();
1249
136
        auto it = iterator_at(0);
1250
136
        it.skip_empty_or_deleted();
1251
136
        return it;
1252
751
    }
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
167
    iterator begin() {
1248
167
        if (empty()) return end();
1249
136
        auto it = iterator_at(0);
1250
136
        it.skip_empty_or_deleted();
1251
136
        return it;
1252
167
    }
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
584
    iterator begin() {
1248
584
        if (empty()) return end();
1249
0
        auto it = iterator_at(0);
1250
0
        it.skip_empty_or_deleted();
1251
0
        return it;
1252
584
    }
1253
    iterator end() 
1254
1.36k
    {
1255
#if 0 // PHMAP_BIDIRECTIONAL
1256
        return iterator_at(capacity_); 
1257
#else
1258
1.36k
        return {ctrl_ + capacity_};
1259
1.36k
#endif
1260
1.36k
    }
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
198
    {
1255
#if 0 // PHMAP_BIDIRECTIONAL
1256
        return iterator_at(capacity_); 
1257
#else
1258
198
        return {ctrl_ + capacity_};
1259
198
#endif
1260
198
    }
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.16k
    {
1255
#if 0 // PHMAP_BIDIRECTIONAL
1256
        return iterator_at(capacity_); 
1257
#else
1258
1.16k
        return {ctrl_ + capacity_};
1259
1.16k
#endif
1260
1.16k
    }
1261
1262
167
    const_iterator begin() const {
1263
167
        return const_cast<raw_hash_set*>(this)->begin();
1264
167
    }
1265
167
    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
751
    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
167
    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
584
    bool empty() const { return !size(); }
1270
4.48k
    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
3.90k
    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
584
    size_t size() const { return size_; }
1271
2.90k
    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
9.85M
    std::pair<iterator, bool> insert(T&& value) {
1304
9.85M
        return emplace(std::forward<T>(value));
1305
9.85M
    }
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
9.85M
    std::pair<iterator, bool> emplace(Args&&... args) {
1443
9.85M
        return PolicyTraits::apply(EmplaceDecomposable{*this},
1444
9.85M
                                   std::forward<Args>(args)...);
1445
9.85M
    }
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
584
         IsNoThrowSwappable<allocator_type>(typename AllocTraits::propagate_on_container_swap{}))) {
1679
584
        using std::swap;
1680
584
        swap(ctrl_, that.ctrl_);
1681
584
        swap(slots_, that.slots_);
1682
584
        swap(size_, that.size_);
1683
584
        swap(capacity_, that.capacity_);
1684
584
        swap(growth_left(), that.growth_left());
1685
584
        swap(hash_ref(), that.hash_ref());
1686
584
        swap(eq_ref(), that.eq_ref());
1687
584
        swap(infoz_, that.infoz_);
1688
584
        SwapAlloc(alloc_ref(), that.alloc_ref(), typename AllocTraits::propagate_on_container_swap{});
1689
584
    }
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((std::max)(n, 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
584
    friend bool operator==(const raw_hash_set& a, const raw_hash_set& b) {
1832
584
        if (a.size() != b.size()) return false;
1833
167
        const raw_hash_set* outer = &a;
1834
167
        const raw_hash_set* inner = &b;
1835
167
        if (outer->capacity() > inner->capacity()) 
1836
0
            std::swap(outer, inner);
1837
167
        for (const value_type& elem : *outer)
1838
559k
            if (!inner->has_element(elem)) return false;
1839
40
        return true;
1840
167
    }
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
9.85M
    size_t hash(const K& key) const {
1853
9.85M
        return HashElement{hash_ref()}(key);
1854
9.85M
    }
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
11.4M
        size_t operator()(const K& key, Args&&...) const {
1896
#if PHMAP_DISABLE_MIX
1897
            return h(key);
1898
#else
1899
11.4M
            return phmap_mix<sizeof(size_t)>()(h(key));
1900
11.4M
#endif
1901
11.4M
        }
unsigned long phmap::priv::raw_hash_set<phmap::priv::FlatHashMapPolicy<unsigned int, int>, phmap::Hash<unsigned int>, phmap::EqualTo<unsigned int>, std::__1::allocator<std::__1::pair<unsigned int const, int> > >::HashElement::operator()<unsigned int, std::__1::piecewise_construct_t const&, std::__1::tuple<unsigned int const&>, std::__1::tuple<int const&> >(unsigned int const&, std::__1::piecewise_construct_t const&, std::__1::tuple<unsigned int const&>&&, std::__1::tuple<int const&>&&) const
Line
Count
Source
1895
1.57M
        size_t operator()(const K& key, Args&&...) const {
1896
#if PHMAP_DISABLE_MIX
1897
            return h(key);
1898
#else
1899
1.57M
            return phmap_mix<sizeof(size_t)>()(h(key));
1900
1.57M
#endif
1901
1.57M
        }
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
9.85M
        size_t operator()(const K& key, Args&&...) const {
1896
#if PHMAP_DISABLE_MIX
1897
            return h(key);
1898
#else
1899
9.85M
            return phmap_mix<sizeof(size_t)>()(h(key));
1900
9.85M
#endif
1901
9.85M
        }
1902
        const hasher& h;
1903
    };
1904
1905
    template <class K1>
1906
    struct EqualElement 
1907
    {
1908
        template <class K2, class... Args>
1909
10.9M
        bool operator()(const K2& lhs, Args&&...) const {
1910
10.9M
            return eq(lhs, rhs);
1911
10.9M
        }
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
9.85M
    {
1920
9.85M
        size_t offset = _find_key(key, hashval);
1921
9.85M
        if (offset == (size_t)-1) {
1922
576k
            offset = prepare_insert(hashval);
1923
576k
            emplace_at(offset, std::forward<Args>(args)...);
1924
576k
            this->set_ctrl(offset, H2(hashval));
1925
576k
            return {iterator_at(offset), true};
1926
576k
        }
1927
9.27M
        return {iterator_at(offset), false};
1928
9.85M
    }
1929
1930
    struct EmplaceDecomposable 
1931
    {
1932
        template <class K, class... Args>
1933
9.85M
        std::pair<iterator, bool> operator()(const K& key, Args&&... args) const {
1934
9.85M
            return s.emplace_decomposable(key, s.hash(key), std::forward<Args>(args)...);
1935
9.85M
        }
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.25k
    void initialize_slots(size_t new_capacity) {
2014
3.25k
        assert(new_capacity);
2015
3.25k
        if (std::is_same<SlotAlloc, std::allocator<slot_type>>::value && 
2016
3.25k
            slots_ == nullptr) {
2017
689
            infoz_ = Sample();
2018
689
        }
2019
2020
3.25k
        auto layout = MakeLayout(new_capacity);
2021
3.25k
        char* mem = static_cast<char*>(
2022
3.25k
            Allocate<Layout::Alignment()>(&alloc_ref(), layout.AllocSize()));
2023
3.25k
        ctrl_ = reinterpret_cast<ctrl_t*>(layout.template Pointer<0>(mem));
2024
3.25k
        slots_ = layout.template Pointer<1>(mem);
2025
3.25k
        reset_ctrl(new_capacity);
2026
3.25k
        reset_growth_left(new_capacity);
2027
3.25k
        infoz_.RecordStorageChanged(size_, new_capacity);
2028
3.25k
    }
2029
2030
2.33k
    void destroy_slots() {
2031
2.33k
        if (!capacity_)
2032
1.64k
            return;
2033
        
2034
689
        PHMAP_IF_CONSTEXPR((!std::is_trivially_destructible<typename PolicyTraits::value_type>::value ||
2035
689
                            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
689
        auto layout = MakeLayout(capacity_);
2045
        // Unpoison before returning the memory to the allocator.
2046
689
        SanitizerUnpoisonMemoryRegion(slots_, sizeof(slot_type) * capacity_);
2047
689
        Deallocate<Layout::Alignment()>(&alloc_ref(), ctrl_, layout.AllocSize());
2048
689
        ctrl_ = EmptyGroup<std_alloc_t>();
2049
689
        slots_ = nullptr;
2050
689
        size_ = 0;
2051
689
        capacity_ = 0;
2052
689
        growth_left() = 0;
2053
689
    }
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.75k
    void destroy_slots() {
2031
1.75k
        if (!capacity_)
2032
1.06k
            return;
2033
        
2034
689
        PHMAP_IF_CONSTEXPR((!std::is_trivially_destructible<typename PolicyTraits::value_type>::value ||
2035
689
                            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
689
        auto layout = MakeLayout(capacity_);
2045
        // Unpoison before returning the memory to the allocator.
2046
689
        SanitizerUnpoisonMemoryRegion(slots_, sizeof(slot_type) * capacity_);
2047
689
        Deallocate<Layout::Alignment()>(&alloc_ref(), ctrl_, layout.AllocSize());
2048
689
        ctrl_ = EmptyGroup<std_alloc_t>();
2049
689
        slots_ = nullptr;
2050
689
        size_ = 0;
2051
689
        capacity_ = 0;
2052
689
        growth_left() = 0;
2053
689
    }
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
584
    void destroy_slots() {
2031
584
        if (!capacity_)
2032
584
            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.12k
    void resize(size_t new_capacity) {
2056
3.12k
        assert(IsValidCapacity(new_capacity));
2057
3.12k
        auto* old_ctrl = ctrl_;
2058
3.12k
        auto* old_slots = slots_;
2059
3.12k
        const size_t old_capacity = capacity_;
2060
3.12k
        initialize_slots(new_capacity);
2061
3.12k
        capacity_ = new_capacity;
2062
2063
1.15M
        for (size_t i = 0; i != old_capacity; ++i) {
2064
1.15M
            if (IsFull(old_ctrl[i])) {
2065
1.01M
                size_t hashval = PolicyTraits::apply(HashElement{hash_ref()},
2066
1.01M
                                                     PolicyTraits::element(old_slots + i));
2067
1.01M
                auto target = find_first_non_full(hashval);
2068
1.01M
                size_t new_i = target.offset;
2069
1.01M
                set_ctrl(new_i, H2(hashval));
2070
1.01M
                PolicyTraits::transfer(&alloc_ref(), slots_ + new_i, old_slots + i);
2071
1.01M
            }
2072
1.15M
        }
2073
3.12k
        if (old_capacity) {
2074
2.56k
            SanitizerUnpoisonMemoryRegion(old_slots,
2075
2.56k
                                          sizeof(slot_type) * old_capacity);
2076
2.56k
            auto layout = MakeLayout(old_capacity);
2077
2.56k
            Deallocate<Layout::Alignment()>(&alloc_ref(), old_ctrl,
2078
2.56k
                                            layout.AllocSize());
2079
2.56k
        }
2080
3.12k
    }
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.12k
    void rehash_and_grow_if_necessary() {
2146
3.12k
        if (capacity_ == 0) {
2147
553
            resize(1);
2148
2.56k
        } else if (size() <= CapacityToGrowth(capacity()) / 2) {
2149
            // Squash DELETED without growing if there is enough capacity.
2150
0
            drop_deletes_without_resize();
2151
2.56k
        } else {
2152
            // Otherwise grow the container.
2153
2.56k
            resize(capacity_ * 2 + 1);
2154
2.56k
        }
2155
3.12k
    }
2156
2157
559k
    bool has_element(const value_type& PHMAP_RESTRICT elem, size_t hashval) const {
2158
559k
        PHMAP_IF_CONSTEXPR (!std_alloc_t::value) {
2159
            // ctrl_ could be nullptr
2160
            if (!ctrl_)
2161
                return false;
2162
        }
2163
559k
        auto seq = probe(hashval);
2164
563k
        while (true) {
2165
563k
            Group g{ctrl_ + seq.offset()};
2166
563k
            for (uint32_t i : g.Match((h2_t)H2(hashval))) {
2167
562k
                if (PHMAP_PREDICT_TRUE(PolicyTraits::element(slots_ + seq.offset((size_t)i)) ==
2168
562k
                                      elem))
2169
559k
                    return true;
2170
562k
            }
2171
4.48k
            if (PHMAP_PREDICT_TRUE(g.MatchEmpty())) return false;
2172
4.35k
            seq.next();
2173
4.35k
            assert(seq.getindex() < capacity_ && "full table!");
2174
4.35k
        }
2175
0
        return false;
2176
559k
    }
2177
2178
559k
    bool has_element(const value_type& elem) const {
2179
559k
        size_t hashval = PolicyTraits::apply(HashElement{hash_ref()}, elem);
2180
559k
        return has_element(elem, hashval);
2181
559k
    }
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
1.59M
    FindInfo find_first_non_full(size_t hashval) {
2198
1.59M
        auto seq = probe(hashval);
2199
1.68M
        while (true) {
2200
1.68M
            Group g{ctrl_ + seq.offset()};
2201
1.68M
            auto mask = g.MatchEmptyOrDeleted();
2202
1.68M
            if (mask) {
2203
1.59M
                return {seq.offset((size_t)mask.LowestBitSet()), seq.getindex()};
2204
1.59M
            }
2205
1.68M
            assert(seq.getindex() < capacity_ && "full table!");
2206
89.0k
            seq.next();
2207
89.0k
        }
2208
1.59M
    }
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
9.85M
    size_t _find_key(const K& PHMAP_RESTRICT key, size_t hashval) {
2225
9.85M
        PHMAP_IF_CONSTEXPR (!std_alloc_t::value) {
2226
            // ctrl_ could be nullptr
2227
            if (!ctrl_)
2228
                return (size_t)-1;
2229
        }
2230
9.85M
        auto seq = probe(hashval);
2231
10.9M
        while (true) {
2232
10.9M
            Group g{ctrl_ + seq.offset()};
2233
10.9M
            for (uint32_t i : g.Match((h2_t)H2(hashval))) {
2234
10.9M
                if (PHMAP_PREDICT_TRUE(PolicyTraits::apply(
2235
10.9M
                                          EqualElement<K>{key, eq_ref()},
2236
10.9M
                                          PolicyTraits::element(slots_ + seq.offset((size_t)i)))))
2237
9.27M
                    return seq.offset((size_t)i);
2238
10.9M
            }
2239
1.70M
            if (PHMAP_PREDICT_TRUE(g.MatchEmpty())) break;
2240
1.12M
            seq.next();
2241
1.12M
        }
2242
576k
        return (size_t)-1;
2243
9.85M
    }
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
576k
    size_t prepare_insert(size_t hashval) PHMAP_ATTRIBUTE_NOINLINE {
2254
576k
        PHMAP_IF_CONSTEXPR (!std_alloc_t::value) {
2255
            // ctrl_ could be nullptr
2256
            if (!ctrl_)
2257
                rehash_and_grow_if_necessary();
2258
        }
2259
576k
        FindInfo target = find_first_non_full(hashval);
2260
576k
        if (PHMAP_PREDICT_FALSE(growth_left() == 0 &&
2261
576k
                               !IsDeleted(ctrl_[target.offset]))) {
2262
3.12k
            rehash_and_grow_if_necessary();
2263
3.12k
            target = find_first_non_full(hashval);
2264
3.12k
        }
2265
576k
        ++size_;
2266
576k
        growth_left() -= IsEmpty(ctrl_[target.offset]);
2267
        // set_ctrl(target.offset, H2(hashval));
2268
576k
        infoz_.RecordInsert(hashval, target.probe_length);
2269
576k
        return target.offset;
2270
576k
    }
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
576k
    void emplace_at(size_t i, Args&&... args) {
2282
576k
        PolicyTraits::construct(&alloc_ref(), slots_ + i,
2283
576k
                                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
576k
    }
2292
2293
9.85M
    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
9.85M
    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
1.58M
    void set_ctrl(size_t i, ctrl_t h) {
2300
1.58M
        assert(i < capacity_);
2301
2302
1.58M
        if (IsFull(h)) {
2303
1.58M
            SanitizerUnpoisonObject(slots_ + i);
2304
1.58M
        } else {
2305
0
            SanitizerPoisonObject(slots_ + i);
2306
0
        }
2307
2308
1.58M
        ctrl_[i] = h;
2309
1.58M
        ctrl_[((i - Group::kWidth) & capacity_) + 1 +
2310
1.58M
              ((Group::kWidth - 1) & capacity_)] = h;
2311
1.58M
    }
2312
2313
private:
2314
    friend struct RawHashSetTestOnlyAccess;
2315
2316
12.0M
    probe_seq<Group::kWidth> probe(size_t hashval) const {
2317
12.0M
        return probe_seq<Group::kWidth>(H1(hashval, ctrl_), capacity_);
2318
12.0M
    }
2319
2320
    // Reset all ctrl bytes back to kEmpty, except the sentinel.
2321
3.25k
    void reset_ctrl(size_t new_capacity) {
2322
3.25k
        std::memset(ctrl_, kEmpty, new_capacity + Group::kWidth);
2323
3.25k
        ctrl_[new_capacity] = kSentinel;
2324
3.25k
        SanitizerPoisonMemoryRegion(slots_, sizeof(slot_type) * new_capacity);
2325
3.25k
    }
2326
2327
3.25k
    void reset_growth_left(size_t new_capacity) {
2328
3.25k
        growth_left() = CapacityToGrowth(new_capacity) - size_;
2329
3.25k
    }
2330
2331
1.15M
    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.15M
    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
553
    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.01M
    hasher& hash_ref() { return std::get<1>(settings_); }
2362
10.4M
    const hasher& hash_ref() const { return std::get<1>(settings_); }
2363
10.9M
    key_equal& eq_ref() { return std::get<2>(settings_); }
2364
    const key_equal& eq_ref() const { return std::get<2>(settings_); }
2365
1.59M
    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
1.59M
    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.75k
    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.16k
    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
584
    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
        size_t target = GrowthToLowerboundCapacity(n);
3597
        size_t normalized = num_tables * NormalizeCapacity(n / num_tables);
3598
        rehash(normalized > target ? normalized : target); 
3599
    }
3600
3601
    // Extension API: support for heterogeneous keys.
3602
    //
3603
    //   std::unordered_set<std::string> s;
3604
    //   // Turns "abc" into std::string.
3605
    //   s.count("abc");
3606
    //
3607
    //   ch_set<std::string> s;
3608
    //   // Uses "abc" directly without copying it into std::string.
3609
    //   s.count("abc");
3610
    // --------------------------------------------------------------------
3611
    template <class K = key_type>
3612
    size_t count(const key_arg<K>& key) const {
3613
        return find(key) == end() ? 0 : 1;
3614
    }
3615
3616
    // Issues CPU prefetch instructions for the memory needed to find or insert
3617
    // a key.  Like all lookup functions, this support heterogeneous keys.
3618
    //
3619
    // NOTE: This is a very low level operation and should not be used without
3620
    // specific benchmarks indicating its importance.
3621
    // --------------------------------------------------------------------
3622
    void prefetch_hash(size_t hashval) const {
3623
        const Inner& inner = sets_[subidx(hashval)];
3624
        const auto&  set   = inner.set_;
3625
        SharedLock m(const_cast<Inner&>(inner));
3626
        set.prefetch_hash(hashval);
3627
    }
3628
3629
    template <class K = key_type>
3630
    void prefetch(const key_arg<K>& key) const {
3631
        prefetch_hash(this->hash(key));
3632
    }
3633
3634
    // The API of find() has two extensions.
3635
    //
3636
    // 1. The hash can be passed by the user. It must be equal to the hash of the
3637
    // key.
3638
    //
3639
    // 2. The type of the key argument doesn't have to be key_type. This is so
3640
    // called heterogeneous key support.
3641
    // --------------------------------------------------------------------
3642
    template <class K = key_type>
3643
    iterator find(const key_arg<K>& key, size_t hashval) {
3644
        SharedLock m;
3645
        return find(key, hashval, m);
3646
    }
3647
3648
    template <class K = key_type>
3649
    iterator find(const key_arg<K>& key) {
3650
        return find(key, this->hash(key));
3651
    }
3652
3653
    template <class K = key_type>
3654
    const_iterator find(const key_arg<K>& key, size_t hashval) const {
3655
        return const_cast<parallel_hash_set*>(this)->find(key, hashval);
3656
    }
3657
3658
    template <class K = key_type>
3659
    const_iterator find(const key_arg<K>& key) const {
3660
        return find(key, this->hash(key));
3661
    }
3662
3663
    template <class K = key_type>
3664
    bool contains(const key_arg<K>& key) const {
3665
        return find(key) != end();
3666
    }
3667
3668
    template <class K = key_type>
3669
    bool contains(const key_arg<K>& key, size_t hashval) const {
3670
        return find(key, hashval) != end();
3671
    }
3672
3673
    template <class K = key_type>
3674
    std::pair<iterator, iterator> equal_range(const key_arg<K>& key) {
3675
        auto it = find(key);
3676
        if (it != end()) return {it, std::next(it)};
3677
        return {it, it};
3678
    }
3679
3680
    template <class K = key_type>
3681
    std::pair<const_iterator, const_iterator> equal_range(
3682
        const key_arg<K>& key) const {
3683
        auto it = find(key);
3684
        if (it != end()) return {it, std::next(it)};
3685
        return {it, it};
3686
    }
3687
3688
    size_t bucket_count() const {
3689
        size_t sz = 0;
3690
        for (const auto& inner : sets_)
3691
        {
3692
            SharedLock m(const_cast<Inner&>(inner));
3693
            sz += inner.set_.bucket_count();
3694
        }
3695
        return sz; 
3696
    }
3697
3698
    float load_factor() const {
3699
        size_t _capacity = bucket_count();
3700
        return _capacity ? static_cast<float>(static_cast<double>(size()) / _capacity) : 0;
3701
    }
3702
3703
    float max_load_factor() const { return 1.0f; }
3704
    void max_load_factor(float) {
3705
        // Does nothing.
3706
    }
3707
3708
    hasher hash_function() const { return hash_ref(); }  // warning: doesn't match internal hash - use hash() member function
3709
    key_equal key_eq() const { return eq_ref(); }
3710
    allocator_type get_allocator() const { return alloc_ref(); }
3711
3712
    friend bool operator==(const parallel_hash_set& a, const parallel_hash_set& b) {
3713
        return std::equal(a.sets_.begin(), a.sets_.end(), b.sets_.begin());
3714
    }
3715
3716
    friend bool operator!=(const parallel_hash_set& a, const parallel_hash_set& b) {
3717
        return !(a == b);
3718
    }
3719
3720
    template<class Mtx2_>
3721
    friend void swap(parallel_hash_set& a,
3722
                     parallel_hash_set<N, RefSet, Mtx2_, Policy, Hash, Eq, Alloc>& b)
3723
        noexcept(noexcept(a.swap(b)))
3724
    {
3725
        a.swap(b);
3726
    }
3727
3728
    template <class K>
3729
    size_t hash(const K& key) const {
3730
        return HashElement{hash_ref()}(key);
3731
    }
3732
3733
#if !defined(PHMAP_NON_DETERMINISTIC)
3734
    template<typename OutputArchive>
3735
    bool phmap_dump(OutputArchive& ar) const;
3736
3737
    template<typename InputArchive>
3738
    bool phmap_load(InputArchive& ar);
3739
#endif
3740
3741
private:
3742
    template <class Container, typename Enabler>
3743
    friend struct phmap::priv::hashtable_debug_internal::HashtableDebugAccess;
3744
3745
    struct FindElement 
3746
    {
3747
        template <class K, class... Args>
3748
        const_iterator operator()(const K& key, Args&&...) const {
3749
            return s.find(key);
3750
        }
3751
        const parallel_hash_set& s;
3752
    };
3753
3754
    struct HashElement 
3755
    {
3756
        template <class K, class... Args>
3757
        size_t operator()(const K& key, Args&&...) const {
3758
#if PHMAP_DISABLE_MIX
3759
            return h(key);
3760
#else
3761
            return phmap_mix<sizeof(size_t)>()(h(key));
3762
#endif
3763
        }
3764
        const hasher& h;
3765
    };
3766
3767
    template <class K1>
3768
    struct EqualElement 
3769
    {
3770
        template <class K2, class... Args>
3771
        bool operator()(const K2& lhs, Args&&...) const {
3772
            return eq(lhs, rhs);
3773
        }
3774
        const K1& rhs;
3775
        const key_equal& eq;
3776
    };
3777
3778
    // "erases" the object from the container, except that it doesn't actually
3779
    // destroy the object. It only updates all the metadata of the class.
3780
    // This can be used in conjunction with Policy::transfer to move the object to
3781
    // another place.
3782
    // --------------------------------------------------------------------
3783
    void erase_meta_only(const_iterator cit) {
3784
        auto &it = cit.iter_;
3785
        assert(it.set_ != nullptr);
3786
        it.set_.erase_meta_only(const_iterator(it.it_));
3787
    }
3788
3789
    void drop_deletes_without_resize() PHMAP_ATTRIBUTE_NOINLINE {
3790
        for (auto& inner : sets_)
3791
        {
3792
            UniqueLock m(inner);
3793
            inner.set_.drop_deletes_without_resize();
3794
        }
3795
    }
3796
3797
    bool has_element(const value_type& elem) const {
3798
        size_t hashval = PolicyTraits::apply(HashElement{hash_ref()}, elem);
3799
        Inner& inner   = sets_[subidx(hashval)];
3800
        auto&  set     = inner.set_;
3801
        SharedLock m(const_cast<Inner&>(inner));
3802
        return set.has_element(elem, hashval);
3803
    }
3804
3805
    // TODO(alkis): Optimize this assuming *this and that don't overlap.
3806
    // --------------------------------------------------------------------
3807
    template<class Mtx2_>
3808
    parallel_hash_set& move_assign(parallel_hash_set<N, RefSet, Mtx2_, Policy, Hash, Eq, Alloc>&& that, std::true_type) {
3809
        parallel_hash_set<N, RefSet, Mtx2_, Policy, Hash, Eq, Alloc> tmp(std::move(that));
3810
        swap(tmp);
3811
        return *this;
3812
    }
3813
3814
    template<class Mtx2_>
3815
    parallel_hash_set& move_assign(parallel_hash_set<N, RefSet, Mtx2_, Policy, Hash, Eq, Alloc>&& that, std::false_type) {
3816
        parallel_hash_set<N, RefSet, Mtx2_, Policy, Hash, Eq, Alloc> tmp(std::move(that), alloc_ref());
3817
        swap(tmp);
3818
        return *this;
3819
    }
3820
3821
protected:
3822
    template <class K = key_type, class L = SharedLock>
3823
    pointer find_ptr(const key_arg<K>& key, size_t hashval, L& mutexlock)
3824
    {
3825
        Inner& inner = sets_[subidx(hashval)];
3826
        auto& set = inner.set_;
3827
        mutexlock = std::move(L(inner));
3828
        return set.find_ptr(key, hashval);
3829
    }
3830
3831
    template <class K = key_type, class L = SharedLock>
3832
    iterator find(const key_arg<K>& key, size_t hashval, L& mutexlock) {
3833
        Inner& inner = sets_[subidx(hashval)];
3834
        auto& set = inner.set_;
3835
        mutexlock = std::move(L(inner));
3836
        return make_iterator(&inner, set.find(key, hashval));
3837
    }
3838
3839
    template <class K>
3840
    std::tuple<Inner*, size_t, bool> 
3841
    find_or_prepare_insert_with_hash(size_t hashval, const K& key, UniqueLock &mutexlock) {
3842
        Inner& inner = sets_[subidx(hashval)];
3843
        auto&  set   = inner.set_;
3844
        mutexlock    = std::move(UniqueLock(inner));
3845
        size_t offset = set._find_key(key, hashval);
3846
        if (offset == (size_t)-1) {
3847
            offset = set.prepare_insert(hashval);
3848
            return std::make_tuple(&inner, offset, true);
3849
        }
3850
        return std::make_tuple(&inner, offset, false);
3851
    }
3852
3853
    template <class K>
3854
    std::tuple<Inner*, size_t, bool> 
3855
    find_or_prepare_insert(const K& key, UniqueLock &mutexlock) {
3856
        return find_or_prepare_insert_with_hash<K>(this->hash(key), key, mutexlock);
3857
    }
3858
3859
    iterator iterator_at(Inner *inner, 
3860
                         const EmbeddedIterator& it) { 
3861
        return {inner, &sets_[0] + num_tables, it}; 
3862
    }
3863
    const_iterator iterator_at(Inner *inner, 
3864
                               const EmbeddedIterator& it) const { 
3865
        return {inner, &sets_[0] + num_tables, it}; 
3866
    }
3867
3868
    static size_t subidx(size_t hashval) {
3869
        return ((hashval >> 8) ^ (hashval >> 16) ^ (hashval >> 24)) & mask;
3870
    }
3871
3872
    static size_t subcnt() {
3873
        return num_tables;
3874
    }
3875
3876
private:
3877
    friend struct RawHashSetTestOnlyAccess;
3878
3879
    size_t growth_left() { 
3880
        size_t sz = 0;
3881
        for (const auto& set : sets_)
3882
            sz += set.growth_left();
3883
        return sz; 
3884
    }
3885
3886
    hasher&       hash_ref()        { return sets_[0].set_.hash_ref(); }
3887
    const hasher& hash_ref() const  { return sets_[0].set_.hash_ref(); }
3888
    key_equal&       eq_ref()       { return sets_[0].set_.eq_ref(); }
3889
    const key_equal& eq_ref() const { return sets_[0].set_.eq_ref(); }
3890
    allocator_type&  alloc_ref()    { return sets_[0].set_.alloc_ref(); }
3891
    const allocator_type& alloc_ref() const { 
3892
        return sets_[0].set_.alloc_ref();
3893
    }
3894
3895
protected:       // protected in case users want to derive fromm this
3896
    std::array<Inner, num_tables> sets_;
3897
};
3898
3899
// --------------------------------------------------------------------------
3900
// --------------------------------------------------------------------------
3901
template <size_t N,
3902
          template <class, class, class, class> class RefSet,
3903
          class Mtx_,
3904
          class Policy, class Hash, class Eq, class Alloc>
3905
class parallel_hash_map : public parallel_hash_set<N, RefSet, Mtx_, Policy, Hash, Eq, Alloc> 
3906
{
3907
    // P is Policy. It's passed as a template argument to support maps that have
3908
    // incomplete types as values, as in unordered_map<K, IncompleteType>.
3909
    // MappedReference<> may be a non-reference type.
3910
    template <class P>
3911
    using MappedReference = decltype(P::value(
3912
            std::addressof(std::declval<typename parallel_hash_map::reference>())));
3913
3914
    // MappedConstReference<> may be a non-reference type.
3915
    template <class P>
3916
    using MappedConstReference = decltype(P::value(
3917
            std::addressof(std::declval<typename parallel_hash_map::const_reference>())));
3918
3919
    using KeyArgImpl =
3920
        KeyArg<IsTransparent<Eq>::value && IsTransparent<Hash>::value>;
3921
3922
    using Base = typename parallel_hash_map::parallel_hash_set;
3923
    using Lockable      = phmap::LockableImpl<Mtx_>;
3924
    using UniqueLock    = typename Lockable::UniqueLock;
3925
    using SharedLock    = typename Lockable::SharedLock;
3926
    using ReadWriteLock = typename Lockable::ReadWriteLock;
3927
3928
public:
3929
    using key_type    = typename Policy::key_type;
3930
    using mapped_type = typename Policy::mapped_type;
3931
    using value_type  = typename Base::value_type;
3932
    template <class K>
3933
    using key_arg = typename KeyArgImpl::template type<K, key_type>;
3934
3935
    static_assert(!std::is_reference<key_type>::value, "");
3936
    // TODO(alkis): remove this assertion and verify that reference mapped_type is
3937
    // supported.
3938
    static_assert(!std::is_reference<mapped_type>::value, "");
3939
3940
    using iterator = typename parallel_hash_map::parallel_hash_set::iterator;
3941
    using const_iterator = typename parallel_hash_map::parallel_hash_set::const_iterator;
3942
3943
    parallel_hash_map() {}
3944
3945
#ifdef __INTEL_COMPILER
3946
    using Base::parallel_hash_set;
3947
#else
3948
    using parallel_hash_map::parallel_hash_set::parallel_hash_set;
3949
#endif
3950
3951
    // The last two template parameters ensure that both arguments are rvalues
3952
    // (lvalue arguments are handled by the overloads below). This is necessary
3953
    // for supporting bitfield arguments.
3954
    //
3955
    //   union { int n : 1; };
3956
    //   flat_hash_map<int, int> m;
3957
    //   m.insert_or_assign(n, n);
3958
    template <class K = key_type, class V = mapped_type, K* = nullptr,
3959
              V* = nullptr>
3960
    std::pair<iterator, bool> insert_or_assign(key_arg<K>&& k, V&& v) {
3961
        return insert_or_assign_impl(std::forward<K>(k), std::forward<V>(v));
3962
    }
3963
3964
    template <class K = key_type, class V = mapped_type, K* = nullptr>
3965
    std::pair<iterator, bool> insert_or_assign(key_arg<K>&& k, const V& v) {
3966
        return insert_or_assign_impl(std::forward<K>(k), v);
3967
    }
3968
3969
    template <class K = key_type, class V = mapped_type, V* = nullptr>
3970
    std::pair<iterator, bool> insert_or_assign(const key_arg<K>& k, V&& v) {
3971
        return insert_or_assign_impl(k, std::forward<V>(v));
3972
    }
3973
3974
    template <class K = key_type, class V = mapped_type>
3975
    std::pair<iterator, bool> insert_or_assign(const key_arg<K>& k, const V& v) {
3976
        return insert_or_assign_impl(k, v);
3977
    }
3978
3979
    template <class K = key_type, class V = mapped_type, K* = nullptr,
3980
              V* = nullptr>
3981
    iterator insert_or_assign(const_iterator, key_arg<K>&& k, V&& v) {
3982
        return insert_or_assign(std::forward<K>(k), std::forward<V>(v)).first;
3983
    }
3984
3985
    template <class K = key_type, class V = mapped_type, K* = nullptr>
3986
    iterator insert_or_assign(const_iterator, key_arg<K>&& k, const V& v) {
3987
        return insert_or_assign(std::forward<K>(k), v).first;
3988
    }
3989
3990
    template <class K = key_type, class V = mapped_type, V* = nullptr>
3991
    iterator insert_or_assign(const_iterator, const key_arg<K>& k, V&& v) {
3992
        return insert_or_assign(k, std::forward<V>(v)).first;
3993
    }
3994
3995
    template <class K = key_type, class V = mapped_type>
3996
    iterator insert_or_assign(const_iterator, const key_arg<K>& k, const V& v) {
3997
        return insert_or_assign(k, v).first;
3998
    }
3999
4000
    template <class K = key_type, class... Args,
4001
              typename std::enable_if<
4002
                  !std::is_convertible<K, const_iterator>::value, int>::type = 0,
4003
              K* = nullptr>
4004
    std::pair<iterator, bool> try_emplace(key_arg<K>&& k, Args&&... args) {
4005
        return try_emplace_impl(std::forward<K>(k), std::forward<Args>(args)...);
4006
    }
4007
4008
    template <class K = key_type, class... Args,
4009
              typename std::enable_if<
4010
                  !std::is_convertible<K, const_iterator>::value, int>::type = 0>
4011
    std::pair<iterator, bool> try_emplace(const key_arg<K>& k, Args&&... args) {
4012
        return try_emplace_impl(k, std::forward<Args>(args)...);
4013
    }
4014
4015
    template <class K = key_type, class... Args, K* = nullptr>
4016
    iterator try_emplace(const_iterator, key_arg<K>&& k, Args&&... args) {
4017
        return try_emplace(std::forward<K>(k), std::forward<Args>(args)...).first;
4018
    }
4019
4020
    template <class K = key_type, class... Args>
4021
    iterator try_emplace(const_iterator, const key_arg<K>& k, Args&&... args) {
4022
        return try_emplace(k, std::forward<Args>(args)...).first;
4023
    }
4024
4025
    template <class K = key_type, class P = Policy>
4026
    MappedReference<P> at(const key_arg<K>& key) {
4027
        auto it = this->find(key);
4028
        if (it == this->end()) 
4029
            phmap::base_internal::ThrowStdOutOfRange("phmap at(): lookup non-existent key");
4030
        return Policy::value(&*it);
4031
    }
4032
4033
    template <class K = key_type, class P = Policy>
4034
    MappedConstReference<P> at(const key_arg<K>& key) const {
4035
        auto it = this->find(key);
4036
        if (it == this->end()) 
4037
            phmap::base_internal::ThrowStdOutOfRange("phmap at(): lookup non-existent key");
4038
        return Policy::value(&*it);
4039
    }
4040
4041
    // ----------- phmap extensions --------------------------
4042
4043
    template <class K = key_type, class... Args,
4044
              typename std::enable_if<
4045
                  !std::is_convertible<K, const_iterator>::value, int>::type = 0,
4046
              K* = nullptr>
4047
    std::pair<iterator, bool> try_emplace_with_hash(size_t hashval, key_arg<K>&& k, Args&&... args) {
4048
        return try_emplace_impl_with_hash(hashval, std::forward<K>(k), std::forward<Args>(args)...);
4049
    }
4050
4051
    template <class K = key_type, class... Args,
4052
              typename std::enable_if<
4053
                  !std::is_convertible<K, const_iterator>::value, int>::type = 0>
4054
    std::pair<iterator, bool> try_emplace_with_hash(size_t hashval, const key_arg<K>& k, Args&&... args) {
4055
        return try_emplace_impl_with_hash(hashval, k, std::forward<Args>(args)...);
4056
    }
4057
4058
    template <class K = key_type, class... Args, K* = nullptr>
4059
    iterator try_emplace_with_hash(size_t hashval, const_iterator, key_arg<K>&& k, Args&&... args) {
4060
        return try_emplace_with_hash(hashval, std::forward<K>(k), std::forward<Args>(args)...).first;
4061
    }
4062
4063
    template <class K = key_type, class... Args>
4064
    iterator try_emplace_with_hash(size_t hashval, const_iterator, const key_arg<K>& k, Args&&... args) {
4065
        return try_emplace_with_hash(hashval, k, std::forward<Args>(args)...).first;
4066
    }
4067
4068
    // if map does not contains key, it is inserted and the mapped value is value-constructed 
4069
    // with the provided arguments (if any), as with try_emplace. 
4070
    // if map already  contains key, then the lambda is called with the mapped value (under 
4071
    // write lock protection) and can update the mapped value.
4072
    // returns true if key was not already present, false otherwise.
4073
    // ---------------------------------------------------------------------------------------
4074
    template <class K = key_type, class F, class... Args>
4075
    bool try_emplace_l(K&& k, F&& f, Args&&... args) {
4076
        size_t hashval = this->hash(k);
4077
        UniqueLock m;
4078
        auto res = this->find_or_prepare_insert_with_hash(hashval, k, m);
4079
        typename Base::Inner *inner = std::get<0>(res);
4080
        if (std::get<2>(res)) {
4081
            inner->set_.emplace_at(std::get<1>(res), std::piecewise_construct,
4082
                                   std::forward_as_tuple(std::forward<K>(k)),
4083
                                   std::forward_as_tuple(std::forward<Args>(args)...));
4084
            inner->set_.set_ctrl(std::get<1>(res), H2(hashval));
4085
        } else {
4086
            auto it = this->iterator_at(inner, inner->set_.iterator_at(std::get<1>(res)));
4087
            // call lambda. in case of the set, non "key" part of value_type can be changed
4088
            std::forward<F>(f)(const_cast<value_type &>(*it));
4089
        }
4090
        return std::get<2>(res);
4091
    }
4092
4093
    // returns {pointer, bool} instead of {iterator, bool} per try_emplace.
4094
    // useful for node-based containers, since the pointer is not invalidated by concurrent insert etc.
4095
    template <class K = key_type, class... Args>
4096
    std::pair<typename parallel_hash_map::parallel_hash_set::pointer, bool> try_emplace_p(K&& k, Args&&... args) {
4097
        size_t hashval = this->hash(k);
4098
        UniqueLock m;
4099
        auto res = this->find_or_prepare_insert_with_hash(hashval, k, m);
4100
        typename Base::Inner *inner = std::get<0>(res);
4101
        if (std::get<2>(res)) {
4102
            inner->set_.emplace_at(std::get<1>(res), std::piecewise_construct,
4103
                                   std::forward_as_tuple(std::forward<K>(k)),
4104
                                   std::forward_as_tuple(std::forward<Args>(args)...));
4105
            inner->set_.set_ctrl(std::get<1>(res), H2(hashval));
4106
        }
4107
        auto it = this->iterator_at(inner, inner->set_.iterator_at(std::get<1>(res)));
4108
        return {&*it, std::get<2>(res)};
4109
    }
4110
4111
    // ----------- end of phmap extensions --------------------------
4112
4113
    template <class K = key_type, class P = Policy, K* = nullptr>
4114
    MappedReference<P> operator[](key_arg<K>&& key) {
4115
        return Policy::value(&*try_emplace(std::forward<K>(key)).first);
4116
    }
4117
4118
    template <class K = key_type, class P = Policy>
4119
    MappedReference<P> operator[](const key_arg<K>& key) {
4120
        return Policy::value(&*try_emplace(key).first);
4121
    }
4122
4123
private:
4124
4125
    template <class K, class V>
4126
    std::pair<iterator, bool> insert_or_assign_impl(K&& k, V&& v) {
4127
        size_t hashval = this->hash(k);
4128
        UniqueLock m;
4129
        auto res = this->find_or_prepare_insert_with_hash(hashval, k, m);
4130
        typename Base::Inner *inner = std::get<0>(res);
4131
        if (std::get<2>(res)) {
4132
            inner->set_.emplace_at(std::get<1>(res), std::forward<K>(k), std::forward<V>(v));
4133
            inner->set_.set_ctrl(std::get<1>(res), H2(hashval));
4134
        } else
4135
            Policy::value(&*inner->set_.iterator_at(std::get<1>(res))) = std::forward<V>(v);
4136
        return {this->iterator_at(inner, inner->set_.iterator_at(std::get<1>(res))), 
4137
                std::get<2>(res)};
4138
    }
4139
4140
    template <class K = key_type, class... Args>
4141
    std::pair<iterator, bool> try_emplace_impl(K&& k, Args&&... args) {
4142
        return try_emplace_impl_with_hash(this->hash(k), std::forward<K>(k),
4143
                                          std::forward<Args>(args)...);
4144
    }
4145
4146
    template <class K = key_type, class... Args>
4147
    std::pair<iterator, bool> try_emplace_impl_with_hash(size_t hashval, K&& k, Args&&... args) {
4148
        UniqueLock m;
4149
        auto res = this->find_or_prepare_insert_with_hash(hashval, k, m);
4150
        typename Base::Inner *inner = std::get<0>(res);
4151
        if (std::get<2>(res)) {
4152
            inner->set_.emplace_at(std::get<1>(res), std::piecewise_construct,
4153
                                   std::forward_as_tuple(std::forward<K>(k)),
4154
                                   std::forward_as_tuple(std::forward<Args>(args)...));
4155
            inner->set_.set_ctrl(std::get<1>(res), H2(hashval));
4156
        }
4157
        return {this->iterator_at(inner, inner->set_.iterator_at(std::get<1>(res))), 
4158
                std::get<2>(res)};
4159
    }
4160
4161
    
4162
};
4163
4164
4165
// Constructs T into uninitialized storage pointed by `ptr` using the args
4166
// specified in the tuple.
4167
// ----------------------------------------------------------------------------
4168
template <class Alloc, class T, class Tuple>
4169
void ConstructFromTuple(Alloc* alloc, T* ptr, Tuple&& t) {
4170
    memory_internal::ConstructFromTupleImpl(
4171
        alloc, ptr, std::forward<Tuple>(t),
4172
        phmap::make_index_sequence<
4173
        std::tuple_size<typename std::decay<Tuple>::type>::value>());
4174
}
4175
4176
// Constructs T using the args specified in the tuple and calls F with the
4177
// constructed value.
4178
// ----------------------------------------------------------------------------
4179
template <class T, class Tuple, class F>
4180
decltype(std::declval<F>()(std::declval<T>())) WithConstructed(
4181
    Tuple&& t, F&& f) {
4182
    return memory_internal::WithConstructedImpl<T>(
4183
        std::forward<Tuple>(t),
4184
        phmap::make_index_sequence<
4185
        std::tuple_size<typename std::decay<Tuple>::type>::value>(),
4186
        std::forward<F>(f));
4187
}
4188
4189
// ----------------------------------------------------------------------------
4190
// Given arguments of an std::pair's consructor, PairArgs() returns a pair of
4191
// tuples with references to the passed arguments. The tuples contain
4192
// constructor arguments for the first and the second elements of the pair.
4193
//
4194
// The following two snippets are equivalent.
4195
//
4196
// 1. std::pair<F, S> p(args...);
4197
//
4198
// 2. auto a = PairArgs(args...);
4199
//    std::pair<F, S> p(std::piecewise_construct,
4200
//                      std::move(p.first), std::move(p.second));
4201
// ----------------------------------------------------------------------------
4202
0
inline std::pair<std::tuple<>, std::tuple<>> PairArgs() { return {}; }
4203
4204
template <class F, class S>
4205
22.4M
std::pair<std::tuple<F&&>, std::tuple<S&&>> PairArgs(F&& f, S&& s) {
4206
22.4M
  return {std::piecewise_construct, std::forward_as_tuple(std::forward<F>(f)),
4207
22.4M
          std::forward_as_tuple(std::forward<S>(s))};
4208
22.4M
}
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
4205
12.5M
std::pair<std::tuple<F&&>, std::tuple<S&&>> PairArgs(F&& f, S&& s) {
4206
12.5M
  return {std::piecewise_construct, std::forward_as_tuple(std::forward<F>(f)),
4207
12.5M
          std::forward_as_tuple(std::forward<S>(s))};
4208
12.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
4205
9.85M
std::pair<std::tuple<F&&>, std::tuple<S&&>> PairArgs(F&& f, S&& s) {
4206
9.85M
  return {std::piecewise_construct, std::forward_as_tuple(std::forward<F>(f)),
4207
9.85M
          std::forward_as_tuple(std::forward<S>(s))};
4208
9.85M
}
4209
4210
template <class F, class S>
4211
std::pair<std::tuple<const F&>, std::tuple<const S&>> PairArgs(
4212
12.5M
    const std::pair<F, S>& p) {
4213
12.5M
    return PairArgs(p.first, p.second);
4214
12.5M
}
4215
4216
template <class F, class S>
4217
9.85M
std::pair<std::tuple<F&&>, std::tuple<S&&>> PairArgs(std::pair<F, S>&& p) {
4218
9.85M
    return PairArgs(std::forward<F>(p.first), std::forward<S>(p.second));
4219
9.85M
}
4220
4221
template <class F, class S>
4222
auto PairArgs(std::piecewise_construct_t, F&& f, S&& s)
4223
    -> decltype(std::make_pair(memory_internal::TupleRef(std::forward<F>(f)),
4224
                               memory_internal::TupleRef(std::forward<S>(s)))) {
4225
    return std::make_pair(memory_internal::TupleRef(std::forward<F>(f)),
4226
                          memory_internal::TupleRef(std::forward<S>(s)));
4227
}
4228
4229
// A helper function for implementing apply() in map policies.
4230
// ----------------------------------------------------------------------------
4231
template <class F, class... Args>
4232
auto DecomposePair(F&& f, Args&&... args)
4233
    -> decltype(memory_internal::DecomposePairImpl(
4234
22.4M
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...))) {
4235
22.4M
    return memory_internal::DecomposePairImpl(
4236
22.4M
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...));
4237
22.4M
}
_ZN5phmap4priv13DecomposePairINS0_12raw_hash_setINS0_17FlatHashMapPolicyIjiEENS_4HashIjEENS_7EqualToIjEENSt3__19allocatorINS9_4pairIKjiEEEEE19EmplaceDecomposableEJSD_EEEDTclsr15memory_internalE17DecomposePairImplclsr3stdE7forwardIT_Efp_Ecl8PairArgsspclsr3stdE7forwardIT0_Efp0_EEEEOSH_DpOSI_
Line
Count
Source
4234
9.85M
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...))) {
4235
9.85M
    return memory_internal::DecomposePairImpl(
4236
9.85M
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...));
4237
9.85M
}
_ZN5phmap4priv13DecomposePairINS0_12raw_hash_setINS0_17FlatHashMapPolicyIjiEENS_4HashIjEENS_7EqualToIjEENSt3__19allocatorINS9_4pairIKjiEEEEE12EqualElementIjEEJRSD_EEEDTclsr15memory_internalE17DecomposePairImplclsr3stdE7forwardIT_Efp_Ecl8PairArgsspclsr3stdE7forwardIT0_Efp0_EEEEOSJ_DpOSK_
Line
Count
Source
4234
10.9M
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...))) {
4235
10.9M
    return memory_internal::DecomposePairImpl(
4236
10.9M
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...));
4237
10.9M
}
_ZN5phmap4priv13DecomposePairINS0_12raw_hash_setINS0_17FlatHashMapPolicyIjiEENS_4HashIjEENS_7EqualToIjEENSt3__19allocatorINS9_4pairIKjiEEEEE11HashElementEJRSD_EEEDTclsr15memory_internalE17DecomposePairImplclsr3stdE7forwardIT_Efp_Ecl8PairArgsspclsr3stdE7forwardIT0_Efp0_EEEEOSI_DpOSJ_
Line
Count
Source
4234
1.01M
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...))) {
4235
1.01M
    return memory_internal::DecomposePairImpl(
4236
1.01M
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...));
4237
1.01M
}
_ZN5phmap4priv13DecomposePairINS0_12raw_hash_setINS0_17FlatHashMapPolicyIjiEENS_4HashIjEENS_7EqualToIjEENSt3__19allocatorINS9_4pairIKjiEEEEE11HashElementEJRKSD_EEEDTclsr15memory_internalE17DecomposePairImplclsr3stdE7forwardIT_Efp_Ecl8PairArgsspclsr3stdE7forwardIT0_Efp0_EEEEOSJ_DpOSK_
Line
Count
Source
4234
559k
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...))) {
4235
559k
    return memory_internal::DecomposePairImpl(
4236
559k
        std::forward<F>(f), PairArgs(std::forward<Args>(args)...));
4237
559k
}
4238
4239
// A helper function for implementing apply() in set policies.
4240
// ----------------------------------------------------------------------------
4241
template <class F, class Arg>
4242
decltype(std::declval<F>()(std::declval<const Arg&>(), std::declval<Arg>()))
4243
DecomposeValue(F&& f, Arg&& arg) {
4244
    const auto& key = arg;
4245
    return std::forward<F>(f)(key, std::forward<Arg>(arg));
4246
}
4247
4248
4249
// --------------------------------------------------------------------------
4250
// Policy: a policy defines how to perform different operations on
4251
// the slots of the hashtable (see hash_policy_traits.h for the full interface
4252
// of policy).
4253
//
4254
// Hash: a (possibly polymorphic) functor that hashes keys of the hashtable. The
4255
// functor should accept a key and return size_t as hash. For best performance
4256
// it is important that the hash function provides high entropy across all bits
4257
// of the hash.
4258
//
4259
// Eq: a (possibly polymorphic) functor that compares two keys for equality. It
4260
// should accept two (of possibly different type) keys and return a bool: true
4261
// if they are equal, false if they are not. If two keys compare equal, then
4262
// their hash values as defined by Hash MUST be equal.
4263
//
4264
// Allocator: an Allocator [https://devdocs.io/cpp/concept/allocator] with which
4265
// the storage of the hashtable will be allocated and the elements will be
4266
// constructed and destroyed.
4267
// --------------------------------------------------------------------------
4268
template <class T>
4269
struct FlatHashSetPolicy 
4270
{
4271
    using slot_type = T;
4272
    using key_type = T;
4273
    using init_type = T;
4274
    using constant_iterators = std::true_type;
4275
    using is_flat = std::true_type;
4276
4277
    template <class Allocator, class... Args>
4278
    static void construct(Allocator* alloc, slot_type* slot, Args&&... args) {
4279
        phmap::allocator_traits<Allocator>::construct(*alloc, slot,
4280
                                                      std::forward<Args>(args)...);
4281
    }
4282
4283
    template <class Allocator>
4284
    static void destroy(Allocator* alloc, slot_type* slot) {
4285
        phmap::allocator_traits<Allocator>::destroy(*alloc, slot);
4286
    }
4287
4288
    template <class Allocator>
4289
    static void transfer(Allocator* alloc, slot_type* new_slot,
4290
                         slot_type* old_slot) {
4291
        construct(alloc, new_slot, std::move(*old_slot));
4292
        destroy(alloc, old_slot);
4293
    }
4294
4295
    static T& element(slot_type* slot) { return *slot; }
4296
4297
    template <class F, class... Args>
4298
    static decltype(phmap::priv::DecomposeValue(
4299
                        std::declval<F>(), std::declval<Args>()...))
4300
    apply(F&& f, Args&&... args) {
4301
        return phmap::priv::DecomposeValue(
4302
            std::forward<F>(f), std::forward<Args>(args)...);
4303
    }
4304
4305
    static size_t space_used(const T*) { return 0; }
4306
};
4307
4308
// --------------------------------------------------------------------------
4309
// --------------------------------------------------------------------------
4310
template <class K, class V>
4311
struct FlatHashMapPolicy 
4312
{
4313
    using slot_policy = priv::map_slot_policy<K, V>;
4314
    using slot_type = typename slot_policy::slot_type;
4315
    using key_type = K;
4316
    using mapped_type = V;
4317
    using init_type = std::pair</*non const*/ key_type, mapped_type>;
4318
    using is_flat = std::true_type;
4319
4320
    template <class Allocator, class... Args>
4321
576k
    static void construct(Allocator* alloc, slot_type* slot, Args&&... args) {
4322
576k
        slot_policy::construct(alloc, slot, std::forward<Args>(args)...);
4323
576k
    }
4324
4325
    template <class Allocator>
4326
0
    static void destroy(Allocator* alloc, slot_type* slot) {
4327
0
        slot_policy::destroy(alloc, slot);
4328
0
    }
4329
4330
    template <class Allocator>
4331
    static void transfer(Allocator* alloc, slot_type* new_slot,
4332
1.01M
                         slot_type* old_slot) {
4333
1.01M
        slot_policy::transfer(alloc, new_slot, old_slot);
4334
1.01M
    }
4335
4336
    template <class F, class... Args>
4337
    static decltype(phmap::priv::DecomposePair(
4338
                        std::declval<F>(), std::declval<Args>()...))
4339
22.4M
    apply(F&& f, Args&&... args) {
4340
22.4M
        return phmap::priv::DecomposePair(std::forward<F>(f),
4341
22.4M
                                                        std::forward<Args>(args)...);
4342
22.4M
    }
_ZN5phmap4priv17FlatHashMapPolicyIjiE5applyINS0_12raw_hash_setIS2_NS_4HashIjEENS_7EqualToIjEENSt3__19allocatorINS9_4pairIKjiEEEEE19EmplaceDecomposableEJSD_EEEDTclsr5phmap4privE13DecomposePairclsr3stdE7declvalIT_EEspclsr3stdE7declvalIT0_EEEEOSH_DpOSI_
Line
Count
Source
4339
9.85M
    apply(F&& f, Args&&... args) {
4340
9.85M
        return phmap::priv::DecomposePair(std::forward<F>(f),
4341
9.85M
                                                        std::forward<Args>(args)...);
4342
9.85M
    }
_ZN5phmap4priv17FlatHashMapPolicyIjiE5applyINS0_12raw_hash_setIS2_NS_4HashIjEENS_7EqualToIjEENSt3__19allocatorINS9_4pairIKjiEEEEE12EqualElementIjEEJRSD_EEEDTclsr5phmap4privE13DecomposePairclsr3stdE7declvalIT_EEspclsr3stdE7declvalIT0_EEEEOSJ_DpOSK_
Line
Count
Source
4339
10.9M
    apply(F&& f, Args&&... args) {
4340
10.9M
        return phmap::priv::DecomposePair(std::forward<F>(f),
4341
10.9M
                                                        std::forward<Args>(args)...);
4342
10.9M
    }
_ZN5phmap4priv17FlatHashMapPolicyIjiE5applyINS0_12raw_hash_setIS2_NS_4HashIjEENS_7EqualToIjEENSt3__19allocatorINS9_4pairIKjiEEEEE11HashElementEJRSD_EEEDTclsr5phmap4privE13DecomposePairclsr3stdE7declvalIT_EEspclsr3stdE7declvalIT0_EEEEOSI_DpOSJ_
Line
Count
Source
4339
1.01M
    apply(F&& f, Args&&... args) {
4340
1.01M
        return phmap::priv::DecomposePair(std::forward<F>(f),
4341
1.01M
                                                        std::forward<Args>(args)...);
4342
1.01M
    }
_ZN5phmap4priv17FlatHashMapPolicyIjiE5applyINS0_12raw_hash_setIS2_NS_4HashIjEENS_7EqualToIjEENSt3__19allocatorINS9_4pairIKjiEEEEE11HashElementEJRKSD_EEEDTclsr5phmap4privE13DecomposePairclsr3stdE7declvalIT_EEspclsr3stdE7declvalIT0_EEEEOSJ_DpOSK_
Line
Count
Source
4339
559k
    apply(F&& f, Args&&... args) {
4340
559k
        return phmap::priv::DecomposePair(std::forward<F>(f),
4341
559k
                                                        std::forward<Args>(args)...);
4342
559k
    }
4343
4344
    static size_t space_used(const slot_type*) { return 0; }
4345
4346
13.1M
    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
4346
13.1M
    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> > >*)
4347
4348
    static V& value(std::pair<const K, V>* kv) { return kv->second; }
4349
    static const V& value(const std::pair<const K, V>* kv) { return kv->second; }
4350
};
4351
4352
template <class Reference, class Policy>
4353
struct node_hash_policy {
4354
    static_assert(std::is_lvalue_reference<Reference>::value, "");
4355
4356
    using slot_type = typename std::remove_cv<
4357
        typename std::remove_reference<Reference>::type>::type*;
4358
4359
    template <class Alloc, class... Args>
4360
    static void construct(Alloc* alloc, slot_type* slot, Args&&... args) {
4361
        *slot = Policy::new_element(alloc, std::forward<Args>(args)...);
4362
    }
4363
4364
    template <class Alloc>
4365
    static void destroy(Alloc* alloc, slot_type* slot) {
4366
        Policy::delete_element(alloc, *slot);
4367
    }
4368
4369
    template <class Alloc>
4370
    static void transfer(Alloc*, slot_type* new_slot, slot_type* old_slot) {
4371
        *new_slot = *old_slot;
4372
    }
4373
4374
    static size_t space_used(const slot_type* slot) {
4375
        if (slot == nullptr) return Policy::element_space_used(nullptr);
4376
        return Policy::element_space_used(*slot);
4377
    }
4378
4379
    static Reference element(slot_type* slot) { return **slot; }
4380
4381
    template <class T, class P = Policy>
4382
    static auto value(T* elem) -> decltype(P::value(elem)) {
4383
        return P::value(elem);
4384
    }
4385
4386
    template <class... Ts, class P = Policy>
4387
    static auto apply(Ts&&... ts) -> decltype(P::apply(std::forward<Ts>(ts)...)) {
4388
        return P::apply(std::forward<Ts>(ts)...);
4389
    }
4390
};
4391
4392
// --------------------------------------------------------------------------
4393
// --------------------------------------------------------------------------
4394
template <class T>
4395
struct NodeHashSetPolicy
4396
    : phmap::priv::node_hash_policy<T&, NodeHashSetPolicy<T>> 
4397
{
4398
    using key_type = T;
4399
    using init_type = T;
4400
    using constant_iterators = std::true_type;
4401
    using is_flat = std::false_type;
4402
4403
    template <class Allocator, class... Args>
4404
        static T* new_element(Allocator* alloc, Args&&... args) {
4405
        using ValueAlloc =
4406
            typename phmap::allocator_traits<Allocator>::template rebind_alloc<T>;
4407
        ValueAlloc value_alloc(*alloc);
4408
        T* res = phmap::allocator_traits<ValueAlloc>::allocate(value_alloc, 1);
4409
        phmap::allocator_traits<ValueAlloc>::construct(value_alloc, res,
4410
                                                       std::forward<Args>(args)...);
4411
        return res;
4412
    }
4413
4414
    template <class Allocator>
4415
        static void delete_element(Allocator* alloc, T* elem) {
4416
        using ValueAlloc =
4417
            typename phmap::allocator_traits<Allocator>::template rebind_alloc<T>;
4418
        ValueAlloc value_alloc(*alloc);
4419
        phmap::allocator_traits<ValueAlloc>::destroy(value_alloc, elem);
4420
        phmap::allocator_traits<ValueAlloc>::deallocate(value_alloc, elem, 1);
4421
    }
4422
4423
    template <class F, class... Args>
4424
        static decltype(phmap::priv::DecomposeValue(
4425
                            std::declval<F>(), std::declval<Args>()...))
4426
        apply(F&& f, Args&&... args) {
4427
        return phmap::priv::DecomposeValue(
4428
            std::forward<F>(f), std::forward<Args>(args)...);
4429
    }
4430
4431
    static size_t element_space_used(const T*) { return sizeof(T); }
4432
};
4433
4434
// --------------------------------------------------------------------------
4435
// --------------------------------------------------------------------------
4436
template <class Key, class Value>
4437
class NodeHashMapPolicy
4438
    : public phmap::priv::node_hash_policy<
4439
          std::pair<const Key, Value>&, NodeHashMapPolicy<Key, Value>> 
4440
{
4441
    using value_type = std::pair<const Key, Value>;
4442
4443
public:
4444
    using key_type = Key;
4445
    using mapped_type = Value;
4446
    using init_type = std::pair</*non const*/ key_type, mapped_type>;
4447
    using is_flat = std::false_type;
4448
4449
    template <class Allocator, class... Args>
4450
        static value_type* new_element(Allocator* alloc, Args&&... args) {
4451
        using PairAlloc = typename phmap::allocator_traits<
4452
            Allocator>::template rebind_alloc<value_type>;
4453
        PairAlloc pair_alloc(*alloc);
4454
        value_type* res =
4455
            phmap::allocator_traits<PairAlloc>::allocate(pair_alloc, 1);
4456
        phmap::allocator_traits<PairAlloc>::construct(pair_alloc, res,
4457
                                                      std::forward<Args>(args)...);
4458
        return res;
4459
    }
4460
4461
    template <class Allocator>
4462
        static void delete_element(Allocator* alloc, value_type* pair) {
4463
        using PairAlloc = typename phmap::allocator_traits<
4464
            Allocator>::template rebind_alloc<value_type>;
4465
        PairAlloc pair_alloc(*alloc);
4466
        phmap::allocator_traits<PairAlloc>::destroy(pair_alloc, pair);
4467
        phmap::allocator_traits<PairAlloc>::deallocate(pair_alloc, pair, 1);
4468
    }
4469
4470
    template <class F, class... Args>
4471
        static decltype(phmap::priv::DecomposePair(
4472
                            std::declval<F>(), std::declval<Args>()...))
4473
        apply(F&& f, Args&&... args) {
4474
        return phmap::priv::DecomposePair(std::forward<F>(f),
4475
                                                        std::forward<Args>(args)...);
4476
    }
4477
4478
    static size_t element_space_used(const value_type*) {
4479
        return sizeof(value_type);
4480
    }
4481
4482
    static Value& value(value_type* elem) { return elem->second; }
4483
    static const Value& value(const value_type* elem) { return elem->second; }
4484
};
4485
4486
4487
// --------------------------------------------------------------------------
4488
//  hash_default
4489
// --------------------------------------------------------------------------
4490
4491
#if PHMAP_HAVE_STD_STRING_VIEW
4492
4493
// Supports heterogeneous lookup for basic_string<T>-like elements.
4494
template<class CharT> 
4495
struct StringHashEqT
4496
{
4497
    struct Hash 
4498
    {
4499
        using is_transparent = void;
4500
        
4501
        size_t operator()(std::basic_string_view<CharT> v) const {
4502
            std::string_view bv{
4503
                reinterpret_cast<const char*>(v.data()), v.size() * sizeof(CharT)};
4504
            return std::hash<std::string_view>()(bv);
4505
        }
4506
    };
4507
4508
    struct Eq {
4509
        using is_transparent = void;
4510
4511
        bool operator()(std::basic_string_view<CharT> lhs,
4512
                        std::basic_string_view<CharT> rhs) const {
4513
            return lhs == rhs;
4514
        }
4515
    };
4516
};
4517
4518
template <>
4519
struct HashEq<std::string> : StringHashEqT<char> {};
4520
4521
template <>
4522
struct HashEq<std::string_view> : StringHashEqT<char> {};
4523
4524
// char16_t
4525
template <>
4526
struct HashEq<std::u16string> : StringHashEqT<char16_t> {};
4527
4528
template <>
4529
struct HashEq<std::u16string_view> : StringHashEqT<char16_t> {};
4530
4531
// wchar_t
4532
template <>
4533
struct HashEq<std::wstring> : StringHashEqT<wchar_t> {};
4534
4535
template <>
4536
struct HashEq<std::wstring_view> : StringHashEqT<wchar_t> {};
4537
4538
#endif
4539
4540
// Supports heterogeneous lookup for pointers and smart pointers.
4541
// -------------------------------------------------------------
4542
template <class T>
4543
struct HashEq<T*> 
4544
{
4545
    struct Hash {
4546
        using is_transparent = void;
4547
        template <class U>
4548
        size_t operator()(const U& ptr) const {
4549
            // we want phmap::Hash<T*> and not phmap::Hash<const T*>
4550
            // so "struct std::hash<T*> " override works
4551
            return phmap::Hash<T*>{}((T*)(uintptr_t)HashEq::ToPtr(ptr));
4552
        }
4553
    };
4554
4555
    struct Eq {
4556
        using is_transparent = void;
4557
        template <class A, class B>
4558
        bool operator()(const A& a, const B& b) const {
4559
            return HashEq::ToPtr(a) == HashEq::ToPtr(b);
4560
        }
4561
    };
4562
4563
private:
4564
    static const T* ToPtr(const T* ptr) { return ptr; }
4565
4566
    template <class U, class D>
4567
    static const T* ToPtr(const std::unique_ptr<U, D>& ptr) {
4568
        return ptr.get();
4569
    }
4570
4571
    template <class U>
4572
    static const T* ToPtr(const std::shared_ptr<U>& ptr) {
4573
        return ptr.get();
4574
    }
4575
};
4576
4577
template <class T, class D>
4578
struct HashEq<std::unique_ptr<T, D>> : HashEq<T*> {};
4579
4580
template <class T>
4581
struct HashEq<std::shared_ptr<T>> : HashEq<T*> {};
4582
4583
namespace hashtable_debug_internal {
4584
4585
// --------------------------------------------------------------------------
4586
// --------------------------------------------------------------------------
4587
4588
template<typename, typename = void >
4589
struct has_member_type_raw_hash_set : std::false_type
4590
{};
4591
template<typename T>
4592
struct has_member_type_raw_hash_set<T, phmap::void_t<typename T::raw_hash_set>> : std::true_type
4593
{};
4594
4595
template <typename Set>
4596
struct HashtableDebugAccess<Set, typename std::enable_if<has_member_type_raw_hash_set<Set>::value>::type>
4597
{
4598
    using Traits = typename Set::PolicyTraits;
4599
    using Slot = typename Traits::slot_type;
4600
4601
    static size_t GetNumProbes(const Set& set,
4602
                               const typename Set::key_type& key) {
4603
        if (!set.ctrl_)
4604
            return 0;
4605
        size_t num_probes = 0;
4606
        size_t hashval = set.hash(key); 
4607
        auto seq = set.probe(hashval);
4608
        while (true) {
4609
            priv::Group g{set.ctrl_ + seq.offset()};
4610
            for (uint32_t i : g.Match((h2_t)priv::H2(hashval))) {
4611
                if (Traits::apply(
4612
                        typename Set::template EqualElement<typename Set::key_type>{
4613
                            key, set.eq_ref()},
4614
                        Traits::element(set.slots_ + seq.offset((size_t)i))))
4615
                    return num_probes;
4616
                ++num_probes;
4617
            }
4618
            if (g.MatchEmpty()) return num_probes;
4619
            seq.next();
4620
            ++num_probes;
4621
        }
4622
    }
4623
4624
    static size_t AllocatedByteSize(const Set& c) {
4625
        size_t capacity = c.capacity_;
4626
        if (capacity == 0) return 0;
4627
        auto layout = Set::MakeLayout(capacity);
4628
        size_t m = layout.AllocSize();
4629
4630
        size_t per_slot = Traits::space_used(static_cast<const Slot*>(nullptr));
4631
        if (per_slot != ~size_t{}) {
4632
            m += per_slot * c.size();
4633
        } else {
4634
            for (size_t i = 0; i != capacity; ++i) {
4635
                if (priv::IsFull(c.ctrl_[i])) {
4636
                    m += Traits::space_used(c.slots_ + i);
4637
                }
4638
            }
4639
        }
4640
        return m;
4641
    }
4642
4643
    static size_t LowerBoundAllocatedByteSize(size_t size) {
4644
        size_t capacity = GrowthToLowerboundCapacity(size);
4645
        if (capacity == 0) return 0;
4646
        auto layout = Set::MakeLayout(NormalizeCapacity(capacity));
4647
        size_t m = layout.AllocSize();
4648
        size_t per_slot = Traits::space_used(static_cast<const Slot*>(nullptr));
4649
        if (per_slot != ~size_t{}) {
4650
            m += per_slot * size;
4651
        }
4652
        return m;
4653
    }
4654
};
4655
4656
4657
template<typename, typename = void >
4658
struct has_member_type_EmbeddedSet : std::false_type
4659
{};
4660
template<typename T>
4661
struct has_member_type_EmbeddedSet<T, phmap::void_t<typename T::EmbeddedSet>> : std::true_type
4662
{};
4663
4664
template <typename Set>
4665
struct HashtableDebugAccess<Set, typename std::enable_if<has_member_type_EmbeddedSet<Set>::value>::type> {
4666
    using Traits = typename Set::PolicyTraits;
4667
    using Slot = typename Traits::slot_type;
4668
    using EmbeddedSet = typename Set::EmbeddedSet;
4669
4670
    static size_t GetNumProbes(const Set& set, const typename Set::key_type& key) {
4671
        size_t hashval = set.hash(key);
4672
        auto& inner = set.sets_[set.subidx(hashval)];
4673
        auto& inner_set = inner.set_;
4674
        return HashtableDebugAccess<EmbeddedSet>::GetNumProbes(inner_set, key);
4675
    }
4676
};
4677
4678
}  // namespace hashtable_debug_internal
4679
}  // namespace priv
4680
4681
// -----------------------------------------------------------------------------
4682
// phmap::flat_hash_set
4683
// -----------------------------------------------------------------------------
4684
// An `phmap::flat_hash_set<T>` is an unordered associative container which has
4685
// been optimized for both speed and memory footprint in most common use cases.
4686
// Its interface is similar to that of `std::unordered_set<T>` with the
4687
// following notable differences:
4688
//
4689
// * Supports heterogeneous lookup, through `find()`, `operator[]()` and
4690
//   `insert()`, provided that the set is provided a compatible heterogeneous
4691
//   hashing function and equality operator.
4692
// * Invalidates any references and pointers to elements within the table after
4693
//   `rehash()`.
4694
// * Contains a `capacity()` member function indicating the number of element
4695
//   slots (open, deleted, and empty) within the hash set.
4696
// * Returns `void` from the `_erase(iterator)` overload.
4697
// -----------------------------------------------------------------------------
4698
template <class T, class Hash, class Eq, class Alloc> // default values in phmap_fwd_decl.h
4699
class flat_hash_set
4700
    : public phmap::priv::raw_hash_set<
4701
          phmap::priv::FlatHashSetPolicy<T>, Hash, Eq, Alloc> 
4702
{
4703
    using Base = typename flat_hash_set::raw_hash_set;
4704
4705
public:
4706
    flat_hash_set() {}
4707
#ifdef __INTEL_COMPILER
4708
    using Base::raw_hash_set;
4709
#else
4710
    using Base::Base;
4711
#endif
4712
    using Base::begin;
4713
    using Base::cbegin;
4714
    using Base::cend;
4715
    using Base::end;
4716
    using Base::capacity;
4717
    using Base::empty;
4718
    using Base::max_size;
4719
    using Base::size;
4720
    using Base::clear; // may shrink - To avoid shrinking `erase(begin(), end())`
4721
    using Base::erase;
4722
    using Base::insert;
4723
    using Base::emplace;
4724
    using Base::emplace_hint; 
4725
    using Base::extract;
4726
    using Base::merge;
4727
    using Base::swap;
4728
    using Base::rehash;
4729
    using Base::reserve;
4730
    using Base::contains;
4731
    using Base::count;
4732
    using Base::equal_range;
4733
    using Base::find;
4734
    using Base::bucket_count;
4735
    using Base::load_factor;
4736
    using Base::max_load_factor;
4737
    using Base::get_allocator;
4738
    using Base::hash_function;
4739
    using Base::hash;
4740
    using Base::key_eq;
4741
};
4742
4743
// -----------------------------------------------------------------------------
4744
// phmap::flat_hash_map
4745
// -----------------------------------------------------------------------------
4746
//
4747
// An `phmap::flat_hash_map<K, V>` is an unordered associative container which
4748
// has been optimized for both speed and memory footprint in most common use
4749
// cases. Its interface is similar to that of `std::unordered_map<K, V>` with
4750
// the following notable differences:
4751
//
4752
// * Supports heterogeneous lookup, through `find()`, `operator[]()` and
4753
//   `insert()`, provided that the map is provided a compatible heterogeneous
4754
//   hashing function and equality operator.
4755
// * Invalidates any references and pointers to elements within the table after
4756
//   `rehash()`.
4757
// * Contains a `capacity()` member function indicating the number of element
4758
//   slots (open, deleted, and empty) within the hash map.
4759
// * Returns `void` from the `_erase(iterator)` overload.
4760
// -----------------------------------------------------------------------------
4761
template <class K, class V, class Hash, class Eq, class Alloc> // default values in phmap_fwd_decl.h
4762
class flat_hash_map : public phmap::priv::raw_hash_map<
4763
                          phmap::priv::FlatHashMapPolicy<K, V>,
4764
                          Hash, Eq, Alloc> {
4765
    using Base = typename flat_hash_map::raw_hash_map;
4766
4767
public:
4768
1.75k
    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
4768
1.16k
    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
4768
584
    flat_hash_map() {}
4769
#ifdef __INTEL_COMPILER
4770
    using Base::raw_hash_map;
4771
#else
4772
    using Base::Base;
4773
#endif
4774
    using Base::begin;
4775
    using Base::cbegin;
4776
    using Base::cend;
4777
    using Base::end;
4778
    using Base::capacity;
4779
    using Base::empty;
4780
    using Base::max_size;
4781
    using Base::size;
4782
    using Base::clear;
4783
    using Base::erase;
4784
    using Base::insert;
4785
    using Base::insert_or_assign;
4786
    using Base::emplace;
4787
    using Base::emplace_hint;
4788
    using Base::try_emplace;
4789
    using Base::extract;
4790
    using Base::merge;
4791
    using Base::swap;
4792
    using Base::rehash;
4793
    using Base::reserve;
4794
    using Base::at;
4795
    using Base::contains;
4796
    using Base::count;
4797
    using Base::equal_range;
4798
    using Base::find;
4799
    using Base::operator[];
4800
    using Base::bucket_count;
4801
    using Base::load_factor;
4802
    using Base::max_load_factor;
4803
    using Base::get_allocator;
4804
    using Base::hash_function;
4805
    using Base::hash;
4806
    using Base::key_eq;
4807
};
4808
4809
// -----------------------------------------------------------------------------
4810
// phmap::node_hash_set
4811
// -----------------------------------------------------------------------------
4812
// An `phmap::node_hash_set<T>` is an unordered associative container which
4813
// has been optimized for both speed and memory footprint in most common use
4814
// cases. Its interface is similar to that of `std::unordered_set<T>` with the
4815
// following notable differences:
4816
//
4817
// * Supports heterogeneous lookup, through `find()`, `operator[]()` and
4818
//   `insert()`, provided that the map is provided a compatible heterogeneous
4819
//   hashing function and equality operator.
4820
// * Contains a `capacity()` member function indicating the number of element
4821
//   slots (open, deleted, and empty) within the hash set.
4822
// * Returns `void` from the `_erase(iterator)` overload.
4823
// -----------------------------------------------------------------------------
4824
template <class T, class Hash, class Eq, class Alloc> // default values in phmap_fwd_decl.h
4825
class node_hash_set
4826
    : public phmap::priv::raw_hash_set<
4827
          phmap::priv::NodeHashSetPolicy<T>, Hash, Eq, Alloc> 
4828
{
4829
    using Base = typename node_hash_set::raw_hash_set;
4830
4831
public:
4832
    node_hash_set() {}
4833
#ifdef __INTEL_COMPILER
4834
    using Base::raw_hash_set;
4835
#else
4836
    using Base::Base;
4837
#endif
4838
    using Base::begin;
4839
    using Base::cbegin;
4840
    using Base::cend;
4841
    using Base::end;
4842
    using Base::capacity;
4843
    using Base::empty;
4844
    using Base::max_size;
4845
    using Base::size;
4846
    using Base::clear;
4847
    using Base::erase;
4848
    using Base::insert;
4849
    using Base::emplace;
4850
    using Base::emplace_hint;
4851
    using Base::emplace_with_hash;
4852
    using Base::emplace_hint_with_hash;
4853
    using Base::extract;
4854
    using Base::merge;
4855
    using Base::swap;
4856
    using Base::rehash;
4857
    using Base::reserve;
4858
    using Base::contains;
4859
    using Base::count;
4860
    using Base::equal_range;
4861
    using Base::find;
4862
    using Base::bucket_count;
4863
    using Base::load_factor;
4864
    using Base::max_load_factor;
4865
    using Base::get_allocator;
4866
    using Base::hash_function;
4867
    using Base::hash;
4868
    using Base::key_eq;
4869
    typename Base::hasher hash_funct() { return this->hash_function(); }
4870
    void resize(typename Base::size_type hint) { this->rehash(hint); }
4871
};
4872
4873
// -----------------------------------------------------------------------------
4874
// phmap::node_hash_map
4875
// -----------------------------------------------------------------------------
4876
//
4877
// An `phmap::node_hash_map<K, V>` is an unordered associative container which
4878
// has been optimized for both speed and memory footprint in most common use
4879
// cases. Its interface is similar to that of `std::unordered_map<K, V>` with
4880
// the following notable differences:
4881
//
4882
// * Supports heterogeneous lookup, through `find()`, `operator[]()` and
4883
//   `insert()`, provided that the map is provided a compatible heterogeneous
4884
//   hashing function and equality operator.
4885
// * Contains a `capacity()` member function indicating the number of element
4886
//   slots (open, deleted, and empty) within the hash map.
4887
// * Returns `void` from the `_erase(iterator)` overload.
4888
// -----------------------------------------------------------------------------
4889
template <class Key, class Value, class Hash, class Eq, class Alloc>  // default values in phmap_fwd_decl.h
4890
class node_hash_map
4891
    : public phmap::priv::raw_hash_map<
4892
          phmap::priv::NodeHashMapPolicy<Key, Value>, Hash, Eq,
4893
          Alloc> 
4894
{
4895
    using Base = typename node_hash_map::raw_hash_map;
4896
4897
public:
4898
    node_hash_map() {}
4899
#ifdef __INTEL_COMPILER
4900
    using Base::raw_hash_map;
4901
#else
4902
    using Base::Base;
4903
#endif
4904
    using Base::begin;
4905
    using Base::cbegin;
4906
    using Base::cend;
4907
    using Base::end;
4908
    using Base::capacity;
4909
    using Base::empty;
4910
    using Base::max_size;
4911
    using Base::size;
4912
    using Base::clear;
4913
    using Base::erase;
4914
    using Base::insert;
4915
    using Base::insert_or_assign;
4916
    using Base::emplace;
4917
    using Base::emplace_hint;
4918
    using Base::try_emplace;
4919
    using Base::extract;
4920
    using Base::merge;
4921
    using Base::swap;
4922
    using Base::rehash;
4923
    using Base::reserve;
4924
    using Base::at;
4925
    using Base::contains;
4926
    using Base::count;
4927
    using Base::equal_range;
4928
    using Base::find;
4929
    using Base::operator[];
4930
    using Base::bucket_count;
4931
    using Base::load_factor;
4932
    using Base::max_load_factor;
4933
    using Base::get_allocator;
4934
    using Base::hash_function;
4935
    using Base::hash;
4936
    using Base::key_eq;
4937
    typename Base::hasher hash_funct() { return this->hash_function(); }
4938
    void resize(typename Base::size_type hint) { this->rehash(hint); }
4939
};
4940
4941
// -----------------------------------------------------------------------------
4942
// phmap::parallel_flat_hash_set
4943
// -----------------------------------------------------------------------------
4944
template <class T, class Hash, class Eq, class Alloc, size_t N, class Mtx_> // default values in phmap_fwd_decl.h
4945
class parallel_flat_hash_set
4946
    : public phmap::priv::parallel_hash_set<
4947
         N, phmap::priv::raw_hash_set, Mtx_,
4948
         phmap::priv::FlatHashSetPolicy<T>, 
4949
         Hash, Eq, Alloc> 
4950
{
4951
    using Base = typename parallel_flat_hash_set::parallel_hash_set;
4952
4953
public:
4954
    parallel_flat_hash_set() {}
4955
#ifdef __INTEL_COMPILER
4956
    using Base::parallel_hash_set;
4957
#else
4958
    using Base::Base;
4959
#endif
4960
    using Base::hash;
4961
    using Base::subidx;
4962
    using Base::subcnt;
4963
    using Base::begin;
4964
    using Base::cbegin;
4965
    using Base::cend;
4966
    using Base::end;
4967
    using Base::capacity;
4968
    using Base::empty;
4969
    using Base::max_size;
4970
    using Base::size;
4971
    using Base::clear;
4972
    using Base::erase;
4973
    using Base::insert;
4974
    using Base::emplace;
4975
    using Base::emplace_hint;
4976
    using Base::emplace_with_hash;
4977
    using Base::emplace_hint_with_hash;
4978
    using Base::extract;
4979
    using Base::merge;
4980
    using Base::swap;
4981
    using Base::rehash;
4982
    using Base::reserve;
4983
    using Base::contains;
4984
    using Base::count;
4985
    using Base::equal_range;
4986
    using Base::find;
4987
    using Base::bucket_count;
4988
    using Base::load_factor;
4989
    using Base::max_load_factor;
4990
    using Base::get_allocator;
4991
    using Base::hash_function;
4992
    using Base::key_eq;
4993
};
4994
4995
// -----------------------------------------------------------------------------
4996
// phmap::parallel_flat_hash_map - default values in phmap_fwd_decl.h
4997
// -----------------------------------------------------------------------------
4998
template <class K, class V, class Hash, class Eq, class Alloc, size_t N, class Mtx_>
4999
class parallel_flat_hash_map : public phmap::priv::parallel_hash_map<
5000
                N, phmap::priv::raw_hash_set, Mtx_,
5001
                phmap::priv::FlatHashMapPolicy<K, V>,
5002
                Hash, Eq, Alloc> 
5003
{
5004
    using Base = typename parallel_flat_hash_map::parallel_hash_map;
5005
5006
public:
5007
    parallel_flat_hash_map() {}
5008
#ifdef __INTEL_COMPILER
5009
    using Base::parallel_hash_map;
5010
#else
5011
    using Base::Base;
5012
#endif
5013
    using Base::hash;
5014
    using Base::subidx;
5015
    using Base::subcnt;
5016
    using Base::begin;
5017
    using Base::cbegin;
5018
    using Base::cend;
5019
    using Base::end;
5020
    using Base::capacity;
5021
    using Base::empty;
5022
    using Base::max_size;
5023
    using Base::size;
5024
    using Base::clear;
5025
    using Base::erase;
5026
    using Base::insert;
5027
    using Base::insert_or_assign;
5028
    using Base::emplace;
5029
    using Base::emplace_hint;
5030
    using Base::try_emplace;
5031
    using Base::emplace_with_hash;
5032
    using Base::emplace_hint_with_hash;
5033
    using Base::try_emplace_with_hash;
5034
    using Base::extract;
5035
    using Base::merge;
5036
    using Base::swap;
5037
    using Base::rehash;
5038
    using Base::reserve;
5039
    using Base::at;
5040
    using Base::contains;
5041
    using Base::count;
5042
    using Base::equal_range;
5043
    using Base::find;
5044
    using Base::operator[];
5045
    using Base::bucket_count;
5046
    using Base::load_factor;
5047
    using Base::max_load_factor;
5048
    using Base::get_allocator;
5049
    using Base::hash_function;
5050
    using Base::key_eq;
5051
};
5052
5053
// -----------------------------------------------------------------------------
5054
// phmap::parallel_node_hash_set
5055
// -----------------------------------------------------------------------------
5056
template <class T, class Hash, class Eq, class Alloc, size_t N, class Mtx_>
5057
class parallel_node_hash_set
5058
    : public phmap::priv::parallel_hash_set<
5059
             N, phmap::priv::raw_hash_set, Mtx_,
5060
             phmap::priv::NodeHashSetPolicy<T>, Hash, Eq, Alloc> 
5061
{
5062
    using Base = typename parallel_node_hash_set::parallel_hash_set;
5063
5064
public:
5065
    parallel_node_hash_set() {}
5066
#ifdef __INTEL_COMPILER
5067
    using Base::parallel_hash_set;
5068
#else
5069
    using Base::Base;
5070
#endif
5071
    using Base::hash;
5072
    using Base::subidx;
5073
    using Base::subcnt;
5074
    using Base::begin;
5075
    using Base::cbegin;
5076
    using Base::cend;
5077
    using Base::end;
5078
    using Base::capacity;
5079
    using Base::empty;
5080
    using Base::max_size;
5081
    using Base::size;
5082
    using Base::clear;
5083
    using Base::erase;
5084
    using Base::insert;
5085
    using Base::emplace;
5086
    using Base::emplace_hint;
5087
    using Base::emplace_with_hash;
5088
    using Base::emplace_hint_with_hash;
5089
    using Base::extract;
5090
    using Base::merge;
5091
    using Base::swap;
5092
    using Base::rehash;
5093
    using Base::reserve;
5094
    using Base::contains;
5095
    using Base::count;
5096
    using Base::equal_range;
5097
    using Base::find;
5098
    using Base::bucket_count;
5099
    using Base::load_factor;
5100
    using Base::max_load_factor;
5101
    using Base::get_allocator;
5102
    using Base::hash_function;
5103
    using Base::key_eq;
5104
    typename Base::hasher hash_funct() { return this->hash_function(); }
5105
    void resize(typename Base::size_type hint) { this->rehash(hint); }
5106
};
5107
5108
// -----------------------------------------------------------------------------
5109
// phmap::parallel_node_hash_map
5110
// -----------------------------------------------------------------------------
5111
template <class Key, class Value, class Hash, class Eq, class Alloc, size_t N, class Mtx_>
5112
class parallel_node_hash_map
5113
    : public phmap::priv::parallel_hash_map<
5114
          N, phmap::priv::raw_hash_set, Mtx_,
5115
          phmap::priv::NodeHashMapPolicy<Key, Value>, Hash, Eq,
5116
          Alloc> 
5117
{
5118
    using Base = typename parallel_node_hash_map::parallel_hash_map;
5119
5120
public:
5121
    parallel_node_hash_map() {}
5122
#ifdef __INTEL_COMPILER
5123
    using Base::parallel_hash_map;
5124
#else
5125
    using Base::Base;
5126
#endif
5127
    using Base::hash;
5128
    using Base::subidx;
5129
    using Base::subcnt;
5130
    using Base::begin;
5131
    using Base::cbegin;
5132
    using Base::cend;
5133
    using Base::end;
5134
    using Base::capacity;
5135
    using Base::empty;
5136
    using Base::max_size;
5137
    using Base::size;
5138
    using Base::clear;
5139
    using Base::erase;
5140
    using Base::insert;
5141
    using Base::insert_or_assign;
5142
    using Base::emplace;
5143
    using Base::emplace_hint;
5144
    using Base::try_emplace;
5145
    using Base::emplace_with_hash;
5146
    using Base::emplace_hint_with_hash;
5147
    using Base::try_emplace_with_hash;
5148
    using Base::extract;
5149
    using Base::merge;
5150
    using Base::swap;
5151
    using Base::rehash;
5152
    using Base::reserve;
5153
    using Base::at;
5154
    using Base::contains;
5155
    using Base::count;
5156
    using Base::equal_range;
5157
    using Base::find;
5158
    using Base::operator[];
5159
    using Base::bucket_count;
5160
    using Base::load_factor;
5161
    using Base::max_load_factor;
5162
    using Base::get_allocator;
5163
    using Base::hash_function;
5164
    using Base::key_eq;
5165
    typename Base::hasher hash_funct() { return this->hash_function(); }
5166
    void resize(typename Base::size_type hint) { this->rehash(hint); }
5167
};
5168
5169
}  // namespace phmap
5170
5171
5172
namespace phmap {
5173
    namespace priv {
5174
        template <class C, class Pred> 
5175
        std::size_t erase_if(C &c, Pred pred) {
5176
            auto old_size = c.size();
5177
            for (auto i = c.begin(), last = c.end(); i != last; ) {
5178
                if (pred(*i)) {
5179
                    i = c.erase(i);
5180
                } else {
5181
                    ++i;
5182
                }
5183
            }
5184
            return old_size - c.size();
5185
        }
5186
    } // priv
5187
5188
    // ======== erase_if for phmap set containers ==================================
5189
    template <class T, class Hash, class Eq, class Alloc, class Pred> 
5190
    std::size_t erase_if(phmap::flat_hash_set<T, Hash, Eq, Alloc>& c, Pred pred) {
5191
        return phmap::priv::erase_if(c, std::move(pred));
5192
    }
5193
5194
    template <class T, class Hash, class Eq, class Alloc, class Pred> 
5195
    std::size_t erase_if(phmap::node_hash_set<T, Hash, Eq, Alloc>& c, Pred pred) {
5196
        return phmap::priv::erase_if(c, std::move(pred));
5197
    }
5198
5199
    template <class T, class Hash, class Eq, class Alloc, size_t N, class Mtx_, class Pred> 
5200
    std::size_t erase_if(phmap::parallel_flat_hash_set<T, Hash, Eq, Alloc, N, Mtx_>& c, Pred pred) {
5201
        return phmap::priv::erase_if(c, std::move(pred));
5202
    }
5203
5204
    template <class T, class Hash, class Eq, class Alloc, size_t N, class Mtx_, class Pred> 
5205
    std::size_t erase_if(phmap::parallel_node_hash_set<T, Hash, Eq, Alloc, N, Mtx_>& c, Pred pred) {
5206
        return phmap::priv::erase_if(c, std::move(pred));
5207
    }
5208
5209
    // ======== erase_if for phmap map containers ==================================
5210
    template <class K, class V, class Hash, class Eq, class Alloc, class Pred> 
5211
    std::size_t erase_if(phmap::flat_hash_map<K, V, Hash, Eq, Alloc>& c, Pred pred) {
5212
        return phmap::priv::erase_if(c, std::move(pred));
5213
    }
5214
5215
    template <class K, class V, class Hash, class Eq, class Alloc, class Pred> 
5216
    std::size_t erase_if(phmap::node_hash_map<K, V, Hash, Eq, Alloc>& c, Pred pred) {
5217
        return phmap::priv::erase_if(c, std::move(pred));
5218
    }
5219
5220
    template <class K, class V, class Hash, class Eq, class Alloc, size_t N, class Mtx_, class Pred> 
5221
    std::size_t erase_if(phmap::parallel_flat_hash_map<K, V, Hash, Eq, Alloc, N, Mtx_>& c, Pred pred) {
5222
        return phmap::priv::erase_if(c, std::move(pred));
5223
    }
5224
5225
    template <class K, class V, class Hash, class Eq, class Alloc, size_t N, class Mtx_, class Pred> 
5226
    std::size_t erase_if(phmap::parallel_node_hash_map<K, V, Hash, Eq, Alloc, N, Mtx_>& c, Pred pred) {
5227
        return phmap::priv::erase_if(c, std::move(pred));
5228
    }
5229
5230
} // phmap
5231
5232
#ifdef _MSC_VER
5233
     #pragma warning(pop)  
5234
#endif
5235
5236
5237
#endif // phmap_h_guard_