-
-
Notifications
You must be signed in to change notification settings - Fork 306
Expand file tree
/
Copy pathraw_hash_set_test.cc
More file actions
1988 lines (1729 loc) · 58.9 KB
/
raw_hash_set_test.cc
File metadata and controls
1988 lines (1729 loc) · 58.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// define this so that the "IterationOrderChanges" tests pass
#define PHMAP_NON_DETERMINISTIC 1
#include "parallel_hashmap/phmap.h"
//#include "container_memory.h"
//#include "hash_function_defaults.h"
#include "hash_policy_testing.h"
#include "hashtable_debug.h"
#include <cmath>
#include <cstdint>
#include <deque>
#include <functional>
#include <memory>
#include <numeric>
#include <random>
#include <string>
#ifdef _MSC_VER
#pragma warning(disable : 4018 4244 4702)
#endif // _MSC_VER
#if PHMAP_HAVE_STD_STRING_VIEW
#include <string_view>
#endif
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace phmap {
namespace priv {
struct RawHashSetTestOnlyAccess {
template <typename C>
static auto GetSlots(const C& c) -> decltype(c.slots_) {
return c.slots_;
}
};
namespace {
using ::testing::DoubleNear;
using ::testing::ElementsAre;
using ::testing::Ge;
using ::testing::Lt;
using ::testing::Optional;
using ::testing::Pair;
using ::testing::UnorderedElementsAre;
TEST(Util, NormalizeCapacity) {
EXPECT_EQ(1, NormalizeCapacity(0));
EXPECT_EQ(1, NormalizeCapacity(1));
EXPECT_EQ(3, NormalizeCapacity(2));
EXPECT_EQ(3, NormalizeCapacity(3));
EXPECT_EQ(7, NormalizeCapacity(4));
EXPECT_EQ(7, NormalizeCapacity(7));
EXPECT_EQ(15, NormalizeCapacity(8));
EXPECT_EQ(15, NormalizeCapacity(15));
EXPECT_EQ(15 * 2 + 1, NormalizeCapacity(15 + 1));
EXPECT_EQ(15 * 2 + 1, NormalizeCapacity(15 + 2));
}
TEST(Util, GrowthAndCapacity) {
// Verify that GrowthToCapacity gives the minimum capacity that has enough
// growth.
for (size_t growth = 0; growth < 10000; ++growth) {
SCOPED_TRACE(growth);
size_t capacity = NormalizeCapacity(GrowthToLowerboundCapacity(growth));
// The capacity is large enough for `growth`
EXPECT_THAT(CapacityToGrowth(capacity), Ge(growth));
if (growth != 0 && capacity > 1) {
// There is no smaller capacity that works.
EXPECT_THAT(CapacityToGrowth(capacity / 2), Lt(growth));
}
}
for (size_t capacity = Group::kWidth - 1; capacity < 10000;
capacity = 2 * capacity + 1) {
SCOPED_TRACE(capacity);
size_t growth = CapacityToGrowth(capacity);
EXPECT_THAT(growth, Lt(capacity));
EXPECT_LE(GrowthToLowerboundCapacity(growth), capacity);
EXPECT_EQ(NormalizeCapacity(GrowthToLowerboundCapacity(growth)), capacity);
}
}
TEST(Util, probe_seq) {
probe_seq<16> seq(0, 127);
auto gen = [&]() {
size_t res = seq.offset();
seq.next();
return res;
};
std::vector<size_t> offsets(8);
std::generate_n(offsets.begin(), 8, gen);
EXPECT_THAT(offsets, ElementsAre(0, 16, 48, 96, 32, 112, 80, 64));
seq = probe_seq<16>(128, 127);
std::generate_n(offsets.begin(), 8, gen);
EXPECT_THAT(offsets, ElementsAre(0, 16, 48, 96, 32, 112, 80, 64));
}
TEST(BitMask, Smoke) {
EXPECT_FALSE((BitMask<uint8_t, 8>(0)));
EXPECT_TRUE((BitMask<uint8_t, 8>(5)));
EXPECT_THAT((BitMask<uint8_t, 8>(0)), ElementsAre());
EXPECT_THAT((BitMask<uint8_t, 8>(0x1)), ElementsAre(0));
EXPECT_THAT((BitMask<uint8_t, 8>(0x2)), ElementsAre(1));
EXPECT_THAT((BitMask<uint8_t, 8>(0x3)), ElementsAre(0, 1));
EXPECT_THAT((BitMask<uint8_t, 8>(0x4)), ElementsAre(2));
EXPECT_THAT((BitMask<uint8_t, 8>(0x5)), ElementsAre(0, 2));
EXPECT_THAT((BitMask<uint8_t, 8>(0x55)), ElementsAre(0, 2, 4, 6));
EXPECT_THAT((BitMask<uint8_t, 8>(0xAA)), ElementsAre(1, 3, 5, 7));
}
TEST(BitMask, WithShift) {
// See the non-SSE version of Group for details on what this math is for.
uint64_t ctrl = 0x1716151413121110;
uint64_t hash = 0x12;
constexpr uint64_t msbs = 0x8080808080808080ULL;
constexpr uint64_t lsbs = 0x0101010101010101ULL;
auto x = ctrl ^ (lsbs * hash);
uint64_t mask = (x - lsbs) & ~x & msbs;
EXPECT_EQ(0x0000000080800000, mask);
BitMask<uint64_t, 8, 3> b(mask);
EXPECT_EQ(*b, 2u);
}
TEST(BitMask, LeadingTrailing) {
EXPECT_EQ((BitMask<uint32_t, 16>(0x00001a40).LeadingZeros()), 3u);
EXPECT_EQ((BitMask<uint32_t, 16>(0x00001a40).TrailingZeros()), 6u);
EXPECT_EQ((BitMask<uint32_t, 16>(0x00000001).LeadingZeros()), 15u);
EXPECT_EQ((BitMask<uint32_t, 16>(0x00000001).TrailingZeros()), 0u);
EXPECT_EQ((BitMask<uint32_t, 16>(0x00008000).LeadingZeros()), 0u);
EXPECT_EQ((BitMask<uint32_t, 16>(0x00008000).TrailingZeros()), 15u);
EXPECT_EQ((BitMask<uint64_t, 8, 3>(0x0000008080808000).LeadingZeros()), 3u);
EXPECT_EQ((BitMask<uint64_t, 8, 3>(0x0000008080808000).TrailingZeros()), 1u);
EXPECT_EQ((BitMask<uint64_t, 8, 3>(0x0000000000000080).LeadingZeros()), 7u);
EXPECT_EQ((BitMask<uint64_t, 8, 3>(0x0000000000000080).TrailingZeros()), 0u);
EXPECT_EQ((BitMask<uint64_t, 8, 3>(0x8000000000000000).LeadingZeros()), 0u);
EXPECT_EQ((BitMask<uint64_t, 8, 3>(0x8000000000000000).TrailingZeros()), 7u);
}
TEST(Group, EmptyGroup) {
for (h2_t h = 0; h != 128; ++h) EXPECT_FALSE(Group{EmptyGroup()}.Match(h));
}
TEST(Group, Match) {
PHMAP_IF_CONSTEXPR (Group::kWidth == 32) {
// 0 1 2 3 4 5 6 7
ctrl_t group[] = {kEmpty, 1, kDeleted, 3, kEmpty, 5, kSentinel, 7,
7, 5, 3, 1, 1, 1, 1, 1,
7, 5, 3, 1, 1, 1, 1, 1,
7, 5, 3, 1, 1, 1, 1, 1};
EXPECT_THAT(Group{group}.Match(0), ElementsAre());
EXPECT_THAT(Group{group}.Match(1), ElementsAre(1,
11, 12, 13, 14, 15,
19, 20, 21, 22, 23,
27, 28, 29, 30, 31));
EXPECT_THAT(Group{group}.Match(3), ElementsAre(3, 10, 18, 26));
EXPECT_THAT(Group{group}.Match(5), ElementsAre(5, 9, 17, 25));
EXPECT_THAT(Group{group}.Match(7), ElementsAre(7, 8, 16, 24));
} else PHMAP_IF_CONSTEXPR (Group::kWidth == 16) {
ctrl_t group[] = {kEmpty, 1, kDeleted, 3, kEmpty, 5, kSentinel, 7,
7, 5, 3, 1, 1, 1, 1, 1};
EXPECT_THAT(Group{group}.Match(0), ElementsAre());
EXPECT_THAT(Group{group}.Match(1), ElementsAre(1, 11, 12, 13, 14, 15));
EXPECT_THAT(Group{group}.Match(3), ElementsAre(3, 10));
EXPECT_THAT(Group{group}.Match(5), ElementsAre(5, 9));
EXPECT_THAT(Group{group}.Match(7), ElementsAre(7, 8));
} else PHMAP_IF_CONSTEXPR (Group::kWidth == 8) {
ctrl_t group[] = {kEmpty, 1, 2, kDeleted, 2, 1, kSentinel, 1};
EXPECT_THAT(Group{group}.Match(0), ElementsAre());
EXPECT_THAT(Group{group}.Match(1), ElementsAre(1, 5, 7));
EXPECT_THAT(Group{group}.Match(2), ElementsAre(2, 4));
} else {
FAIL() << "No test coverage for Group::kWidth==" << Group::kWidth;
}
}
TEST(Group, MatchEmpty) {
PHMAP_IF_CONSTEXPR (Group::kWidth == 32) {
ctrl_t group[] = {kEmpty, 1, kDeleted, 3, kEmpty, 5, kSentinel, 7,
7, 5, 3, 1, 1, 1, 1, 1,
kEmpty, 1, kDeleted, 3, kEmpty, 5, kSentinel, 7,
7, 5, 3, 1, 1, 1, 1, 1};
EXPECT_THAT(Group{group}.MatchEmpty(), ElementsAre(0, 4, 16, 20));
} else PHMAP_IF_CONSTEXPR (Group::kWidth == 16) {
ctrl_t group[] = {kEmpty, 1, kDeleted, 3, kEmpty, 5, kSentinel, 7,
7, 5, 3, 1, 1, 1, 1, 1};
EXPECT_THAT(Group{group}.MatchEmpty(), ElementsAre(0, 4));
} else PHMAP_IF_CONSTEXPR (Group::kWidth == 8) {
ctrl_t group[] = {kEmpty, 1, 2, kDeleted, 2, 1, kSentinel, 1};
EXPECT_THAT(Group{group}.MatchEmpty(), ElementsAre(0));
} else {
FAIL() << "No test coverage for Group::kWidth==" << Group::kWidth;
}
}
TEST(Group, MatchEmptyOrDeleted) {
PHMAP_IF_CONSTEXPR (Group::kWidth == 32) {
ctrl_t group[] = {kEmpty, 1, kDeleted, 3, kEmpty, 5, kSentinel, 7,
7, 5, 3, 1, 1, 1, 1, 1,
kEmpty, 1, kDeleted, 3, kEmpty, 5, kSentinel, 7,
7, 5, 3, 1, 1, 1, 1, 1};
EXPECT_THAT(Group{group}.MatchEmptyOrDeleted(), ElementsAre(0, 2, 4, 16, 18, 20));
} else PHMAP_IF_CONSTEXPR (Group::kWidth == 16) {
ctrl_t group[] = {kEmpty, 1, kDeleted, 3, kEmpty, 5, kSentinel, 7,
7, 5, 3, 1, 1, 1, 1, 1};
EXPECT_THAT(Group{group}.MatchEmptyOrDeleted(), ElementsAre(0, 2, 4));
} else PHMAP_IF_CONSTEXPR (Group::kWidth == 8) {
ctrl_t group[] = {kEmpty, 1, 2, kDeleted, 2, 1, kSentinel, 1};
EXPECT_THAT(Group{group}.MatchEmptyOrDeleted(), ElementsAre(0, 3));
} else {
FAIL() << "No test coverage for Group::kWidth==" << Group::kWidth;
}
}
TEST(Batch, DropDeletes) {
constexpr size_t kCapacity = 63;
constexpr size_t kGroupWidth = priv::Group::kWidth;
std::vector<ctrl_t> ctrl(kCapacity + 1 + kGroupWidth);
ctrl[kCapacity] = kSentinel;
std::vector<ctrl_t> pattern = {kEmpty, 2, kDeleted, 2, kEmpty, 1, kDeleted};
for (size_t i = 0; i != kCapacity; ++i) {
ctrl[i] = pattern[i % pattern.size()];
if (i < kGroupWidth - 1)
ctrl[i + kCapacity + 1] = pattern[i % pattern.size()];
}
ConvertDeletedToEmptyAndFullToDeleted(ctrl.data(), kCapacity);
ASSERT_EQ(ctrl[kCapacity], kSentinel);
for (size_t i = 0; i < kCapacity + 1 + kGroupWidth; ++i) {
ctrl_t expected = pattern[i % (kCapacity + 1) % pattern.size()];
if (i == kCapacity) expected = kSentinel;
if (expected == kDeleted) expected = kEmpty;
if (IsFull(expected)) expected = kDeleted;
EXPECT_EQ(ctrl[i], expected)
<< i << " " << int{pattern[i % pattern.size()]};
}
}
TEST(Group, CountLeadingEmptyOrDeleted) {
const std::vector<ctrl_t> empty_examples = {kEmpty, kDeleted};
const std::vector<ctrl_t> full_examples = {0, 1, 2, 3, 5, 9, 127, kSentinel};
for (ctrl_t empty : empty_examples) {
std::vector<ctrl_t> e(Group::kWidth, empty);
EXPECT_EQ(Group::kWidth, (int)Group{e.data()}.CountLeadingEmptyOrDeleted());
for (ctrl_t full : full_examples) {
for (size_t i = 0; i != Group::kWidth; ++i) {
std::vector<ctrl_t> f(Group::kWidth, empty);
f[i] = full;
EXPECT_EQ(i, Group{f.data()}.CountLeadingEmptyOrDeleted());
}
std::vector<ctrl_t> f(Group::kWidth, empty);
f[Group::kWidth * 2 / 3] = full;
f[Group::kWidth / 2] = full;
EXPECT_EQ(
Group::kWidth / 2, (int)Group{f.data()}.CountLeadingEmptyOrDeleted());
}
}
}
struct IntPolicy {
using slot_type = int64_t;
using key_type = int64_t;
using init_type = int64_t;
static void construct(void*, int64_t* slot, int64_t v) { *slot = v; }
static void destroy(void*, int64_t*) {}
static void transfer(void*, int64_t* new_slot, int64_t* old_slot) {
*new_slot = *old_slot;
}
static int64_t& element(slot_type* slot) { return *slot; }
template <class F>
static auto apply(F&& f, int64_t x) -> decltype(std::forward<F>(f)(x, x)) {
return std::forward<F>(f)(x, x);
}
};
#if PHMAP_HAVE_STD_STRING_VIEW
class StringPolicy {
template <class F, class K, class V,
class = typename std::enable_if<
std::is_convertible<const K&, std::string_view>::value>::type>
decltype(std::declval<F>()(
std::declval<const std::string_view&>(), std::piecewise_construct,
std::declval<std::tuple<K>>(),
std::declval<V>())) static apply_impl(F&& f,
std::pair<std::tuple<K>, V> p) {
const std::string_view& key = std::get<0>(p.first);
return std::forward<F>(f)(key, std::piecewise_construct, std::move(p.first),
std::move(p.second));
}
public:
struct slot_type {
struct ctor {};
template <class... Ts>
slot_type(ctor, Ts&&... ts) : pair(std::forward<Ts>(ts)...) {}
std::pair<std::string, std::string> pair;
};
using key_type = std::string;
using init_type = std::pair<std::string, std::string>;
template <class allocator_type, class... Args>
static void construct(allocator_type* alloc, slot_type* slot, Args... args) {
std::allocator_traits<allocator_type>::construct(
*alloc, slot, typename slot_type::ctor(), std::forward<Args>(args)...);
}
template <class allocator_type>
static void destroy(allocator_type* alloc, slot_type* slot) {
std::allocator_traits<allocator_type>::destroy(*alloc, slot);
}
template <class allocator_type>
static void transfer(allocator_type* alloc, slot_type* new_slot,
slot_type* old_slot) {
construct(alloc, new_slot, std::move(old_slot->pair));
destroy(alloc, old_slot);
}
static std::pair<std::string, std::string>& element(slot_type* slot) {
return slot->pair;
}
template <class F, class... Args>
static auto apply(F&& f, Args&&... args)
-> decltype(apply_impl(std::forward<F>(f),
PairArgs(std::forward<Args>(args)...))) {
return apply_impl(std::forward<F>(f),
PairArgs(std::forward<Args>(args)...));
}
};
struct StringHash : phmap::Hash<std::string_view> {
using is_transparent = void;
};
struct StringEq : std::equal_to<std::string_view> {
using is_transparent = void;
};
struct StringTable
: raw_hash_set<StringPolicy, StringHash, StringEq, std::allocator<int>> {
using Base = typename StringTable::raw_hash_set;
StringTable() {}
using Base::Base;
};
#endif
struct IntTable
: raw_hash_set<IntPolicy, priv::hash_default_hash<int64_t>,
std::equal_to<int64_t>, std::allocator<int64_t>> {
using Base = typename IntTable::raw_hash_set;
IntTable() {}
using Base::Base;
};
template <typename T>
struct CustomAlloc : std::allocator<T> {
CustomAlloc() {}
template <typename U>
CustomAlloc(const CustomAlloc<U>& ) {}
template<class U> struct rebind {
using other = CustomAlloc<U>;
};
};
struct CustomAllocIntTable
: raw_hash_set<IntPolicy, priv::hash_default_hash<int64_t>,
std::equal_to<int64_t>, CustomAlloc<int64_t>> {
using Base = typename CustomAllocIntTable::raw_hash_set;
using Base::Base;
};
struct BadFastHash {
template <class T>
size_t operator()(const T&) const {
return 0;
}
};
struct BadTable : raw_hash_set<IntPolicy, BadFastHash, std::equal_to<int>,
std::allocator<int>> {
using Base = typename BadTable::raw_hash_set;
BadTable() {}
using Base::Base;
};
#if PHMAP_HAVE_STD_STRING_VIEW
TEST(Table, EmptyFunctorOptimization) {
static_assert(std::is_empty<std::equal_to<std::string_view>>::value, "");
static_assert(std::is_empty<std::allocator<int>>::value, "");
struct MockTable {
void* ctrl;
void* slots;
size_t size;
size_t capacity;
size_t growth_left;
void* infoz;
};
struct StatelessHash {
size_t operator()(std::string_view) const { return 0; }
};
struct StatefulHash : StatelessHash {
size_t dummy;
};
EXPECT_EQ(
sizeof(MockTable),
sizeof(
raw_hash_set<StringPolicy, StatelessHash,
std::equal_to<std::string_view>, std::allocator<int>>));
EXPECT_EQ(
sizeof(MockTable) + sizeof(StatefulHash),
sizeof(
raw_hash_set<StringPolicy, StatefulHash,
std::equal_to<std::string_view>, std::allocator<int>>));
}
#endif
TEST(Table, Empty) {
IntTable t;
EXPECT_EQ(0, t.size());
EXPECT_TRUE(t.empty());
}
#ifdef __GNUC__
template <class T>
PHMAP_ATTRIBUTE_ALWAYS_INLINE inline void DoNotOptimize(const T& v) {
asm volatile("" : : "r,m"(v) : "memory");
}
#endif
TEST(Table, Prefetch) {
IntTable t;
t.emplace(1);
// Works for both present and absent keys.
t.prefetch(1);
t.prefetch(2);
// Do not run in debug mode, when prefetch is not implemented, or when
// sanitizers are enabled.
#if 0 && defined(NDEBUG) && defined(__GNUC__) && defined(__x86_64__) && \
!defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER) && \
!defined(THREAD_SANITIZER) && !defined(UNDEFINED_BEHAVIOR_SANITIZER)&& \
!defined(__EMSCRIPTEN__)
const auto now = [] { return phmap::base_internal::CycleClock::Now(); };
// Make size enough to not fit in L2 cache (16.7 Mb)
static constexpr int size = 1 << 22;
for (int i = 0; i < size; ++i) t.insert(i);
int64_t no_prefetch = 0, prefetch = 0;
for (int iter = 0; iter < 10; ++iter) {
int64_t time = now();
for (int i = 0; i < size; ++i) {
DoNotOptimize(t.find(i));
}
no_prefetch += now() - time;
time = now();
for (int i = 0; i < size; ++i) {
t.prefetch(i + 20);
DoNotOptimize(t.find(i));
}
prefetch += now() - time;
}
// no_prefetch is at least 30% slower.
EXPECT_GE(1.0 * no_prefetch / prefetch, 1.3);
#endif
}
TEST(Table, LookupEmpty) {
IntTable t;
auto it = t.find(0);
EXPECT_TRUE(it == t.end());
}
TEST(Table, Insert1) {
IntTable t;
EXPECT_TRUE(t.find(0) == t.end());
auto res = t.emplace(0);
EXPECT_TRUE(res.second);
EXPECT_THAT(*res.first, 0);
EXPECT_EQ(1, t.size());
EXPECT_THAT(*t.find(0), 0);
}
TEST(Table, Insert2) {
IntTable t;
EXPECT_TRUE(t.find(0) == t.end());
auto res = t.emplace(0);
EXPECT_TRUE(res.second);
EXPECT_THAT(*res.first, 0);
EXPECT_EQ(1, t.size());
EXPECT_TRUE(t.find(1) == t.end());
res = t.emplace(1);
EXPECT_TRUE(res.second);
EXPECT_THAT(*res.first, 1);
EXPECT_EQ(2, t.size());
EXPECT_THAT(*t.find(0), 0);
EXPECT_THAT(*t.find(1), 1);
}
TEST(Table, InsertCollision) {
BadTable t;
EXPECT_TRUE(t.find(1) == t.end());
auto res = t.emplace(1);
EXPECT_TRUE(res.second);
EXPECT_THAT(*res.first, 1);
EXPECT_EQ(1, t.size());
EXPECT_TRUE(t.find(2) == t.end());
res = t.emplace(2);
EXPECT_THAT(*res.first, 2);
EXPECT_TRUE(res.second);
EXPECT_EQ(2, t.size());
EXPECT_THAT(*t.find(1), 1);
EXPECT_THAT(*t.find(2), 2);
}
// Test that we do not add existent element in case we need to search through
// many groups with deleted elements
TEST(Table, InsertCollisionAndFindAfterDelete) {
BadTable t; // all elements go to the same group.
// Have at least 2 groups with Group::kWidth collisions
// plus some extra collisions in the last group.
constexpr size_t kNumInserts = Group::kWidth * 2 + 5;
for (size_t i = 0; i < kNumInserts; ++i) {
auto res = t.emplace(i);
EXPECT_TRUE(res.second);
EXPECT_THAT(*res.first, i);
EXPECT_EQ(i + 1, t.size());
}
// Remove elements one by one and check
// that we still can find all other elements.
for (size_t i = 0; i < kNumInserts; ++i) {
EXPECT_EQ(1, t.erase(i)) << i;
for (size_t j = i + 1; j < kNumInserts; ++j) {
EXPECT_THAT(*t.find(j), j);
auto res = t.emplace(j);
EXPECT_FALSE(res.second) << i << " " << j;
EXPECT_THAT(*res.first, j);
EXPECT_EQ(kNumInserts - i - 1, t.size());
}
}
EXPECT_TRUE(t.empty());
}
#if PHMAP_HAVE_STD_STRING_VIEW
TEST(Table, LazyEmplace) {
StringTable t;
bool called = false;
auto it = t.lazy_emplace("abc", [&](const StringTable::constructor& f) {
called = true;
f("abc", "ABC");
});
EXPECT_TRUE(called);
EXPECT_THAT(*it, Pair("abc", "ABC"));
called = false;
it = t.lazy_emplace("abc", [&](const StringTable::constructor& f) {
called = true;
f("abc", "DEF");
});
EXPECT_FALSE(called);
EXPECT_THAT(*it, Pair("abc", "ABC"));
}
#endif
TEST(Table, ContainsEmpty) {
IntTable t;
EXPECT_FALSE(t.contains(0));
}
TEST(Table, Contains1) {
IntTable t;
EXPECT_TRUE(t.insert(0).second);
EXPECT_TRUE(t.contains(0));
EXPECT_FALSE(t.contains(1));
EXPECT_EQ(1, t.erase(0));
EXPECT_FALSE(t.contains(0));
}
TEST(Table, Contains2) {
IntTable t;
EXPECT_TRUE(t.insert(0).second);
EXPECT_TRUE(t.contains(0));
EXPECT_FALSE(t.contains(1));
t.clear();
EXPECT_FALSE(t.contains(0));
}
int decompose_constructed;
struct DecomposeType {
DecomposeType(int i_) : i(i_) { // NOLINT
++decompose_constructed;
}
explicit DecomposeType(const char* d) : DecomposeType(*d) {}
int i;
};
struct DecomposeHash {
using is_transparent = void;
size_t operator()(DecomposeType a) const { return a.i; }
size_t operator()(int a) const { return a; }
size_t operator()(const char* a) const { return *a; }
};
struct DecomposeEq {
using is_transparent = void;
bool operator()(DecomposeType a, DecomposeType b) const { return a.i == b.i; }
bool operator()(DecomposeType a, int b) const { return a.i == b; }
bool operator()(DecomposeType a, const char* b) const { return a.i == *b; }
};
struct DecomposePolicy {
using slot_type = DecomposeType;
using key_type = DecomposeType;
using init_type = DecomposeType;
template <typename T>
static void construct(void*, DecomposeType* slot, T&& v) {
*slot = DecomposeType(std::forward<T>(v));
}
static void destroy(void*, DecomposeType*) {}
static DecomposeType& element(slot_type* slot) { return *slot; }
template <class F, class T>
static auto apply(F&& f, const T& x) -> decltype(std::forward<F>(f)(x, x)) {
return std::forward<F>(f)(x, x);
}
};
template <typename Hash, typename Eq>
void TestDecompose(bool construct_three) {
DecomposeType elem{0};
const int one = 1;
const char* three_p = "3";
const auto& three = three_p;
raw_hash_set<DecomposePolicy, Hash, Eq, std::allocator<int>> set1;
decompose_constructed = 0;
int expected_constructed = 0;
EXPECT_EQ(expected_constructed, decompose_constructed);
set1.insert(elem);
EXPECT_EQ(expected_constructed, decompose_constructed);
set1.insert(1);
EXPECT_EQ(++expected_constructed, decompose_constructed);
set1.emplace("3");
EXPECT_EQ(++expected_constructed, decompose_constructed);
EXPECT_EQ(expected_constructed, decompose_constructed);
{ // insert(T&&)
set1.insert(1);
EXPECT_EQ(expected_constructed, decompose_constructed);
}
{ // insert(const T&)
set1.insert(one);
EXPECT_EQ(expected_constructed, decompose_constructed);
}
{ // insert(hint, T&&)
set1.insert(set1.begin(), 1);
EXPECT_EQ(expected_constructed, decompose_constructed);
}
{ // insert(hint, const T&)
set1.insert(set1.begin(), one);
EXPECT_EQ(expected_constructed, decompose_constructed);
}
{ // emplace(...)
set1.emplace(1);
EXPECT_EQ(expected_constructed, decompose_constructed);
set1.emplace("3");
expected_constructed += construct_three;
EXPECT_EQ(expected_constructed, decompose_constructed);
set1.emplace(one);
EXPECT_EQ(expected_constructed, decompose_constructed);
set1.emplace(three);
expected_constructed += construct_three;
EXPECT_EQ(expected_constructed, decompose_constructed);
}
{ // emplace_hint(...)
set1.emplace_hint(set1.begin(), 1);
EXPECT_EQ(expected_constructed, decompose_constructed);
set1.emplace_hint(set1.begin(), "3");
expected_constructed += construct_three;
EXPECT_EQ(expected_constructed, decompose_constructed);
set1.emplace_hint(set1.begin(), one);
EXPECT_EQ(expected_constructed, decompose_constructed);
set1.emplace_hint(set1.begin(), three);
expected_constructed += construct_three;
EXPECT_EQ(expected_constructed, decompose_constructed);
}
}
TEST(Table, Decompose) {
TestDecompose<DecomposeHash, DecomposeEq>(false);
struct TransparentHashIntOverload {
size_t operator()(DecomposeType a) const { return a.i; }
size_t operator()(int a) const { return a; }
};
struct TransparentEqIntOverload {
bool operator()(DecomposeType a, DecomposeType b) const {
return a.i == b.i;
}
bool operator()(DecomposeType a, int b) const { return a.i == b; }
};
TestDecompose<TransparentHashIntOverload, DecomposeEq>(true);
TestDecompose<TransparentHashIntOverload, TransparentEqIntOverload>(true);
TestDecompose<DecomposeHash, TransparentEqIntOverload>(true);
}
// Returns the largest m such that a table with m elements has the same number
// of buckets as a table with n elements.
size_t MaxDensitySize(size_t n) {
IntTable t;
t.reserve(n);
for (size_t i = 0; i != n; ++i) t.emplace(i);
const size_t c = t.bucket_count();
while (c == t.bucket_count()) t.emplace(n++);
return t.size() - 1;
}
#if 0
struct Modulo1000Hash {
size_t operator()(int x) const { return x % 1000; }
};
struct Modulo1000HashTable
: public raw_hash_set<IntPolicy, Modulo1000Hash, std::equal_to<int>,
std::allocator<int>> {};
// Test that rehash with no resize happen in case of many deleted slots.
TEST(Table, RehashWithNoResize) {
Modulo1000HashTable t;
// Adding the same length (and the same hash) strings
// to have at least kMinFullGroups groups
// with Group::kWidth collisions. Then fill up to MaxDensitySize;
const size_t kMinFullGroups = 7;
std::vector<int> keys;
for (size_t i = 0; i < MaxDensitySize(Group::kWidth * kMinFullGroups); ++i) {
int k = (int)i * 1000;
t.emplace(k);
keys.push_back(k);
}
const size_t capacity = t.capacity();
// Remove elements from all groups except the first and the last one.
// All elements removed from full groups will be marked as kDeleted.
const size_t erase_begin = Group::kWidth / 2;
const size_t erase_end = (t.size() / Group::kWidth - 1) * Group::kWidth;
for (size_t i = erase_begin; i < erase_end; ++i) {
EXPECT_EQ(1, t.erase(keys[i])) << i;
}
keys.erase(keys.begin() + erase_begin, keys.begin() + erase_end);
auto last_key = keys.back();
size_t last_key_num_probes = GetHashtableDebugNumProbes(t, last_key);
// Make sure that we have to make a lot of probes for last key.
ASSERT_GT(last_key_num_probes, kMinFullGroups);
int x = 1;
// Insert and erase one element, before inplace rehash happen.
while (last_key_num_probes == GetHashtableDebugNumProbes(t, last_key)) {
t.emplace(x);
ASSERT_EQ(capacity, t.capacity());
// All elements should be there.
ASSERT_TRUE(t.find(x) != t.end()) << x;
for (const auto& k : keys) {
ASSERT_TRUE(t.find(k) != t.end()) << k;
}
t.erase(x);
++x;
}
}
#endif
TEST(Table, InsertEraseStressTest) {
IntTable t;
const size_t kMinElementCount = 250;
std::deque<size_t> keys;
size_t i = 0;
for (; i < MaxDensitySize(kMinElementCount); ++i) {
t.emplace(i);
keys.push_back(i);
}
const size_t kNumIterations = 1000000;
for (; i < kNumIterations; ++i) {
ASSERT_EQ(1, t.erase(keys.front()));
keys.pop_front();
t.emplace(i);
keys.push_back(i);
}
}
#if PHMAP_HAVE_STD_STRING_VIEW
TEST(Table, InsertOverloads) {
StringTable t;
// These should all trigger the insert(init_type) overload.
t.insert({{}, {}});
t.insert({"ABC", {}});
t.insert({"DEF", "!!!"});
EXPECT_THAT(t, UnorderedElementsAre(Pair("", ""), Pair("ABC", ""),
Pair("DEF", "!!!")));
}
#endif
TEST(Table, LargeTable) {
IntTable t;
for (int64_t i = 0; i != 100000; ++i) t.emplace(i << 40);
for (int64_t i = 0; i != 100000; ++i) ASSERT_EQ(i << 40, *t.find(i << 40));
}
// Timeout if copy is quadratic as it was in Rust.
TEST(Table, EnsureNonQuadraticAsInRust) {
static const size_t kLargeSize = 1 << 15;
IntTable t;
for (size_t i = 0; i != kLargeSize; ++i) {
t.insert(i);
}
// If this is quadratic, the test will timeout.
IntTable t2;
for (const auto& entry : t) t2.insert(entry);
}
TEST(Table, ClearBug) {
IntTable t;
constexpr size_t capacity = priv::Group::kWidth - 1;
constexpr size_t max_size = capacity / 2 + 1;
for (size_t i = 0; i < max_size; ++i) {
t.insert(i);
}
ASSERT_EQ(capacity, t.capacity());
intptr_t original = reinterpret_cast<intptr_t>(&*t.find(2));
t.clear();
ASSERT_EQ(capacity, t.capacity());
for (size_t i = 0; i < max_size; ++i) {
t.insert(i);
}
ASSERT_EQ(capacity, t.capacity());
intptr_t second = reinterpret_cast<intptr_t>(&*t.find(2));
// We are checking that original and second are close enough to each other
// that they are probably still in the same group. This is not strictly
// guaranteed.
EXPECT_LT(std::abs(original - second),
capacity * sizeof(IntTable::value_type));
}
TEST(Table, Erase) {
IntTable t;
EXPECT_TRUE(t.find(0) == t.end());
auto res = t.emplace(0);
EXPECT_TRUE(res.second);
EXPECT_EQ(1, t.size());
t.erase(res.first);
EXPECT_EQ(0, t.size());
EXPECT_TRUE(t.find(0) == t.end());
}
TEST(Table, EraseMaintainsValidIterator) {
IntTable t;
const int kNumElements = 100;
for (int i = 0; i < kNumElements; i ++) {
EXPECT_TRUE(t.emplace(i).second);
}
EXPECT_EQ(t.size(), kNumElements);
int num_erase_calls = 0;
auto it = t.begin();
while (it != t.end()) {
t.erase(it++);
num_erase_calls++;
}
EXPECT_TRUE(t.empty());
EXPECT_EQ(num_erase_calls, kNumElements);
}
// Collect N bad keys by following algorithm:
// 1. Create an empty table and reserve it to 2 * N.
// 2. Insert N random elements.
// 3. Take first Group::kWidth - 1 to bad_keys array.
// 4. Clear the table without resize.
// 5. Go to point 2 while N keys not collected
std::vector<int64_t> CollectBadMergeKeys(size_t N) {
static constexpr int kGroupSize = Group::kWidth - 1;
auto topk_range = [](size_t b, size_t e, IntTable* t) -> std::vector<int64_t> {
for (size_t i = b; i != e; ++i) {
t->emplace(i);
}
std::vector<int64_t> res;
res.reserve(kGroupSize);
auto it = t->begin();
for (size_t i = b; i != e && i != b + kGroupSize; ++i, ++it) {
res.push_back(*it);
}
return res;
};
std::vector<int64_t> bad_keys;
bad_keys.reserve(N);
IntTable t;
t.reserve(N * 2);
for (size_t b = 0; bad_keys.size() < N; b += N) {
auto keys = topk_range(b, b + N, &t);
bad_keys.insert(bad_keys.end(), keys.begin(), keys.end());
t.erase(t.begin(), t.end());
EXPECT_TRUE(t.empty());
}
return bad_keys;
}
struct ProbeStats {
// Number of elements with specific probe length over all tested tables.
std::vector<size_t> all_probes_histogram;
// Ratios total_probe_length/size for every tested table.
std::vector<double> single_table_ratios;
friend ProbeStats operator+(const ProbeStats& a, const ProbeStats& b) {
ProbeStats res = a;
res.all_probes_histogram.resize(std::max(res.all_probes_histogram.size(),
b.all_probes_histogram.size()));
std::transform(b.all_probes_histogram.begin(), b.all_probes_histogram.end(),
res.all_probes_histogram.begin(),
res.all_probes_histogram.begin(), std::plus<size_t>());
res.single_table_ratios.insert(res.single_table_ratios.end(),
b.single_table_ratios.begin(),
b.single_table_ratios.end());
return res;
}
// Average ratio total_probe_length/size over tables.
double AvgRatio() const {
return std::accumulate(single_table_ratios.begin(),
single_table_ratios.end(), 0.0) /
single_table_ratios.size();
}
// Maximum ratio total_probe_length/size over tables.
double MaxRatio() const {
return *std::max_element(single_table_ratios.begin(),
single_table_ratios.end());
}
// Percentile ratio total_probe_length/size over tables.
double PercentileRatio(double Percentile = 0.95) const {
auto r = single_table_ratios;