forked from ktprime/emhash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash_table7.hpp
1910 lines (1650 loc) · 59.3 KB
/
hash_table7.hpp
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
// emhash7::HashMap for C++11/14/17
// version 2.2.5
// https://github.com/ktprime/emhash/blob/master/hash_table7.hpp
//
// Licensed under the MIT License <https://opensource.org/licenses/MIT>.
// SPDX-License-Identifier: MIT
// Copyright (c) 2019-2024 Huang Yuanbing & bailuzhou AT 163.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE
// From
// NUMBER OF PROBES / LOOKUP Successful Unsuccessful
// Quadratic collision resolution 1 - ln(1-L) - L/2 1/(1-L) - L - ln(1-L)
// Linear collision resolution [1+1/(1-L)]/2 [1+1/(1-L)2]/2
// separator chain resolution 1 + L / 2 exp(-L) + L
// -- enlarge_factor -- 0.10 0.50 0.60 0.75 0.80 0.90 0.99
// QUADRATIC COLLISION RES.
// probes/successful lookup 1.05 1.44 1.62 2.01 2.21 2.85 5.11
// probes/unsuccessful lookup 1.11 2.19 2.82 4.64 5.81 11.4 103.6
// LINEAR COLLISION RES.
// probes/successful lookup 1.06 1.5 1.75 2.5 3.0 5.5 50.5
// probes/unsuccessful lookup 1.12 2.5 3.6 8.5 13.0 50.0
// SEPARATE CHAN RES.
// probes/successful lookup 1.05 1.25 1.3 1.25 1.4 1.45 1.50
// probes/unsuccessful lookup 1.00 1.11 1.15 1.22 1.25 1.31 1.37
// clacul/unsuccessful lookup 1.01 1.25 1.36, 1.56, 1.64, 1.81, 1.97
/****************
under random hashCodes, the frequency of nodes in bins follows a Poisson
distribution(https://en.wikipedia.org/wiki/Poisson_distribution) with a parameter of about 0.5
on average for the default resizing threshold of 0.75, although with a large variance because
of resizing granularity. Ignoring variance, the expected occurrences of list size k are
(exp(-0.5) * pow(0.5, k)/factorial(k)). The first values are:
0: 0.60653066
1: 0.30326533
2: 0.07581633
3: 0.01263606
4: 0.00157952
5: 0.00015795
6: 0.00001316
7: 0.00000094
8: 0.00000006
============== buckets size ration ========
1 1543981 0.36884964|0.36787944 36.885
2 768655 0.36725597|0.36787944 73.611
3 256236 0.18364065|0.18393972 91.975
4 64126 0.06127757|0.06131324 98.102
5 12907 0.01541710|0.01532831 99.644
6 2050 0.00293841|0.00306566 99.938
7 310 0.00051840|0.00051094 99.990
8 49 0.00009365|0.00007299 99.999
9 4 0.00000860|0.00000913 100.000
========== collision miss ration ===========
_num_filled aver_size k.v size_kv = 4185936, 1.58, x.x 24
collision,possion,cache_miss hit_find|hit_miss, load_factor = 36.73%,36.74%,31.31% 1.50|2.00, 1.00
============== buckets size ration ========
*******************************************************/
#pragma once
#include <cstring>
#include <string>
#include <cmath>
#include <cstdlib>
#include <type_traits>
#include <cassert>
#include <utility>
#include <cstdint>
#include <functional>
#include <iterator>
#include <algorithm>
#if EMH_WY_HASH
#include "wyhash.h"
#endif
#ifdef EMH_NEW
#undef EMH_KEY
#undef EMH_VAL
#undef EMH_PKV
#undef EMH_NEW
#undef EMH_SET
#undef EMH_BUCKET
#undef EMH_EMPTY
#endif
// likely/unlikely
#if (__GNUC__ >= 4 || __clang__)
# define EMH_LIKELY(condition) __builtin_expect(condition, 1)
# define EMH_UNLIKELY(condition) __builtin_expect(condition, 0)
#else
# define EMH_LIKELY(condition) condition
# define EMH_UNLIKELY(condition) condition
#endif
#ifndef EMH_BUCKET_INDEX
#define EMH_BUCKET_INDEX 1
#endif
#if EMH_BUCKET_INDEX == 0
#define EMH_KEY(p,n) p[n].second.first
#define EMH_VAL(p,n) p[n].second.second
#define EMH_BUCKET(p,n) p[n].first
#define EMH_PKV(p,n) p[n].second
#define EMH_NEW(key, val, bucket)\
new(_pairs + bucket) PairT(bucket, value_type(key, val));\
_num_filled ++; EMH_SET(bucket)
#elif EMH_BUCKET_INDEX == 2
#define EMH_KEY(p,n) p[n].first.first
#define EMH_VAL(p,n) p[n].first.second
#define EMH_BUCKET(p,n) p[n].second
#define EMH_PKV(p,n) p[n].first
#define EMH_NEW(key, val, bucket)\
new(_pairs + bucket) PairT(value_type(key, val), bucket);\
_num_filled ++; EMH_SET(bucket)
#else
#define EMH_KEY(p,n) p[n].first
#define EMH_VAL(p,n) p[n].second
#define EMH_BUCKET(p,n) p[n].bucket
#define EMH_PKV(p,n) p[n]
#define EMH_NEW(key, val, bucket)\
new(_pairs + bucket) PairT(key, val, bucket);\
_num_filled ++; EMH_SET(bucket)
#endif
#define EMH_MASK(n) 1 << (n % MASK_BIT)
#define EMH_SET(n) _bitmask[n / MASK_BIT] &= ~(EMH_MASK(n))
#define EMH_CLS(n) _bitmask[n / MASK_BIT] |= EMH_MASK(n)
#define EMH_EMPTY(n) (_bitmask[n / MASK_BIT] & (EMH_MASK(n))) != 0
#if _WIN32
#include <intrin.h>
#if _WIN64
#pragma intrinsic(_umul128)
#endif
#endif
namespace emhash7 {
#ifdef EMH_SIZE_TYPE_16BIT
typedef uint16_t size_type;
static constexpr size_type INACTIVE = 0xFFFF;
#elif EMH_SIZE_TYPE_64BIT
typedef uint64_t size_type;
static constexpr size_type INACTIVE = 0 - 0x1ull;
#else
typedef uint32_t size_type;
static constexpr size_type INACTIVE = 0 - 0x1u;
#endif
#ifndef EMH_MALIGN
static constexpr uint32_t EMH_MALIGN = 16;
#endif
static_assert(EMH_MALIGN >= 16 && 0 == (EMH_MALIGN & (EMH_MALIGN - 1)));
#ifndef EMH_SIZE_TYPE_16BIT
static_assert((int)INACTIVE < 0, "INACTIVE must negative (to int)");
#endif
//count the leading zero bit
static inline int CTZ(size_t n)
{
#if defined(__x86_64__) || defined(_WIN32) || (__BYTE_ORDER__ && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
#elif __BIG_ENDIAN__ || (__BYTE_ORDER__ && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
n = __builtin_bswap64(n);
#else
static uint32_t endianness = 0x12345678;
const auto is_big = *(const char *)&endianness == 0x12;
if (is_big)
n = __builtin_bswap64(n);
#endif
#if _WIN32
unsigned long index;
#if defined(_WIN64)
_BitScanForward64(&index, n);
#else
_BitScanForward(&index, n);
#endif
#elif defined (__LP64__) || (SIZE_MAX == UINT64_MAX) || defined (__x86_64__)
auto index = __builtin_ctzll(n);
#elif 1
auto index = __builtin_ctzl(n);
#else
#if defined (__LP64__) || (SIZE_MAX == UINT64_MAX) || defined (__x86_64__)
size_type index;
__asm__("bsfq %1, %0\n" : "=r" (index) : "rm" (n) : "cc");
#else
size_type index;
__asm__("bsf %1, %0\n" : "=r" (index) : "rm" (n) : "cc");
#endif
#endif
return (int)index;
}
template <typename First, typename Second>
struct entry {
using first_type = First;
using second_type = Second;
entry(const First& key, const Second& val, size_type ibucket)
:second(val), first(key)
{
bucket = ibucket;
}
entry(First&& key, Second&& val, size_type ibucket)
:second(std::move(val)), first(std::move(key))
{
bucket = ibucket;
}
template<typename K, typename V>
entry(K&& key, V&& val, size_type ibucket)
:second(std::forward<V>(val)), first(std::forward<K>(key))
{
bucket = ibucket;
}
entry(const std::pair<First, Second>& pair)
:second(pair.second), first(pair.first)
{
bucket = INACTIVE;
}
entry(std::pair<First, Second>&& pair)
:second(std::move(pair.second)), first(std::move(pair.first))
{
bucket = INACTIVE;
}
entry(std::tuple<First, Second>&& tup)
:second(std::move(std::get<2>(tup))), first(std::move(std::get<1>(tup)))
{
bucket = INACTIVE;
}
entry(const entry& rhs)
:second(rhs.second), first(rhs.first)
{
bucket = rhs.bucket;
}
entry(entry&& rhs) noexcept
:second(std::move(rhs.second)), first(std::move(rhs.first))
{
bucket = rhs.bucket;
}
entry& operator = (entry&& rhs) noexcept
{
second = std::move(rhs.second);
bucket = rhs.bucket;
first = std::move(rhs.first);
return *this;
}
entry& operator = (const entry& rhs)
{
second = rhs.second;
bucket = rhs.bucket;
first = rhs.first;
return *this;
}
bool operator == (const entry<First, Second>& p) const
{
return first == p.first && second == p.second;
}
bool operator == (const std::pair<First, Second>& p) const
{
return first == p.first && second == p.second;
}
void swap(entry<First, Second>& o)
{
std::swap(second, o.second);
std::swap(first, o.first);
}
#if EMH_ORDER_KV || EMH_SIZE_TYPE_64BIT
First first;
size_type bucket;
Second second;
#else
Second second;
size_type bucket;
First first;
#endif
};
/// A cache-friendly hash table with open addressing, linear/qua probing and power-of-two capacity
template <typename KeyT, typename ValueT, typename HashT = std::hash<KeyT>, typename EqT = std::equal_to<KeyT>>
class HashMap
{
#ifndef EMH_DEFAULT_LOAD_FACTOR
constexpr static float EMH_DEFAULT_LOAD_FACTOR = 0.80f;
constexpr static float EMH_MIN_LOAD_FACTOR = 0.25f; //< 0.5
#endif
public:
typedef HashMap<KeyT, ValueT, HashT, EqT> htype;
typedef std::pair<KeyT, ValueT> value_type;
#if EMH_BUCKET_INDEX == 0
typedef value_type value_pair;
typedef std::pair<size_type, value_type> PairT;
#elif EMH_BUCKET_INDEX == 2
typedef value_type value_pair;
typedef std::pair<value_type, size_type> PairT;
#else
typedef entry<KeyT, ValueT> value_pair;
typedef entry<KeyT, ValueT> PairT;
#endif
typedef KeyT key_type;
typedef ValueT val_type;
typedef ValueT mapped_type;
typedef HashT hasher;
typedef EqT key_equal;
typedef PairT& reference;
typedef const PairT& const_reference;
class const_iterator;
class iterator
{
public:
typedef std::forward_iterator_tag iterator_category;
typedef std::ptrdiff_t difference_type;
typedef value_pair value_type;
typedef value_pair* pointer;
typedef value_pair& reference;
iterator() = default;
iterator(const const_iterator& it) : _map(it._map), _bucket(it._bucket), _from(it._from), _bmask(it._bmask) { }
//iterator(const htype* hash_map, size_type bucket, bool) : _map(hash_map), _bucket(bucket) { init(); }
#if EMH_ITER_SAFE
iterator(const htype* hash_map, size_type bucket) : _map(hash_map), _bucket(bucket) { init(); }
#else
iterator(const htype* hash_map, size_type bucket) : _map(hash_map), _bucket(bucket) { _from = -1; }
#endif
void init()
{
_from = (_bucket / SIZE_BIT) * SIZE_BIT;
if (_bucket < _map->bucket_count()) {
_bmask = *(size_t*)((size_t*)_map->_bitmask + _from / SIZE_BIT);
_bmask |= (1ull << _bucket % SIZE_BIT) - 1;
_bmask = ~_bmask;
} else {
_bmask = 0;
}
}
size_type bucket() const
{
return _bucket;
}
void clear(size_type bucket)
{
if (_bucket / SIZE_BIT == bucket / SIZE_BIT)
_bmask &= ~(1ull << (bucket % SIZE_BIT));
}
iterator& next()
{
goto_next_element();
return *this;
}
iterator& operator++()
{
#ifndef EMH_ITER_SAFE
if (_from == (size_type)-1) init();
#endif
_bmask &= _bmask - 1;
goto_next_element();
return *this;
}
iterator operator++(int)
{
#ifndef EMH_ITER_SAFE
if (_from == (size_type)-1) init();
#endif
iterator old = *this;
_bmask &= _bmask - 1;
goto_next_element();
return old;
}
reference operator*() const
{
return _map->EMH_PKV(_pairs, _bucket);
}
pointer operator->() const
{
return &(_map->EMH_PKV(_pairs, _bucket));
}
bool operator==(const iterator& rhs) const { return _bucket == rhs._bucket; }
bool operator!=(const iterator& rhs) const { return _bucket != rhs._bucket; }
bool operator==(const const_iterator& rhs) const { return _bucket == rhs._bucket; }
bool operator!=(const const_iterator& rhs) const { return _bucket != rhs._bucket; }
private:
void goto_next_element()
{
if (_bmask != 0) {
_bucket = _from + CTZ(_bmask);
return;
}
do {
_bmask = ~*(size_t*)((size_t*)_map->_bitmask + (_from += SIZE_BIT) / SIZE_BIT);
} while (_bmask == 0);
_bucket = _from + CTZ(_bmask);
}
public:
const htype* _map;
size_type _bucket;
size_type _from;
size_t _bmask;
};
class const_iterator
{
public:
typedef std::forward_iterator_tag iterator_category;
typedef std::ptrdiff_t difference_type;
typedef value_pair value_type;
typedef const value_pair* pointer;
typedef const value_pair& reference;
const_iterator(const iterator& it) : _map(it._map), _bucket(it._bucket), _from(it._from), _bmask(it._bmask) { }
//const_iterator(const htype* hash_map, size_type bucket, bool) : _map(hash_map), _bucket(bucket) { init(); }
#if EMH_ITER_SAFE
const_iterator(const htype* hash_map, size_type bucket) : _map(hash_map), _bucket(bucket) { init(); }
#else
const_iterator(const htype* hash_map, size_type bucket) : _map(hash_map), _bucket(bucket) { _from = -1; }
#endif
void init()
{
_from = (_bucket / SIZE_BIT) * SIZE_BIT;
if (_bucket < _map->bucket_count()) {
_bmask = *(size_t*)((size_t*)_map->_bitmask + _from / SIZE_BIT);
_bmask |= (1ull << _bucket % SIZE_BIT) - 1;
_bmask = ~_bmask;
} else {
_bmask = 0;
}
}
size_type bucket() const
{
return _bucket;
}
const_iterator& operator++()
{
#ifndef EMH_ITER_SAFE
if (_from == (size_type)-1) init();
#endif
goto_next_element();
return *this;
}
const_iterator operator++(int)
{
#ifndef EMH_ITER_SAFE
if (_from == (size_type)-1) init();
#endif
const_iterator old(*this);
goto_next_element();
return old;
}
reference operator*() const
{
return _map->EMH_PKV(_pairs, _bucket);
}
pointer operator->() const
{
return &(_map->EMH_PKV(_pairs, _bucket));
}
bool operator==(const const_iterator& rhs) const { return _bucket == rhs._bucket; }
bool operator!=(const const_iterator& rhs) const { return _bucket != rhs._bucket; }
private:
void goto_next_element()
{
_bmask &= _bmask - 1;
if (_bmask != 0) {
_bucket = _from + CTZ(_bmask);
return;
}
do {
_bmask = ~*(size_t*)((size_t*)_map->_bitmask + (_from += SIZE_BIT) / SIZE_BIT);
} while (_bmask == 0);
_bucket = _from + CTZ(_bmask);
}
public:
const htype* _map;
size_type _bucket;
size_type _from;
size_t _bmask;
};
void init(size_type bucket, float mlf = EMH_DEFAULT_LOAD_FACTOR)
{
_pairs = nullptr;
_bitmask = nullptr;
_num_buckets = _num_filled = 0;
_mlf = (uint32_t)((1 << 27) / EMH_DEFAULT_LOAD_FACTOR);
max_load_factor(mlf);
rehash(bucket);
}
HashMap(size_type bucket = 2, float mlf = EMH_DEFAULT_LOAD_FACTOR) noexcept
{
init(bucket, mlf);
}
static size_t AllocSize(uint64_t num_buckets)
{
return (num_buckets + EPACK_SIZE) * sizeof(PairT) + (num_buckets + 7) / 8 + BIT_PACK;
}
static PairT* alloc_bucket(size_type num_buckets)
{
#ifdef EMH_ALLOC
auto* new_pairs = (PairT*)aligned_alloc(EMH_MALIGN, AllocSize(num_buckets));
#else
auto* new_pairs = (PairT*)malloc(AllocSize(num_buckets));
#endif
return new_pairs;
}
HashMap(const HashMap& rhs) noexcept
{
if (rhs.load_factor() > EMH_MIN_LOAD_FACTOR) {
_pairs = (PairT*)alloc_bucket(rhs._num_buckets);
clone(rhs);
} else {
init(rhs._num_filled + 2, EMH_DEFAULT_LOAD_FACTOR);
for (auto it = rhs.begin(); it != rhs.end(); ++it)
insert_unique(it->first, it->second);
}
}
HashMap(HashMap&& rhs) noexcept
{
#ifndef EMH_ZERO_MOVE
init(4);
#else
_num_buckets = _num_filled = _mask = 0;
_pairs = nullptr;
#endif
swap(rhs);
}
HashMap(std::initializer_list<value_type> ilist)
{
init((size_type)ilist.size());
for (auto it = ilist.begin(); it != ilist.end(); ++it)
do_insert(*it);
}
template<class InputIt>
HashMap(InputIt first, InputIt last, size_type bucket_count=4)
{
init(std::distance(first, last) + bucket_count);
for (; first != last; ++first)
emplace(*first);
}
HashMap& operator= (const HashMap& rhs) noexcept
{
if (this == &rhs)
return *this;
if (rhs.load_factor() < EMH_MIN_LOAD_FACTOR) {
clear(); free(_pairs); _pairs = nullptr;
rehash(rhs._num_filled + 2);
for (auto it = rhs.begin(); it != rhs.end(); ++it)
insert_unique(it->first, it->second);
return *this;
}
if (_num_filled)
clearkv();
if (_num_buckets != rhs._num_buckets) {
free(_pairs);
_pairs = alloc_bucket(rhs._num_buckets);
}
clone(rhs);
return *this;
}
HashMap& operator= (HashMap&& rhs) noexcept
{
if (this != &rhs) {
swap(rhs);
rhs.clear();
}
return *this;
}
template<typename Con>
bool operator == (const Con& rhs) const
{
if (size() != rhs.size())
return false;
for (auto it = begin(), last = end(); it != last; ++it) {
auto oi = rhs.find(it->first);
if (oi == rhs.end() || it->second != oi->second)
return false;
}
return true;
}
template<typename Con>
bool operator != (const Con& rhs) const { return !(*this == rhs); }
~HashMap() noexcept
{
if (is_triviall_destructable() && _num_filled) {
for (auto it = cbegin(); _num_filled; ++it) {
_num_filled --;
it->~value_pair();
}
}
free(_pairs);
_pairs = nullptr;
}
void clone(const HashMap& rhs) noexcept
{
_hasher = rhs._hasher;
//_eq = rhs._eq;
_num_filled = rhs._num_filled;
_mask = rhs._mask;
_mlf = rhs._mlf;
_num_buckets = rhs._num_buckets;
_bitmask = decltype(_bitmask)(_pairs + EPACK_SIZE + _num_buckets);
auto* opairs = rhs._pairs;
if (is_copy_trivially())
memcpy(_pairs, opairs, AllocSize(_num_buckets));
else {
memcpy(_pairs + _num_buckets, opairs + _num_buckets, EPACK_SIZE * sizeof(PairT) + (_num_buckets + 7) / 8 + BIT_PACK);
for (auto it = rhs.cbegin(); it.bucket() <= _mask; ++it) {
const auto bucket = it.bucket();
new(_pairs + bucket) PairT(opairs[bucket]); EMH_BUCKET(_pairs, bucket) = EMH_BUCKET(opairs, bucket);
}
}
}
void swap(HashMap& rhs)
{
std::swap(_hasher, rhs._hasher);
//std::swap(_eq, rhs._eq);
std::swap(_pairs, rhs._pairs);
std::swap(_num_buckets, rhs._num_buckets);
std::swap(_num_filled, rhs._num_filled);
std::swap(_mask, rhs._mask);
std::swap(_mlf, rhs._mlf);
std::swap(_bitmask, rhs._bitmask);
}
// -------------------------------------------------------------
iterator begin() noexcept
{
#ifdef EMH_ZERO_MOVE
if (0 == _num_filled)
return {this, _num_buckets};
#endif
const auto bmask = ~(*(size_t*)_bitmask);
if (bmask != 0)
return {this, (size_type)CTZ(bmask)};
iterator it(this, sizeof(bmask) * 8 - 1);
it.init();
return it.next();
}
const_iterator cbegin() const noexcept
{
#ifdef EMH_ZERO_MOVE
if (0 == _num_filled)
return {this, _num_buckets};
#endif
const auto bmask = ~(*(size_t*)_bitmask);
if (bmask != 0)
return {this, (size_type)CTZ(bmask)};
iterator it(this, sizeof(bmask) * 8 - 1);
it.init();
return it.next();
}
iterator last() const
{
if (_num_filled == 0)
return end();
auto bucket = _mask;
while (EMH_EMPTY(bucket)) bucket--;
return {this, bucket};
}
inline const_iterator begin() const noexcept { return cbegin(); }
inline iterator end() noexcept { return {this, _num_buckets}; }
inline const_iterator cend() const { return {this, _num_buckets}; }
inline const_iterator end() const { return cend(); }
inline size_type size() const { return _num_filled; }
inline bool empty() const { return _num_filled == 0; }
inline size_type bucket_count() const { return _num_buckets; }
inline float load_factor() const { return static_cast<float>(_num_filled) / (_mask + 1); }
inline HashT& hash_function() const { return _hasher; }
inline EqT& key_eq() const { return _eq; }
inline void max_load_factor(float mlf)
{
if (mlf <= 0.999f && mlf > EMH_MIN_LOAD_FACTOR)
_mlf = (uint32_t)((1 << 27) / mlf);
}
inline constexpr float max_load_factor() const { return (1 << 27) / (float)_mlf; }
inline constexpr size_type max_size() const { return 1ull << (sizeof(size_type) * 8 - 1); }
inline constexpr size_type max_bucket_count() const { return max_size(); }
size_type bucket_main() const
{
auto main_size = 0;
for (size_type bucket = 0; bucket < _num_buckets; ++bucket) {
if (EMH_BUCKET(_pairs, bucket) == bucket)
main_size ++;
}
return main_size;
}
#if EMH_STATIS
//Returns the bucket number where the element with key k is located.
size_type bucket(const KeyT& key) const
{
const auto bucket = hash_key(key) & _mask;
const auto next_bucket = EMH_BUCKET(_pairs, bucket);
if (EMH_EMPTY(bucket))
return 0;
else if (bucket == next_bucket)
return bucket + 1;
const auto& bucket_key = EMH_KEY(_pairs, bucket);
return (hash_key(bucket_key) & _mask) + 1;
}
//Returns the number of elements in bucket n.
size_type bucket_size(const size_type bucket) const
{
if (EMH_EMPTY(bucket))
return 0;
auto next_bucket = EMH_BUCKET(_pairs, bucket);
next_bucket = hash_key(EMH_KEY(_pairs, bucket)) & _mask;
size_type bucket_size = 1;
//iterator each item in current main bucket
while (true) {
const auto nbucket = EMH_BUCKET(_pairs, next_bucket);
if (nbucket == next_bucket) {
break;
}
bucket_size++;
next_bucket = nbucket;
}
return bucket_size;
}
size_type get_main_bucket(const size_type bucket) const
{
if (EMH_EMPTY(bucket))
return INACTIVE;
auto next_bucket = EMH_BUCKET(_pairs, bucket);
const auto& bucket_key = EMH_KEY(_pairs, bucket);
const auto main_bucket = hash_key(bucket_key) & _mask;
return main_bucket;
}
size_type get_diss(size_type bucket, size_type next_bucket, const size_type slots) const
{
const int cahe_line_size = 64;
auto pbucket = reinterpret_cast<uint64_t>(&_pairs[bucket]);
auto pnext = reinterpret_cast<uint64_t>(&_pairs[next_bucket]);
if (pbucket / cahe_line_size == pnext / cahe_line_size)
return 0;
size_type diff = pbucket > pnext ? (pbucket - pnext) : (pnext - pbucket);
if (diff / cahe_line_size + 1 < slots)
return (diff / cahe_line_size + 1);
return slots - 1;
}
int get_bucket_info(const size_type bucket, size_type steps[], const size_type slots) const
{
if (EMH_EMPTY(bucket))
return -1;
auto next_bucket = EMH_BUCKET(_pairs, bucket);
if ((hash_key(EMH_KEY(_pairs, bucket)) & _mask) != bucket)
return 0;
else if (next_bucket == bucket)
return 1;
steps[get_diss(bucket, next_bucket, slots)] ++;
size_type bucket_size = 2;
while (true) {
const auto nbucket = EMH_BUCKET(_pairs, next_bucket);
if (nbucket == next_bucket)
break;
steps[get_diss(nbucket, next_bucket, slots)] ++;
bucket_size ++;
next_bucket = nbucket;
}
return bucket_size;
}
void dump_statics(bool show_cache) const
{
const int slots = 128;
size_type buckets[slots + 1] = {0};
size_type steps[slots + 1] = {0};
char buff[1024 * 8];
for (size_type bucket = 0; bucket < _num_buckets; ++bucket) {
auto bsize = get_bucket_info(bucket, steps, slots);
if (bsize >= 0)
buckets[bsize] ++;
}
size_type sumb = 0, sums = 0, sumn = 0;
size_type miss = 0, finds = 0, bucket_coll = 0;
double lf = load_factor(), fk = 1.0 / exp(lf), sum_poisson = 0;
int bsize = sprintf (buff, "============== buckets size ration ========\n");
miss += _num_buckets - _num_filled;
for (int i = 1, factorial = 1; i < int(sizeof(buckets) / sizeof(buckets[0])); i++) {
double poisson = fk / factorial; factorial *= i; fk *= lf;
if (poisson > 1e-13 && i < 20)
sum_poisson += poisson * 100.0 * (i - 1) / i;
const int64_t bucketsi = buckets[i];
if (bucketsi == 0)
continue;
sumb += bucketsi;
sumn += bucketsi * i;
bucket_coll += bucketsi * (i - 1);
finds += bucketsi * i * (i + 1) / 2;
miss += bucketsi * i * i;
auto errs = (bucketsi * 1.0 * i / _num_filled - poisson) * 100 / poisson;
bsize += sprintf(buff + bsize, " %2d %8ld %0.8lf|%0.2lf%% %2.3lf\n",
i, bucketsi, bucketsi * 1.0 * i / _num_filled, errs, sumn * 100.0 / _num_filled);
if (sumn >= _num_filled)
break;
}
bsize += sprintf(buff + bsize, "========== collision miss ration ===========\n");
for (size_type i = 0; show_cache && i < sizeof(steps) / sizeof(steps[0]); i++) {
sums += steps[i];
if (steps[i] == 0)
continue;
if (steps[i] > 10)
bsize += sprintf(buff + bsize, " %2d %8u %0.2lf %.2lf\n", (int)i, steps[i], steps[i] * 100.0 / bucket_coll, sums * 100.0 / bucket_coll);
}
if (sumb == 0) return;
bsize += sprintf(buff + bsize, " _num_filled aver_size k.v size_kv = %u, %.2lf, %s.%s %zd\n",
_num_filled, _num_filled * 1.0 / sumb, typeid(KeyT).name(), typeid(ValueT).name(), sizeof(PairT));
bsize += sprintf(buff + bsize, " collision, poisson, cache_miss hit_find|hit_miss, load_factor = %.2lf%%,%.2lf%%,%.2lf%% %.2lf|%.2lf, %.2lf\n",
(bucket_coll * 100.0 / _num_filled), sum_poisson, (bucket_coll - steps[0]) * 100.0 / _num_filled,
finds * 1.0 / _num_filled, miss * 1.0 / _num_buckets, _num_filled * 1.0 / _num_buckets);
bsize += sprintf(buff + bsize, "============== buckets size end =============\n");
buff[bsize + 1] = 0;
#ifdef EMH_LOG
EMH_LOG << __FUNCTION__ << "|" << buff << endl;
#else
puts(buff);
#endif
assert(sumn == _num_filled);
assert(sums == bucket_coll || !show_cache);
assert(bucket_coll == buckets[0]);
}
#endif
// ------------------------------------------------------------
template<typename Key = KeyT>
inline iterator find(const Key& key, size_t key_hash) noexcept
{
return {this, find_filled_hash(key, key_hash)};
}
template<typename Key = KeyT>
inline const_iterator find(const Key& key, size_t key_hash) const noexcept
{
return {this, find_filled_hash(key, key_hash)};
}
template<typename Key=KeyT>
inline iterator find(const Key& key) noexcept
{
return {this, find_filled_bucket(key)};
}
template<typename Key = KeyT>
inline const_iterator find(const Key& key) const noexcept
{
return {this, find_filled_bucket(key)};
}
template<typename Key = KeyT>
ValueT& at(const KeyT& key)
{
const auto bucket = find_filled_bucket(key);
//throw
return EMH_VAL(_pairs, bucket);
}
template<typename Key = KeyT>
const ValueT& at(const KeyT& key) const
{
const auto bucket = find_filled_bucket(key);
//throw
return EMH_VAL(_pairs, bucket);
}
template<typename Key = KeyT>
inline bool contains(const Key& key) const noexcept
{
return find_filled_bucket(key) != _num_buckets;
}
template<typename Key = KeyT>
inline size_type count(const Key& key) const noexcept
{
return find_filled_bucket(key) != _num_buckets ? 1 : 0;
}
template<typename Key = KeyT>
std::pair<iterator, iterator> equal_range(const Key& key) const noexcept
{
const auto found = {this, find_filled_bucket(key), true};