-
Notifications
You must be signed in to change notification settings - Fork 36
/
lru_time.h
1402 lines (1199 loc) · 41.6 KB
/
lru_time.h
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
// By Huang Yuanbing 2019-2024
// version 2.1.1
// LICENSE:
// This software is dual-licensed to the public domain and under the following
// license: you are granted a perpetual, irrevocable license to copy, modify,
// publish, and distribute this file as you see fit.
// 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
//
// -- 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
#pragma once
#include <cstring>
#include <cstdlib>
#include <type_traits>
#include <cassert>
#include <utility>
#include <cstdint>
#include <functional>
#include <iterator>
#include <ctime>
// likely/unlikely
#if (__GNUC__ >= 4 || __clang__)
# define EMHASH_LIKELY(condition) __builtin_expect(condition, 1)
# define EMHASH_UNLIKELY(condition) __builtin_expect(condition, 0)
#else
# define EMHASH_LIKELY(condition) condition
# define EMHASH_UNLIKELY(condition) condition
#endif
#if EMHASH_CACHE_LINE_SIZE < 32
#define EMHASH_CACHE_LINE_SIZE 64
#endif
#define IS_TIMEOUT(p,b) (p[b].timeout < nowts())
#define SET_TIMEOUT(b,t) _pairs[b].timeout = nowts() + t
#undef NEW_KVALUE
#define EMH_KEY(p,n) p[n].first
#define EMH_VAL(p,n) p[n].second
#define NEXT_BUCKET(p,n) p[n].bucket
#define EMH_PKV(p,n) p[n]
#define NEW_KVALUE(key, value, bucket) new(_pairs + bucket) PairT(key, value, bucket, _time_out), _num_filled ++
namespace emlru_time {
constexpr uint32_t INACTIVE = 0xFFFFFFFF;
inline static uint32_t nowts()
{
#if EMHASH_LRU_TIME > 0
return EMHASH_LRU_TIME;
#else
return time(0);
#endif
}
template <typename First, typename Second>
struct entry {
entry(const First& key, const Second& value, uint32_t ibucket, uint32_t itimeout = 5)
:second(value),first(key)
{
bucket = ibucket;
timeout = nowts() + itimeout;
}
entry(First&& key, Second&& value, uint32_t ibucket, uint32_t itimeout = 5)
:second(std::move(value)), first(std::move(key))
{
bucket = ibucket;
timeout = nowts() + itimeout;
}
entry(const std::pair<First,Second>& pair, uint32_t itimeout = 5)
:second(pair.second),first(pair.first)
{
bucket = INACTIVE;
timeout = nowts() + itimeout;
}
entry(std::pair<First, Second>&& pair, uint32_t itimeout = 5)
:second(std::move(pair.second)),first(std::move(pair.first))
{
bucket = INACTIVE;
timeout = nowts() + itimeout;
}
entry(const entry& pairT)
:second(pairT.second),first(pairT.first)
{
bucket = pairT.bucket;
timeout = pairT.timeout;
}
entry(entry&& pairT)
:second(std::move(pairT.second)),first(std::move(pairT.first))
{
bucket = pairT.bucket;
timeout= pairT.timeout;
}
entry& operator = (entry&& pairT)
{
second = std::move(pairT.second);
first = std::move(pairT.first);
bucket = pairT.bucket;
timeout = pairT.timeout;
return *this;
}
entry& operator = (entry& o)
{
second = o.second;
first = o.first;
bucket = o.bucket;
timeout = o.timeout;
return *this;
}
void swap(entry<First, Second>& o)
{
std::swap(second, o.second);
std::swap(first, o.first);
std::swap(timeout, o.timeout);
}
Second second;//int
First first; //long
uint32_t bucket;
uint32_t timeout;
};// __attribute__ ((packed));
/// 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 lru_cache
{
private:
typedef lru_cache<KeyT, ValueT, HashT, EqT> htype;
typedef entry<KeyT, ValueT> PairT;
typedef entry<KeyT, ValueT> value_pair;
public:
typedef KeyT key_type;
typedef ValueT mapped_type;
typedef size_t size_type;
typedef std::pair<KeyT,ValueT> value_type;
typedef PairT& reference;
typedef const PairT& const_reference;
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() { }
iterator(htype* hash_map, uint32_t bucket) : _map(hash_map), _bucket(bucket) { }
iterator& operator++()
{
goto_next_element();
return *this;
}
iterator operator++(int)
{
auto old_index = _bucket;
goto_next_element();
return {_map, old_index};
}
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;
}
private:
void goto_next_element()
{
do {
_bucket++;
} while (_map->NEXT_BUCKET(_pairs, _bucket) == INACTIVE);
}
public:
htype* _map;
uint32_t _bucket;
};
class const_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;
const_iterator() { }
const_iterator(const iterator& proto) : _map(proto._map), _bucket(proto._bucket) { }
const_iterator(const htype* hash_map, uint32_t bucket) : _map(hash_map), _bucket(bucket) { }
const_iterator& operator++()
{
goto_next_element();
return *this;
}
const_iterator operator++(int)
{
auto old_index = _bucket;
goto_next_element();
return {_map, old_index};
}
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()
{
do {
_bucket++;
} while (_map->NEXT_BUCKET(_pairs, _bucket) == INACTIVE);
}
public:
const htype* _map;
uint32_t _bucket;
};
// ------------------------------------------------------------------------
void init(uint32_t max_bucket = 1 << 10)
{
_num_buckets = 0;
_mask = 0;
_time_out = 5;
_pairs = nullptr;
_num_filled = 0;
_max_buckets = max_bucket;
max_load_factor(0.8f);
}
lru_cache(uint32_t bucket = 4, uint32_t max_bucket = 1 << 24, int timeout = 3600 * 24 * 365)
{
init(max_bucket);
_time_out = timeout;
reserve(bucket);
}
lru_cache(const lru_cache& other)
{
_pairs = (PairT*)malloc((2 + other._num_buckets) * sizeof(PairT));
clone(other);
}
lru_cache(lru_cache&& other)
{
init(1);
reserve(1);
*this = std::move(other);
}
/**
lru_cache(std::initializer_list<std::pair<KeyT, ValueT>> il)
{
init(il.size() * 2);
reserve((uint32_t)il.size());
for (auto begin = il.begin(); begin != il.end(); ++begin)
insert(*begin);
}
*/
lru_cache& operator=(const lru_cache& other)
{
if (this == &other)
return *this;
if (is_notrivially())
clearkv();
if (_num_buckets != other._num_buckets) {
free(_pairs);
_pairs = (PairT*)malloc((2 + other._num_buckets) * sizeof(PairT));
}
clone(other);
return *this;
}
lru_cache& operator=(lru_cache&& other)
{
if (this != &other) {
swap(other);
other.clear();
}
return *this;
}
~lru_cache()
{
if (is_notrivially())
clearkv();
free(_pairs);
}
void clone(const lru_cache& other)
{
_hasher = other._hasher;
_num_buckets = other._num_buckets;
_num_filled = other._num_filled;
_mask = other._mask;
_loadlf = other._loadlf;
_max_buckets = other._max_buckets;
_time_out = other._time_out;
auto opairs = other._pairs;
if (std::is_pod<KeyT>::value && std::is_pod<ValueT>::value) {
memcpy(_pairs, opairs, (_num_buckets + 2) * sizeof(PairT));
} else {
for (uint32_t bucket = 0; bucket < _num_buckets; bucket++) {
auto next_bucket = NEXT_BUCKET(_pairs, bucket) = NEXT_BUCKET(opairs, bucket);
if (next_bucket != INACTIVE)
new(_pairs + bucket) PairT(opairs[bucket]);
}
NEXT_BUCKET(_pairs, _num_buckets) = NEXT_BUCKET(_pairs, _num_buckets + 1) = 0;
_pairs[_num_buckets + 0].timeout = _pairs[_num_buckets + 1].timeout = INACTIVE;
}
}
void swap(lru_cache& other)
{
std::swap(_hasher, other._hasher);
std::swap(_pairs, other._pairs);
std::swap(_num_buckets, other._num_buckets);
std::swap(_num_filled, other._num_filled);
std::swap(_mask, other._mask);
std::swap(_loadlf, other._loadlf);
std::swap(_time_out, other._time_out);
std::swap(_max_buckets, other._max_buckets);
}
bool check_timeout(uint32_t bucket)
{
//check only main bucket
if (IS_TIMEOUT(_pairs, bucket) || hash_bucket(EMH_KEY(_pairs, bucket)) == bucket)
{
//_pairs[bucket].~PairT();
clear_bucket(bucket);
return true;
}
return false;
}
// -------------------------------------------------------------
iterator begin()
{
uint32_t bucket = 0;
while (NEXT_BUCKET(_pairs, bucket) == INACTIVE) {
++bucket;
}
return {this, bucket};
}
const_iterator cbegin() const
{
uint32_t bucket = 0;
while (NEXT_BUCKET(_pairs, bucket) == INACTIVE) {
++bucket;
}
return {this, bucket};
}
const_iterator begin() const
{
return cbegin();
}
iterator end()
{
return {this, _num_buckets};
}
const_iterator cend() const
{
return {this, _num_buckets};
}
const_iterator end() const
{
return {this, _num_buckets};
}
size_type size() const
{
return _num_filled;
}
bool empty() const
{
return _num_filled == 0;
}
// Returns the number of buckets.
size_type bucket_count() const
{
return _num_buckets;
}
/// Returns average number of elements per bucket.
float load_factor() const
{
return static_cast<float>(_num_filled) / (_mask + 1);
}
HashT& hash_function() const
{
return _hasher;
}
EqT& key_eq() const
{
return _eq;
}
constexpr float max_load_factor() const
{
return (1 << 27) / (float)_loadlf;
}
void max_load_factor(float value)
{
if (value < 0.95f && value > 0.2f)
_loadlf = (uint32_t)((1 << 27) / value);
}
constexpr size_type max_size() const
{
return (1 << 30);
}
constexpr size_type max_bucket_count() const
{
return (1 << 30);
}
#ifdef EMHASH_STATIS
//Returns the bucket number where the element with key k is located.
size_type bucket(const KeyT& key) const
{
const auto bucket = hash_bucket(key);
const auto next_bucket = NEXT_BUCKET(_pairs, bucket);
if (next_bucket == INACTIVE)
return 0;
else if (bucket == next_bucket)
return bucket + 1;
const auto& bucket_key = EMH_KEY(_pairs, bucket);
return hash_bucket(bucket_key) + 1;
}
//Returns the number of elements in bucket n.
size_type bucket_size(const uint32_t bucket) const
{
auto next_bucket = NEXT_BUCKET(_pairs, bucket);
if (next_bucket == INACTIVE)
return 0;
const auto& bucket_key = EMH_KEY(_pairs, bucket);
next_bucket = hash_bucket(bucket_key);
uint32_t ibucket_size = 1;
//iterator each item in current main bucket
while (true) {
const auto nbucket = NEXT_BUCKET(_pairs, next_bucket);
if (nbucket == next_bucket) {
break;
}
ibucket_size ++;
next_bucket = nbucket;
}
return ibucket_size;
}
size_type get_main_bucket(const uint32_t bucket) const
{
auto next_bucket = NEXT_BUCKET(_pairs, bucket);
if (next_bucket == INACTIVE)
return INACTIVE;
const auto& bucket_key = EMH_KEY(_pairs, bucket);
const auto main_bucket = hash_bucket(bucket_key);
return main_bucket;
}
size_type get_cache_info(uint32_t bucket, uint32_t next_bucket) const
{
auto pbucket = reinterpret_cast<std::uintptr_t>(&_pairs[bucket]);
auto pnext = reinterpret_cast<std::uintptr_t>(&_pairs[next_bucket]);
if (pbucket / 64 == pnext / 64)
return 0;
auto diff = pbucket > pnext ? (pbucket - pnext) : pnext - pbucket;
if (diff < 127 * 64)
return diff / 64 + 1;
return 127;
}
int get_bucket_info(const uint32_t bucket, uint32_t steps[], const uint32_t slots) const
{
auto next_bucket = NEXT_BUCKET(_pairs, bucket);
if (next_bucket == INACTIVE)
return -1;
const auto& bucket_key = EMH_KEY(_pairs, bucket);
const auto main_bucket = hash_bucket(bucket_key);
if (main_bucket != bucket)
return 0;
else if (next_bucket == bucket)
return 1;
steps[get_cache_info(bucket, next_bucket) % slots] ++;
uint32_t ibucket_size = 2;
//find a new empty and linked it to tail
while (true) {
const auto nbucket = NEXT_BUCKET(_pairs, next_bucket);
if (nbucket == next_bucket)
break;
steps[get_cache_info(nbucket, next_bucket) % slots] ++;
ibucket_size ++;
next_bucket = nbucket;
}
return ibucket_size;
}
void dump_statis() const
{
uint32_t buckets[129] = {0};
uint32_t steps[129] = {0};
for (uint32_t bucket = 0; bucket < _num_buckets; ++bucket) {
auto bsize = get_bucket_info(bucket, steps, 128);
if (bsize > 0)
buckets[bsize] ++;
}
uint32_t sumb = 0, collision = 0, sumc = 0, finds = 0, sumn = 0;
puts("============== buckets size ration =========");
for (uint32_t i = 0; i < sizeof(buckets) / sizeof(buckets[0]); i++) {
const auto bucketsi = buckets[i];
if (bucketsi == 0)
continue;
sumb += bucketsi;
sumn += bucketsi * i;
collision += bucketsi * (i - 1);
finds += bucketsi * i * (i + 1) / 2;
printf(" %2u %8u %.2lf %.2lf\n", i, bucketsi, bucketsi * 100.0 * i / _num_filled, sumn * 100.0 / _num_filled);
}
puts("========== collision miss ration ===========");
for (uint32_t i = 0; i < sizeof(steps) / sizeof(steps[0]); i++) {
sumc += steps[i];
if (steps[i] <= 2)
continue;
printf(" %2u %8u %.2lf %.2lf\n", i, steps[i], steps[i] * 100.0 / collision, sumc * 100.0 / collision);
}
if (sumb == 0) return;
printf(" _num_filled/bucket_size/packed collision/cache_miss/hit_found = %u/%.2lf/%zd/ %.2lf%%/%.2lf%%/%.2lf\n",
_num_filled, _num_filled * 1.0 / sumb, sizeof(PairT), (collision * 100.0 / _num_filled), (collision - steps[0]) * 100.0 / _num_filled, finds * 1.0 / _num_filled);
assert(sumn == _num_filled);
assert(sumc == collision);
}
#endif
// ------------------------------------------------------------
iterator find(const KeyT& key) noexcept
{
return {this, find_filled_bucket(key)};
}
const_iterator find(const KeyT& key) const noexcept
{
return {this, find_filled_bucket(key)};
}
bool contains(const KeyT& key) const noexcept
{
return find_filled_bucket(key) != _num_buckets;
}
size_type count(const KeyT& key) const noexcept
{
return find_filled_bucket(key) == _num_buckets ? 0 : 1;
}
std::pair<iterator, iterator> equal_range(const KeyT& key)
{
const auto found = find(key);
if (found == end())
return { found, found };
else
return { found, std::next(found) };
}
/// Returns false if key isn't found.
bool try_get(const KeyT& key, ValueT& val) const noexcept
{
const auto bucket = find_filled_bucket(key);
const auto found = bucket != _num_buckets;
if (found) {
val = EMH_VAL(_pairs, bucket);
}
return found;
}
/// Returns the matching ValueT or nullptr if k isn't found.
ValueT* try_get(const KeyT& key) noexcept
{
const auto bucket = find_filled_bucket(key);
return bucket == _num_buckets ? nullptr : &EMH_VAL(_pairs, bucket);
}
/// Const version of the above
ValueT* try_get(const KeyT& key) const noexcept
{
const auto bucket = find_filled_bucket(key);
return bucket == _num_buckets ? nullptr : &EMH_VAL(_pairs, bucket);
}
/// Convenience function.
ValueT get_or_return_default(const KeyT& key) const noexcept
{
const auto bucket = find_filled_bucket(key);
return bucket == _num_buckets ? ValueT() : EMH_VAL(_pairs, bucket);
}
// -----------------------------------------------------
/// Returns a pair consisting of an iterator to the inserted element
/// (or to the element that prevented the insertion)
/// and a bool denoting whether the insertion took place.
std::pair<iterator, bool> insert(const KeyT& key, const ValueT& value)
{
check_expand_need();
const auto bucket = find_or_allocate(key);
auto found = NEXT_BUCKET(_pairs, bucket) == INACTIVE;
if (found) {
NEW_KVALUE(key, value, bucket);
} else {
if (IS_TIMEOUT(_pairs, bucket)) {
EMH_KEY(_pairs, bucket) = key;
EMH_VAL(_pairs, bucket) = value;
found = true;
}
SET_TIMEOUT(bucket, _time_out);
}
return { {this, bucket}, found };
}
std::pair<iterator, bool> insert(const KeyT& key, const ValueT& value, int timeout) noexcept
{
check_expand_need();
const auto bucket = find_or_allocate(key);
auto found = NEXT_BUCKET(_pairs, bucket) == INACTIVE;
if (found) {
NEW_KVALUE(key, value, bucket);
} else {
if (IS_TIMEOUT(_pairs, bucket)) {
EMH_KEY(_pairs, bucket) = key;
EMH_VAL(_pairs, bucket) = value;
found = true;
}
SET_TIMEOUT(bucket, timeout);
}
return { {this, bucket}, found };
}
// std::pair<iterator, bool> insert(const value_pair& value) { return insert(value.first, value.second); }
std::pair<iterator, bool> insert(KeyT&& key, ValueT&& value) noexcept
{
check_expand_need();
const auto bucket = find_or_allocate(key);
auto found = NEXT_BUCKET(_pairs, bucket) == INACTIVE;
if (found) {
NEW_KVALUE(std::move(key), std::move(value), bucket);
} else {
if (IS_TIMEOUT(_pairs, bucket)) {
EMH_KEY(_pairs, bucket) = std::move(key);
EMH_VAL(_pairs, bucket) = std::move(value);
found = true;
}
SET_TIMEOUT(bucket, _time_out);
}
return { {this, bucket}, found };
}
inline std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT>& p)
{
return insert(p.first, p.second);
}
inline std::pair<iterator, bool> insert(std::pair<KeyT, ValueT>&& p)
{
return insert(std::move(p.first), std::move(p.second));
}
#if 0
template <typename Iter>
void insert(Iter begin, Iter end)
{
reserve(std::distance(begin, end) + _num_filled);
for (; begin != end; ++begin) {
emplace(*begin);
}
}
void insert(std::initializer_list<value_type> ilist)
{
reserve(ilist.size() + _num_filled);
for (auto begin = ilist.begin(); begin != end; ++begin) {
emplace(*begin);
}
}
template <typename Iter>
void insert2(Iter begin, Iter end)
{
Iter citbeg = begin;
Iter citend = begin;
reserve(std::distance(begin, end) + _num_filled);
for (; begin != end; ++begin) {
if (try_insert_mainbucket(begin->first, begin->second) == INACTIVE) {
std::swap(*begin, *citend++);
}
}
for (; citbeg != citend; ++citbeg)
insert(*citbeg);
}
uint32_t try_insert_mainbucket(const KeyT& key, const ValueT& value)
{
const auto bucket = hash_bucket(key);
auto next_bucket = NEXT_BUCKET(_pairs, bucket);
if (next_bucket != INACTIVE)
return INACTIVE;
NEW_KVALUE(key, value, bucket);
return bucket;
}
#endif
template <typename Iter>
void insert_unique(Iter begin, Iter end)
{
reserve(std::distance(begin, end) + _num_filled);
for (; begin != end; ++begin) {
insert_unique(*begin);
}
}
/// Same as above, but contains(key) MUST be false
uint32_t insert_unique(const KeyT& key, const ValueT& value)
{
check_expand_need();
auto bucket = find_unique_bucket(key);
NEW_KVALUE(key, value, bucket);
return bucket;
}
uint32_t insert_unique(KeyT&& key, ValueT&& value)
{
check_expand_need();
auto bucket = find_unique_bucket(key);
NEW_KVALUE(std::move(key), std::move(value), bucket);
return bucket;
}
uint32_t insert_unique(entry<KeyT, ValueT>&& pair)
{
auto bucket = find_unique_bucket(pair.first);
NEW_KVALUE(std::move(pair.first), std::move(pair.second), bucket);
return bucket;
}
inline uint32_t insert_unique(std::pair<KeyT, ValueT>&& p)
{
return insert_unique(std::move(p.first), std::move(p.second));
}
inline uint32_t insert_unique(std::pair<KeyT, ValueT>& p)
{
return insert_unique(p.first, p.second);
}
template <class... Args>
inline std::pair<iterator, bool> emplace(Args&&... args)
{
return insert(std::forward<Args>(args)...);
}
//no any optimize for position
template <class... Args>
iterator emplace_hint(const_iterator position, Args&&... args)
{
return insert(std::forward<Args>(args)...).first;
}
template<class... Args>
std::pair<iterator, bool> try_emplace(key_type&& k, Args&&... args)
{
return insert(k, std::forward<Args>(args)...).first;
}
template <class... Args>
inline std::pair<iterator, bool> emplace_unique(Args&&... args)
{
return insert_unique(std::forward<Args>(args)...);
}
std::pair<iterator, bool> insert_or_assign(const KeyT& key, ValueT&& value)
{
return insert(key, std::move(value));
}
std::pair<iterator, bool> insert_or_assign(KeyT&& key, ValueT&& value)
{
return insert(std::move(key), std::move(value));
}
/// Like std::map<KeyT,ValueT>::operator[].
ValueT& operator[](const KeyT& key)
{
EMHASH_UNLIKELY(check_expand_need());
auto bucket = find_or_allocate(key);
/* Check if inserting a new value rather than overwriting an old entry */
if (NEXT_BUCKET(_pairs, bucket) == INACTIVE) {
NEW_KVALUE(key, std::move(ValueT()), bucket);
} else {
//TODO:replace the key
if (IS_TIMEOUT(_pairs, bucket)) {
EMH_KEY(_pairs, bucket) = key;
EMH_VAL(_pairs, bucket) = ValueT();
}
SET_TIMEOUT(bucket, _time_out);
}
return EMH_VAL(_pairs, bucket);
}
ValueT& operator[](KeyT&& key)
{
EMHASH_UNLIKELY(check_expand_need());
auto bucket = find_or_allocate(key);
/* Check if inserting a new value rather than overwriting an old entry */
if (NEXT_BUCKET(_pairs, bucket) == INACTIVE) {
NEW_KVALUE(std::move(key), std::move(ValueT()), bucket);
} else {
if (IS_TIMEOUT(_pairs, bucket)) {
EMH_KEY(_pairs, bucket) = std::move(key);
EMH_VAL(_pairs, bucket) = std::move(ValueT());
}
SET_TIMEOUT(bucket, _time_out);
}
return EMH_VAL(_pairs, bucket);
}
// -------------------------------------------------------
/// Erase an element from the hash table.
/// return 0 if element was not found
size_type erase(const KeyT& key)
{
const auto bucket = erase_key(key);
if (bucket == INACTIVE)
return 0;
clear_bucket(bucket);
return 1;
}
//iterator erase(const_iterator begin_it, const_iterator end_it)
iterator erase(const_iterator cit)
{
iterator it(this, cit._bucket);
const auto bucket = erase_bucket(it._bucket);
clear_bucket(bucket);
//erase from main bucket, return main bucket as next
return (bucket == it._bucket) ? ++it : it;
}
void _erase(const_iterator it)
{
const auto bucket = erase_bucket(it._bucket);
clear_bucket(bucket);
}
constexpr bool is_notrivially() noexcept
{
#if __cplusplus >= 201402L || _MSC_VER > 1600 || __clang__
return !(std::is_trivially_destructible<KeyT>::value && std::is_trivially_destructible<ValueT>::value);
#else
return !(std::is_pod<KeyT>::value && std::is_pod<ValueT>::value);
#endif
}
void clearkv()
{
for (uint32_t bucket = 0; _num_filled > 0; ++bucket) {
if (NEXT_BUCKET(_pairs, bucket) != INACTIVE)
clear_bucket(bucket);
}
}
void clear_timeout()
{
auto now_ts = nowts();
for (uint32_t bucket = 0; bucket < _num_buckets; ++bucket) {
if (NEXT_BUCKET(_pairs, bucket) != INACTIVE && _pairs[bucket].timeout < now_ts) {
erase_bucket(bucket);
clear_bucket(bucket);
}
}
}
/// Remove all elements, keeping full capacity.
void clear()
{
if (is_notrivially() || sizeof(PairT) > EMHASH_CACHE_LINE_SIZE || _num_filled < _num_buckets / 4)
clearkv();
else
memset(_pairs, INACTIVE, sizeof(_pairs[0]) * _num_buckets);
_num_filled = 0;
}
void shrink_to_fit()
{
rehash(_num_filled);
}