-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathHashSet.cpp
13482 lines (13018 loc) · 444 KB
/
HashSet.cpp
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 (C) 2005-2017 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#define NDEBUG 1
#include <algorithm>
#include <memory>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
// Compile with: xcrun clang++ -o HashSet HashSet.cpp -O2 -W -framework Foundation -licucore -std=c++11 -fvisibility=hidden -DNDEBUG=1
// Or for wasm: em++ -o HashSet.js -o HashSet.html HashSet.cpp -O2 -W -std=c++11 -DNDEBUG=1 -g1 -s WASM=1 -s TOTAL_MEMORY=52428800
#define ALWAYS_INLINE inline __attribute__((__always_inline__))
#define WTFMove(value) std::move(value)
#define ASSERT(exp) do { } while(0)
#define ASSERT_UNUSED(var, exp) do { (void)(var); } while(0)
#define RELEASE_ASSERT(exp) do { \
if (!(exp)) { \
fprintf(stderr, "%s:%d: assertion failed: %s\n", __FILE__, __LINE__, #exp); \
abort(); \
} \
} while(0)
#define ASSERT_ENABLED 0
#define DUMP_HASHTABLE_STATS 0
#define DUMP_HASHTABLE_STATS_PER_TABLE 0
// This version of placement new omits a 0 check.
enum NotNullTag { NotNull };
inline void* operator new(size_t, NotNullTag, void* location)
{
ASSERT(location);
return location;
}
namespace WTF {
inline uint32_t roundUpToPowerOfTwo(uint32_t v)
{
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
/*
* C++'s idea of a reinterpret_cast lacks sufficient cojones.
*/
template<typename ToType, typename FromType>
inline ToType bitwise_cast(FromType from)
{
typename std::remove_const<ToType>::type to { };
std::memcpy(&to, &from, sizeof(to));
return to;
}
enum HashTableDeletedValueType { HashTableDeletedValue };
enum HashTableEmptyValueType { HashTableEmptyValue };
template <typename T> inline T* getPtr(T* p) { return p; }
template <typename T> struct IsSmartPtr {
static const bool value = false;
};
template <typename T, bool isSmartPtr>
struct GetPtrHelperBase;
template <typename T>
struct GetPtrHelperBase<T, false /* isSmartPtr */> {
typedef T* PtrType;
static T* getPtr(T& p) { return std::addressof(p); }
};
template <typename T>
struct GetPtrHelperBase<T, true /* isSmartPtr */> {
typedef typename T::PtrType PtrType;
static PtrType getPtr(const T& p) { return p.get(); }
};
template <typename T>
struct GetPtrHelper : GetPtrHelperBase<T, IsSmartPtr<T>::value> {
};
template <typename T>
inline typename GetPtrHelper<T>::PtrType getPtr(T& p)
{
return GetPtrHelper<T>::getPtr(p);
}
template <typename T>
inline typename GetPtrHelper<T>::PtrType getPtr(const T& p)
{
return GetPtrHelper<T>::getPtr(p);
}
// Explicit specialization for C++ standard library types.
template <typename T, typename Deleter> struct IsSmartPtr<std::unique_ptr<T, Deleter>> {
static const bool value = true;
};
template <typename T, typename Deleter>
struct GetPtrHelper<std::unique_ptr<T, Deleter>> {
typedef T* PtrType;
static T* getPtr(const std::unique_ptr<T, Deleter>& p) { return p.get(); }
};
template<size_t size> struct IntTypes;
template<> struct IntTypes<1> { typedef int8_t SignedType; typedef uint8_t UnsignedType; };
template<> struct IntTypes<2> { typedef int16_t SignedType; typedef uint16_t UnsignedType; };
template<> struct IntTypes<4> { typedef int32_t SignedType; typedef uint32_t UnsignedType; };
template<> struct IntTypes<8> { typedef int64_t SignedType; typedef uint64_t UnsignedType; };
// integer hash function
// Thomas Wang's 32 Bit Mix Function: http://www.cris.com/~Ttwang/tech/inthash.htm
inline unsigned intHash(uint8_t key8)
{
unsigned key = key8;
key += ~(key << 15);
key ^= (key >> 10);
key += (key << 3);
key ^= (key >> 6);
key += ~(key << 11);
key ^= (key >> 16);
return key;
}
// Thomas Wang's 32 Bit Mix Function: http://www.cris.com/~Ttwang/tech/inthash.htm
inline unsigned intHash(uint16_t key16)
{
unsigned key = key16;
key += ~(key << 15);
key ^= (key >> 10);
key += (key << 3);
key ^= (key >> 6);
key += ~(key << 11);
key ^= (key >> 16);
return key;
}
// Thomas Wang's 32 Bit Mix Function: http://www.cris.com/~Ttwang/tech/inthash.htm
inline unsigned intHash(uint32_t key)
{
key += ~(key << 15);
key ^= (key >> 10);
key += (key << 3);
key ^= (key >> 6);
key += ~(key << 11);
key ^= (key >> 16);
return key;
}
// Thomas Wang's 64 bit Mix Function: http://www.cris.com/~Ttwang/tech/inthash.htm
inline unsigned intHash(uint64_t key)
{
key += ~(key << 32);
key ^= (key >> 22);
key += ~(key << 13);
key ^= (key >> 8);
key += (key << 3);
key ^= (key >> 15);
key += ~(key << 27);
key ^= (key >> 31);
return static_cast<unsigned>(key);
}
// Compound integer hash method: http://opendatastructures.org/versions/edition-0.1d/ods-java/node33.html#SECTION00832000000000000000
inline unsigned pairIntHash(unsigned key1, unsigned key2)
{
unsigned shortRandom1 = 277951225; // A random 32-bit value.
unsigned shortRandom2 = 95187966; // A random 32-bit value.
uint64_t longRandom = 19248658165952622LL; // A random 64-bit value.
uint64_t product = longRandom * (shortRandom1 * key1 + shortRandom2 * key2);
unsigned highBits = static_cast<unsigned>(product >> (sizeof(uint64_t) - sizeof(unsigned)));
return highBits;
}
template<typename T> struct IntHash {
static unsigned hash(T key) { return intHash(static_cast<typename IntTypes<sizeof(T)>::UnsignedType>(key)); }
static bool equal(T a, T b) { return a == b; }
static const bool safeToCompareToEmptyOrDeleted = true;
};
template<typename T> struct FloatHash {
typedef typename IntTypes<sizeof(T)>::UnsignedType Bits;
static unsigned hash(T key)
{
return intHash(bitwise_cast<Bits>(key));
}
static bool equal(T a, T b)
{
return bitwise_cast<Bits>(a) == bitwise_cast<Bits>(b);
}
static const bool safeToCompareToEmptyOrDeleted = true;
};
// pointer identity hash function
template<typename T, bool isSmartPointer>
struct PtrHashBase;
template <typename T>
struct PtrHashBase<T, false /* isSmartPtr */> {
typedef T PtrType;
static unsigned hash(PtrType key) { return IntHash<uintptr_t>::hash(reinterpret_cast<uintptr_t>(key)); }
static bool equal(PtrType a, PtrType b) { return a == b; }
static const bool safeToCompareToEmptyOrDeleted = true;
};
template <typename T>
struct PtrHashBase<T, true /* isSmartPtr */> {
typedef typename GetPtrHelper<T>::PtrType PtrType;
static unsigned hash(PtrType key) { return IntHash<uintptr_t>::hash(reinterpret_cast<uintptr_t>(key)); }
static bool equal(PtrType a, PtrType b) { return a == b; }
static const bool safeToCompareToEmptyOrDeleted = true;
static unsigned hash(const T& key) { return hash(getPtr(key)); }
static bool equal(const T& a, const T& b) { return getPtr(a) == getPtr(b); }
static bool equal(PtrType a, const T& b) { return a == getPtr(b); }
static bool equal(const T& a, PtrType b) { return getPtr(a) == b; }
};
template<typename T> struct PtrHash : PtrHashBase<T, IsSmartPtr<T>::value> {
};
// default hash function for each type
template<typename T> struct DefaultHash;
template<typename T, typename U> struct PairHash {
static unsigned hash(const std::pair<T, U>& p)
{
return pairIntHash(DefaultHash<T>::Hash::hash(p.first), DefaultHash<U>::Hash::hash(p.second));
}
static bool equal(const std::pair<T, U>& a, const std::pair<T, U>& b)
{
return DefaultHash<T>::Hash::equal(a.first, b.first) && DefaultHash<U>::Hash::equal(a.second, b.second);
}
static const bool safeToCompareToEmptyOrDeleted = DefaultHash<T>::Hash::safeToCompareToEmptyOrDeleted && DefaultHash<U>::Hash::safeToCompareToEmptyOrDeleted;
};
template<typename T, typename U> struct IntPairHash {
static unsigned hash(const std::pair<T, U>& p) { return pairIntHash(p.first, p.second); }
static bool equal(const std::pair<T, U>& a, const std::pair<T, U>& b) { return PairHash<T, T>::equal(a, b); }
static const bool safeToCompareToEmptyOrDeleted = PairHash<T, U>::safeToCompareToEmptyOrDeleted;
};
template<typename... Types>
struct TupleHash {
template<size_t I = 0>
static typename std::enable_if<I < sizeof...(Types) - 1, unsigned>::type hash(const std::tuple<Types...>& t)
{
using IthTupleElementType = typename std::tuple_element<I, typename std::tuple<Types...>>::type;
return pairIntHash(DefaultHash<IthTupleElementType>::Hash::hash(std::get<I>(t)), hash<I + 1>(t));
}
template<size_t I = 0>
static typename std::enable_if<I == sizeof...(Types) - 1, unsigned>::type hash(const std::tuple<Types...>& t)
{
using IthTupleElementType = typename std::tuple_element<I, typename std::tuple<Types...>>::type;
return DefaultHash<IthTupleElementType>::Hash::hash(std::get<I>(t));
}
template<size_t I = 0>
static typename std::enable_if<I < sizeof...(Types) - 1, bool>::type equal(const std::tuple<Types...>& a, const std::tuple<Types...>& b)
{
using IthTupleElementType = typename std::tuple_element<I, typename std::tuple<Types...>>::type;
return DefaultHash<IthTupleElementType>::Hash::equal(std::get<I>(a), std::get<I>(b)) && equal<I + 1>(a, b);
}
template<size_t I = 0>
static typename std::enable_if<I == sizeof...(Types) - 1, bool>::type equal(const std::tuple<Types...>& a, const std::tuple<Types...>& b)
{
using IthTupleElementType = typename std::tuple_element<I, typename std::tuple<Types...>>::type;
return DefaultHash<IthTupleElementType>::Hash::equal(std::get<I>(a), std::get<I>(b));
}
// We should use safeToCompareToEmptyOrDeleted = DefaultHash<Types>::Hash::safeToCompareToEmptyOrDeleted &&... whenever
// we switch to C++17. We can't do anything better here right now because GCC can't do C++.
template<typename BoolType>
static constexpr bool allTrue(BoolType value) { return value; }
template<typename BoolType, typename... BoolTypes>
static constexpr bool allTrue(BoolType value, BoolTypes... values) { return value && allTrue(values...); }
static const bool safeToCompareToEmptyOrDeleted = allTrue(DefaultHash<Types>::Hash::safeToCompareToEmptyOrDeleted...);
};
// make IntHash the default hash function for many integer types
template<> struct DefaultHash<bool> { typedef IntHash<uint8_t> Hash; };
template<> struct DefaultHash<short> { typedef IntHash<unsigned> Hash; };
template<> struct DefaultHash<unsigned short> { typedef IntHash<unsigned> Hash; };
template<> struct DefaultHash<int> { typedef IntHash<unsigned> Hash; };
template<> struct DefaultHash<unsigned> { typedef IntHash<unsigned> Hash; };
template<> struct DefaultHash<long> { typedef IntHash<unsigned long> Hash; };
template<> struct DefaultHash<unsigned long> { typedef IntHash<unsigned long> Hash; };
template<> struct DefaultHash<long long> { typedef IntHash<unsigned long long> Hash; };
template<> struct DefaultHash<unsigned long long> { typedef IntHash<unsigned long long> Hash; };
#if defined(_NATIVE_WCHAR_T_DEFINED)
template<> struct DefaultHash<wchar_t> { typedef IntHash<wchar_t> Hash; };
#endif
template<> struct DefaultHash<float> { typedef FloatHash<float> Hash; };
template<> struct DefaultHash<double> { typedef FloatHash<double> Hash; };
// make PtrHash the default hash function for pointer types that don't specialize
template<typename P> struct DefaultHash<P*> { typedef PtrHash<P*> Hash; };
template<typename P, typename Deleter> struct DefaultHash<std::unique_ptr<P, Deleter>> { typedef PtrHash<std::unique_ptr<P, Deleter>> Hash; };
// make IntPairHash the default hash function for pairs of (at most) 32-bit integers.
template<> struct DefaultHash<std::pair<short, short>> { typedef IntPairHash<short, short> Hash; };
template<> struct DefaultHash<std::pair<short, unsigned short>> { typedef IntPairHash<short, unsigned short> Hash; };
template<> struct DefaultHash<std::pair<short, int>> { typedef IntPairHash<short, int> Hash; };
template<> struct DefaultHash<std::pair<short, unsigned>> { typedef IntPairHash<short, unsigned> Hash; };
template<> struct DefaultHash<std::pair<unsigned short, short>> { typedef IntPairHash<unsigned short, short> Hash; };
template<> struct DefaultHash<std::pair<unsigned short, unsigned short>> { typedef IntPairHash<unsigned short, unsigned short> Hash; };
template<> struct DefaultHash<std::pair<unsigned short, int>> { typedef IntPairHash<unsigned short, int> Hash; };
template<> struct DefaultHash<std::pair<unsigned short, unsigned>> { typedef IntPairHash<unsigned short, unsigned> Hash; };
template<> struct DefaultHash<std::pair<int, short>> { typedef IntPairHash<int, short> Hash; };
template<> struct DefaultHash<std::pair<int, unsigned short>> { typedef IntPairHash<int, unsigned short> Hash; };
template<> struct DefaultHash<std::pair<int, int>> { typedef IntPairHash<int, int> Hash; };
template<> struct DefaultHash<std::pair<int, unsigned>> { typedef IntPairHash<unsigned, unsigned> Hash; };
template<> struct DefaultHash<std::pair<unsigned, short>> { typedef IntPairHash<unsigned, short> Hash; };
template<> struct DefaultHash<std::pair<unsigned, unsigned short>> { typedef IntPairHash<unsigned, unsigned short> Hash; };
template<> struct DefaultHash<std::pair<unsigned, int>> { typedef IntPairHash<unsigned, int> Hash; };
template<> struct DefaultHash<std::pair<unsigned, unsigned>> { typedef IntPairHash<unsigned, unsigned> Hash; };
// make PairHash the default hash function for pairs of arbitrary values.
template<typename T, typename U> struct DefaultHash<std::pair<T, U>> { typedef PairHash<T, U> Hash; };
template<typename... Types> struct DefaultHash<std::tuple<Types...>> { typedef TupleHash<Types...> Hash; };
template<typename T> struct HashTraits;
template<bool isInteger, typename T> struct GenericHashTraitsBase;
template<typename T> struct GenericHashTraitsBase<false, T> {
// The emptyValueIsZero flag is used to optimize allocation of empty hash tables with zeroed memory.
static const bool emptyValueIsZero = false;
// The hasIsEmptyValueFunction flag allows the hash table to automatically generate code to check
// for the empty value when it can be done with the equality operator, but allows custom functions
// for cases like String that need them.
static const bool hasIsEmptyValueFunction = false;
// The starting table size. Can be overridden when we know beforehand that
// a hash table will have at least N entries.
static const unsigned minimumTableSize = 8;
};
// Default integer traits disallow both 0 and -1 as keys (max value instead of -1 for unsigned).
template<typename T> struct GenericHashTraitsBase<true, T> : GenericHashTraitsBase<false, T> {
static const bool emptyValueIsZero = true;
static void constructDeletedValue(T& slot) { slot = static_cast<T>(-1); }
static bool isDeletedValue(T value) { return value == static_cast<T>(-1); }
};
template<typename T> struct GenericHashTraits : GenericHashTraitsBase<std::is_integral<T>::value, T> {
typedef T TraitType;
typedef T EmptyValueType;
static T emptyValue() { return T(); }
template<typename U, typename V>
static void assignToEmpty(U& emptyValue, V&& value)
{
emptyValue = std::forward<V>(value);
}
// Type for return value of functions that do not transfer ownership, such as get.
typedef T PeekType;
template<typename U> static U&& peek(U&& value) { return std::forward<U>(value); }
typedef T TakeType;
template<typename U> static TakeType take(U&& value) { return std::forward<U>(value); }
};
template<typename T> struct HashTraits : GenericHashTraits<T> { };
template<typename T> struct FloatHashTraits : GenericHashTraits<T> {
static T emptyValue() { return std::numeric_limits<T>::infinity(); }
static void constructDeletedValue(T& slot) { slot = -std::numeric_limits<T>::infinity(); }
static bool isDeletedValue(T value) { return value == -std::numeric_limits<T>::infinity(); }
};
template<> struct HashTraits<float> : FloatHashTraits<float> { };
template<> struct HashTraits<double> : FloatHashTraits<double> { };
// Default unsigned traits disallow both 0 and max as keys -- use these traits to allow zero and disallow max - 1.
template<typename T> struct UnsignedWithZeroKeyHashTraits : GenericHashTraits<T> {
static const bool emptyValueIsZero = false;
static T emptyValue() { return std::numeric_limits<T>::max(); }
static void constructDeletedValue(T& slot) { slot = std::numeric_limits<T>::max() - 1; }
static bool isDeletedValue(T value) { return value == std::numeric_limits<T>::max() - 1; }
};
template<typename T> struct SignedWithZeroKeyHashTraits : GenericHashTraits<T> {
static const bool emptyValueIsZero = false;
static T emptyValue() { return std::numeric_limits<T>::min(); }
static void constructDeletedValue(T& slot) { slot = std::numeric_limits<T>::max(); }
static bool isDeletedValue(T value) { return value == std::numeric_limits<T>::max(); }
};
// Can be used with strong enums, allows zero as key.
template<typename T> struct StrongEnumHashTraits : GenericHashTraits<T> {
using UnderlyingType = typename std::underlying_type<T>::type;
static const bool emptyValueIsZero = false;
static T emptyValue() { return static_cast<T>(std::numeric_limits<UnderlyingType>::max()); }
static void constructDeletedValue(T& slot) { slot = static_cast<T>(std::numeric_limits<UnderlyingType>::max() - 1); }
static bool isDeletedValue(T value) { return value == static_cast<T>(std::numeric_limits<UnderlyingType>::max() - 1); }
};
template<typename P> struct HashTraits<P*> : GenericHashTraits<P*> {
static const bool emptyValueIsZero = true;
static void constructDeletedValue(P*& slot) { slot = reinterpret_cast<P*>(-1); }
static bool isDeletedValue(P* value) { return value == reinterpret_cast<P*>(-1); }
};
template<typename T> struct SimpleClassHashTraits : GenericHashTraits<T> {
static const bool emptyValueIsZero = true;
static void constructDeletedValue(T& slot) { new (NotNull, std::addressof(slot)) T(HashTableDeletedValue); }
static bool isDeletedValue(const T& value) { return value.isHashTableDeletedValue(); }
};
template<typename T, typename Deleter> struct HashTraits<std::unique_ptr<T, Deleter>> : SimpleClassHashTraits<std::unique_ptr<T, Deleter>> {
typedef std::nullptr_t EmptyValueType;
static EmptyValueType emptyValue() { return nullptr; }
static void constructDeletedValue(std::unique_ptr<T, Deleter>& slot) { new (NotNull, std::addressof(slot)) std::unique_ptr<T, Deleter> { reinterpret_cast<T*>(-1) }; }
static bool isDeletedValue(const std::unique_ptr<T, Deleter>& value) { return value.get() == reinterpret_cast<T*>(-1); }
typedef T* PeekType;
static T* peek(const std::unique_ptr<T, Deleter>& value) { return value.get(); }
static T* peek(std::nullptr_t) { return nullptr; }
static void customDeleteBucket(std::unique_ptr<T, Deleter>& value)
{
// The custom delete function exists to avoid a dead store before the value is destructed.
// The normal destruction sequence of a bucket would be:
// 1) Call the destructor of unique_ptr.
// 2) unique_ptr store a zero for its internal pointer.
// 3) unique_ptr destroys its value.
// 4) Call constructDeletedValue() to set the bucket as destructed.
//
// The problem is the call in (3) prevents the compile from eliminating the dead store in (2)
// becase a side effect of free() could be observing the value.
//
// This version of deleteBucket() ensures the dead 2 stores changing "value"
// are on the same side of the function call.
ASSERT(!isDeletedValue(value));
T* pointer = value.release();
constructDeletedValue(value);
// The null case happens if a caller uses std::move() to remove the pointer before calling remove()
// with an iterator. This is very uncommon.
if (LIKELY(pointer))
Deleter()(pointer);
}
};
// This struct template is an implementation detail of the isHashTraitsEmptyValue function,
// which selects either the emptyValue function or the isEmptyValue function to check for empty values.
template<typename Traits, bool hasEmptyValueFunction> struct HashTraitsEmptyValueChecker;
template<typename Traits> struct HashTraitsEmptyValueChecker<Traits, true> {
template<typename T> static bool isEmptyValue(const T& value) { return Traits::isEmptyValue(value); }
};
template<typename Traits> struct HashTraitsEmptyValueChecker<Traits, false> {
template<typename T> static bool isEmptyValue(const T& value) { return value == Traits::emptyValue(); }
};
template<typename Traits, typename T> inline bool isHashTraitsEmptyValue(const T& value)
{
return HashTraitsEmptyValueChecker<Traits, Traits::hasIsEmptyValueFunction>::isEmptyValue(value);
}
template<typename Traits, typename T>
struct HashTraitHasCustomDelete {
static T& bucketArg;
template<typename X> static std::true_type TestHasCustomDelete(X*, decltype(X::customDeleteBucket(bucketArg))* = nullptr);
static std::false_type TestHasCustomDelete(...);
typedef decltype(TestHasCustomDelete(static_cast<Traits*>(nullptr))) ResultType;
static const bool value = ResultType::value;
};
template<typename Traits, typename T>
typename std::enable_if<HashTraitHasCustomDelete<Traits, T>::value>::type
hashTraitsDeleteBucket(T& value)
{
Traits::customDeleteBucket(value);
}
template<typename Traits, typename T>
typename std::enable_if<!HashTraitHasCustomDelete<Traits, T>::value>::type
hashTraitsDeleteBucket(T& value)
{
value.~T();
Traits::constructDeletedValue(value);
}
template<typename FirstTraitsArg, typename SecondTraitsArg>
struct PairHashTraits : GenericHashTraits<std::pair<typename FirstTraitsArg::TraitType, typename SecondTraitsArg::TraitType>> {
typedef FirstTraitsArg FirstTraits;
typedef SecondTraitsArg SecondTraits;
typedef std::pair<typename FirstTraits::TraitType, typename SecondTraits::TraitType> TraitType;
typedef std::pair<typename FirstTraits::EmptyValueType, typename SecondTraits::EmptyValueType> EmptyValueType;
static const bool emptyValueIsZero = FirstTraits::emptyValueIsZero && SecondTraits::emptyValueIsZero;
static EmptyValueType emptyValue() { return std::make_pair(FirstTraits::emptyValue(), SecondTraits::emptyValue()); }
static const unsigned minimumTableSize = FirstTraits::minimumTableSize;
static void constructDeletedValue(TraitType& slot) { FirstTraits::constructDeletedValue(slot.first); }
static bool isDeletedValue(const TraitType& value) { return FirstTraits::isDeletedValue(value.first); }
};
template<typename First, typename Second>
struct HashTraits<std::pair<First, Second>> : public PairHashTraits<HashTraits<First>, HashTraits<Second>> { };
template<typename FirstTrait, typename... Traits>
struct TupleHashTraits : GenericHashTraits<std::tuple<typename FirstTrait::TraitType, typename Traits::TraitType...>> {
typedef std::tuple<typename FirstTrait::TraitType, typename Traits::TraitType...> TraitType;
typedef std::tuple<typename FirstTrait::EmptyValueType, typename Traits::EmptyValueType...> EmptyValueType;
// We should use emptyValueIsZero = Traits::emptyValueIsZero &&... whenever we switch to C++17. We can't do anything
// better here right now because GCC can't do C++.
template<typename BoolType>
static constexpr bool allTrue(BoolType value) { return value; }
template<typename BoolType, typename... BoolTypes>
static constexpr bool allTrue(BoolType value, BoolTypes... values) { return value && allTrue(values...); }
static const bool emptyValueIsZero = allTrue(FirstTrait::emptyValueIsZero, Traits::emptyValueIsZero...);
static EmptyValueType emptyValue() { return std::make_tuple(FirstTrait::emptyValue(), Traits::emptyValue()...); }
static const unsigned minimumTableSize = FirstTrait::minimumTableSize;
static void constructDeletedValue(TraitType& slot) { FirstTrait::constructDeletedValue(std::get<0>(slot)); }
static bool isDeletedValue(const TraitType& value) { return FirstTrait::isDeletedValue(std::get<0>(value)); }
};
template<typename... Traits>
struct HashTraits<std::tuple<Traits...>> : public TupleHashTraits<HashTraits<Traits>...> { };
template<typename KeyTypeArg, typename ValueTypeArg>
struct KeyValuePair {
typedef KeyTypeArg KeyType;
KeyValuePair()
{
}
template<typename K, typename V>
KeyValuePair(K&& key, V&& value)
: key(std::forward<K>(key))
, value(std::forward<V>(value))
{
}
template <typename OtherKeyType, typename OtherValueType>
KeyValuePair(KeyValuePair<OtherKeyType, OtherValueType>&& other)
: key(std::forward<OtherKeyType>(other.key))
, value(std::forward<OtherValueType>(other.value))
{
}
KeyTypeArg key;
ValueTypeArg value;
};
template<typename KeyTraitsArg, typename ValueTraitsArg>
struct KeyValuePairHashTraits : GenericHashTraits<KeyValuePair<typename KeyTraitsArg::TraitType, typename ValueTraitsArg::TraitType>> {
typedef KeyTraitsArg KeyTraits;
typedef ValueTraitsArg ValueTraits;
typedef KeyValuePair<typename KeyTraits::TraitType, typename ValueTraits::TraitType> TraitType;
typedef KeyValuePair<typename KeyTraits::EmptyValueType, typename ValueTraits::EmptyValueType> EmptyValueType;
typedef typename ValueTraitsArg::TraitType ValueType;
static const bool emptyValueIsZero = KeyTraits::emptyValueIsZero && ValueTraits::emptyValueIsZero;
static EmptyValueType emptyValue() { return KeyValuePair<typename KeyTraits::EmptyValueType, typename ValueTraits::EmptyValueType>(KeyTraits::emptyValue(), ValueTraits::emptyValue()); }
static const unsigned minimumTableSize = KeyTraits::minimumTableSize;
static void constructDeletedValue(TraitType& slot) { KeyTraits::constructDeletedValue(slot.key); }
static bool isDeletedValue(const TraitType& value) { return KeyTraits::isDeletedValue(value.key); }
static void customDeleteBucket(TraitType& value)
{
static_assert(std::is_trivially_destructible<KeyValuePair<int, int>>::value,
"The wrapper itself has to be trivially destructible for customDeleteBucket() to make sense, since we do not destruct the wrapper itself.");
hashTraitsDeleteBucket<KeyTraits>(value.key);
value.value.~ValueType();
}
};
template<typename Key, typename Value>
struct HashTraits<KeyValuePair<Key, Value>> : public KeyValuePairHashTraits<HashTraits<Key>, HashTraits<Value>> { };
template<typename T>
struct NullableHashTraits : public HashTraits<T> {
static const bool emptyValueIsZero = false;
static T emptyValue() { return reinterpret_cast<T>(1); }
};
// Useful for classes that want complete control over what is empty and what is deleted,
// and how to construct both.
template<typename T>
struct CustomHashTraits : public GenericHashTraits<T> {
static const bool emptyValueIsZero = false;
static const bool hasIsEmptyValueFunction = true;
static void constructDeletedValue(T& slot)
{
new (NotNull, std::addressof(slot)) T(T::DeletedValue);
}
static bool isDeletedValue(const T& value)
{
return value.isDeletedValue();
}
static T emptyValue()
{
return T(T::EmptyValue);
}
static bool isEmptyValue(const T& value)
{
return value.isEmptyValue();
}
};
// Enables internal WTF consistency checks that are invoked automatically. Non-WTF callers can call checkTableConsistency() even if internal checks are disabled.
#define CHECK_HASHTABLE_CONSISTENCY 0
#ifdef NDEBUG
#define CHECK_HASHTABLE_ITERATORS 0
#define CHECK_HASHTABLE_USE_AFTER_DESTRUCTION 0
#else
#define CHECK_HASHTABLE_ITERATORS 1
#define CHECK_HASHTABLE_USE_AFTER_DESTRUCTION 1
#endif
#if DUMP_HASHTABLE_STATS
struct HashTableStats {
// The following variables are all atomically incremented when modified.
WTF_EXPORTDATA static std::atomic<unsigned> numAccesses;
WTF_EXPORTDATA static std::atomic<unsigned> numRehashes;
WTF_EXPORTDATA static std::atomic<unsigned> numRemoves;
WTF_EXPORTDATA static std::atomic<unsigned> numReinserts;
// The following variables are only modified in the recordCollisionAtCount method within a mutex.
WTF_EXPORTDATA static unsigned maxCollisions;
WTF_EXPORTDATA static unsigned numCollisions;
WTF_EXPORTDATA static unsigned collisionGraph[4096];
WTF_EXPORT_PRIVATE static void recordCollisionAtCount(unsigned count);
WTF_EXPORT_PRIVATE static void dumpStats();
};
#endif
template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
class HashTable;
template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
class HashTableIterator;
template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
class HashTableConstIterator;
template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
void addIterator(const HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>*,
HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>*);
template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
void removeIterator(HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>*);
#if !CHECK_HASHTABLE_ITERATORS
template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
inline void addIterator(const HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>*,
HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>*) { }
template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
inline void removeIterator(HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>*) { }
#endif
typedef enum { HashItemKnownGood } HashItemKnownGoodTag;
template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
class HashTableConstIterator : public std::iterator<std::forward_iterator_tag, Value, std::ptrdiff_t, const Value*, const Value&> {
private:
typedef HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> HashTableType;
typedef HashTableIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> iterator;
typedef HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> const_iterator;
typedef Value ValueType;
typedef const ValueType& ReferenceType;
typedef const ValueType* PointerType;
friend class HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>;
friend class HashTableIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>;
void skipEmptyBuckets()
{
while (m_position != m_endPosition && HashTableType::isEmptyOrDeletedBucket(*m_position))
++m_position;
}
HashTableConstIterator(const HashTableType* table, PointerType position, PointerType endPosition)
: m_position(position), m_endPosition(endPosition)
{
addIterator(table, this);
skipEmptyBuckets();
}
HashTableConstIterator(const HashTableType* table, PointerType position, PointerType endPosition, HashItemKnownGoodTag)
: m_position(position), m_endPosition(endPosition)
{
addIterator(table, this);
}
public:
HashTableConstIterator()
{
addIterator(static_cast<const HashTableType*>(0), this);
}
// default copy, assignment and destructor are OK if CHECK_HASHTABLE_ITERATORS is 0
#if CHECK_HASHTABLE_ITERATORS
~HashTableConstIterator()
{
removeIterator(this);
}
HashTableConstIterator(const const_iterator& other)
: m_position(other.m_position), m_endPosition(other.m_endPosition)
{
addIterator(other.m_table, this);
}
const_iterator& operator=(const const_iterator& other)
{
m_position = other.m_position;
m_endPosition = other.m_endPosition;
removeIterator(this);
addIterator(other.m_table, this);
return *this;
}
#endif
PointerType get() const
{
checkValidity();
return m_position;
}
ReferenceType operator*() const { return *get(); }
PointerType operator->() const { return get(); }
const_iterator& operator++()
{
checkValidity();
ASSERT(m_position != m_endPosition);
++m_position;
skipEmptyBuckets();
return *this;
}
// postfix ++ intentionally omitted
// Comparison.
bool operator==(const const_iterator& other) const
{
checkValidity(other);
return m_position == other.m_position;
}
bool operator!=(const const_iterator& other) const
{
checkValidity(other);
return m_position != other.m_position;
}
bool operator==(const iterator& other) const
{
return *this == static_cast<const_iterator>(other);
}
bool operator!=(const iterator& other) const
{
return *this != static_cast<const_iterator>(other);
}
private:
void checkValidity() const
{
#if CHECK_HASHTABLE_ITERATORS
ASSERT(m_table);
#endif
}
#if CHECK_HASHTABLE_ITERATORS
void checkValidity(const const_iterator& other) const
{
ASSERT(m_table);
ASSERT_UNUSED(other, other.m_table);
ASSERT(m_table == other.m_table);
}
#else
void checkValidity(const const_iterator&) const { }
#endif
PointerType m_position;
PointerType m_endPosition;
#if CHECK_HASHTABLE_ITERATORS
public:
// Any modifications of the m_next or m_previous of an iterator that is in a linked list of a HashTable::m_iterator,
// should be guarded with m_table->m_mutex.
mutable const HashTableType* m_table;
mutable const_iterator* m_next;
mutable const_iterator* m_previous;
#endif
};
template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
class HashTableIterator : public std::iterator<std::forward_iterator_tag, Value, std::ptrdiff_t, Value*, Value&> {
private:
typedef HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> HashTableType;
typedef HashTableIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> iterator;
typedef HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> const_iterator;
typedef Value ValueType;
typedef ValueType& ReferenceType;
typedef ValueType* PointerType;
friend class HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits>;
HashTableIterator(HashTableType* table, PointerType pos, PointerType end) : m_iterator(table, pos, end) { }
HashTableIterator(HashTableType* table, PointerType pos, PointerType end, HashItemKnownGoodTag tag) : m_iterator(table, pos, end, tag) { }
public:
HashTableIterator() { }
// default copy, assignment and destructor are OK
PointerType get() const { return const_cast<PointerType>(m_iterator.get()); }
ReferenceType operator*() const { return *get(); }
PointerType operator->() const { return get(); }
iterator& operator++() { ++m_iterator; return *this; }
// postfix ++ intentionally omitted
// Comparison.
bool operator==(const iterator& other) const { return m_iterator == other.m_iterator; }
bool operator!=(const iterator& other) const { return m_iterator != other.m_iterator; }
bool operator==(const const_iterator& other) const { return m_iterator == other; }
bool operator!=(const const_iterator& other) const { return m_iterator != other; }
operator const_iterator() const { return m_iterator; }
private:
const_iterator m_iterator;
};
template<typename ValueTraits, typename HashFunctions> class IdentityHashTranslator {
public:
template<typename T> static unsigned hash(const T& key) { return HashFunctions::hash(key); }
template<typename T, typename U> static bool equal(const T& a, const U& b) { return HashFunctions::equal(a, b); }
template<typename T, typename U, typename V> static void translate(T& location, const U&, V&& value)
{
ValueTraits::assignToEmpty(location, std::forward<V>(value));
}
};
template<typename IteratorType> struct HashTableAddResult {
HashTableAddResult() : isNewEntry(false) { }
HashTableAddResult(IteratorType iter, bool isNewEntry) : iterator(iter), isNewEntry(isNewEntry) { }
IteratorType iterator;
bool isNewEntry;
explicit operator bool() const { return isNewEntry; }
};
template<typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits>
class HashTable {
public:
typedef HashTableIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> iterator;
typedef HashTableConstIterator<Key, Value, Extractor, HashFunctions, Traits, KeyTraits> const_iterator;
typedef Traits ValueTraits;
typedef Key KeyType;
typedef Value ValueType;
typedef IdentityHashTranslator<ValueTraits, HashFunctions> IdentityTranslatorType;
typedef HashTableAddResult<iterator> AddResult;
#if DUMP_HASHTABLE_STATS_PER_TABLE
struct Stats {
Stats()
: numAccesses(0)
, numRehashes(0)
, numRemoves(0)
, numReinserts(0)
, maxCollisions(0)
, numCollisions(0)
, collisionGraph()
{
}
unsigned numAccesses;
unsigned numRehashes;
unsigned numRemoves;
unsigned numReinserts;
unsigned maxCollisions;
unsigned numCollisions;
unsigned collisionGraph[4096];
void recordCollisionAtCount(unsigned count)
{
if (count > maxCollisions)
maxCollisions = count;
numCollisions++;
collisionGraph[count]++;
}
void dumpStats()
{
dataLogF("\nWTF::HashTable::Stats dump\n\n");
dataLogF("%d accesses\n", numAccesses);
dataLogF("%d total collisions, average %.2f probes per access\n", numCollisions, 1.0 * (numAccesses + numCollisions) / numAccesses);
dataLogF("longest collision chain: %d\n", maxCollisions);
for (unsigned i = 1; i <= maxCollisions; i++) {
dataLogF(" %d lookups with exactly %d collisions (%.2f%% , %.2f%% with this many or more)\n", collisionGraph[i], i, 100.0 * (collisionGraph[i] - collisionGraph[i+1]) / numAccesses, 100.0 * collisionGraph[i] / numAccesses);
}
dataLogF("%d rehashes\n", numRehashes);
dataLogF("%d reinserts\n", numReinserts);
}
};
#endif
HashTable();
~HashTable()
{
invalidateIterators();
if (m_table)
deallocateTable(m_table, m_tableSize);
#if CHECK_HASHTABLE_USE_AFTER_DESTRUCTION
m_table = (ValueType*)(uintptr_t)0xbbadbeef;
#endif
}
HashTable(const HashTable&);
void swap(HashTable&);
HashTable& operator=(const HashTable&);
HashTable(HashTable&&);
HashTable& operator=(HashTable&&);
// When the hash table is empty, just return the same iterator for end as for begin.
// This is more efficient because we don't have to skip all the empty and deleted
// buckets, and iterating an empty table is a common case that's worth optimizing.
iterator begin() { return isEmpty() ? end() : makeIterator(m_table); }
iterator end() { return makeKnownGoodIterator(m_table + m_tableSize); }
const_iterator begin() const { return isEmpty() ? end() : makeConstIterator(m_table); }
const_iterator end() const { return makeKnownGoodConstIterator(m_table + m_tableSize); }
unsigned size() const { return m_keyCount; }
unsigned capacity() const { return m_tableSize; }