-
Notifications
You must be signed in to change notification settings - Fork 275
/
cuckoohash_map.hh
2754 lines (2449 loc) · 100 KB
/
cuckoohash_map.hh
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
/** \file */
#ifndef _CUCKOOHASH_MAP_HH
#define _CUCKOOHASH_MAP_HH
#include <algorithm>
#include <array>
#include <atomic>
#include <bitset>
#include <cassert>
#include <cstdint>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <iterator>
#include <limits>
#include <list>
#include <memory>
#include <mutex>
#include <stdexcept>
#include <thread>
#include <type_traits>
#include <utility>
#include <vector>
#include "cuckoohash_config.hh"
#include "cuckoohash_util.hh"
#include "libcuckoo_bucket_container.hh"
/**
* A concurrent hash table
*
* @tparam Key type of keys in the table
* @tparam T type of values in the table
* @tparam Hash type of hash functor
* @tparam KeyEqual type of equality comparison functor
* @tparam Allocator type of allocator. We suggest using an aligned allocator,
* because the table relies on types that are over-aligned to optimize
* concurrent cache usage.
* @tparam SLOT_PER_BUCKET number of slots for each bucket in the table
*/
template <class Key, class T, class Hash = std::hash<Key>,
class KeyEqual = std::equal_to<Key>,
class Allocator = std::allocator<std::pair<const Key, T>>,
std::size_t SLOT_PER_BUCKET = LIBCUCKOO_DEFAULT_SLOT_PER_BUCKET>
class cuckoohash_map {
private:
// Type of the partial key
using partial_t = uint8_t;
// The type of the buckets container
using buckets_t =
libcuckoo_bucket_container<Key, T, Allocator, partial_t, SLOT_PER_BUCKET>;
public:
/** @name Type Declarations */
/**@{*/
using key_type = typename buckets_t::key_type;
using mapped_type = typename buckets_t::mapped_type;
/**
* This type is defined as an @c std::pair. Note that table behavior is
* undefined if a user-defined specialization of @c std::pair<Key, T> or @c
* std::pair<const Key, T> exists.
*/
using value_type = typename buckets_t::value_type;
using size_type = typename buckets_t::size_type;
using difference_type = std::ptrdiff_t;
using hasher = Hash;
using key_equal = KeyEqual;
using allocator_type = typename buckets_t::allocator_type;
using reference = typename buckets_t::reference;
using const_reference = typename buckets_t::const_reference;
using pointer = typename buckets_t::pointer;
using const_pointer = typename buckets_t::const_pointer;
class locked_table;
/**@}*/
/** @name Table Parameters */
/**@{*/
/**
* The number of slots per hash bucket
*/
static constexpr uint16_t slot_per_bucket() { return SLOT_PER_BUCKET; }
/**@}*/
/** @name Constructors, Destructors, and Assignment */
/**@{*/
/**
* Creates a new cuckohash_map instance
*
* @param n the number of elements to reserve space for initially
* @param hf hash function instance to use
* @param equal equality function instance to use
* @param alloc allocator instance to use
*/
cuckoohash_map(size_type n = LIBCUCKOO_DEFAULT_SIZE, const Hash &hf = Hash(),
const KeyEqual &equal = KeyEqual(),
const Allocator &alloc = Allocator())
: hash_fn_(hf), eq_fn_(equal),
buckets_(reserve_calc(n), alloc),
old_buckets_(0, alloc),
all_locks_(get_allocator()),
num_remaining_lazy_rehash_locks_(0),
minimum_load_factor_(LIBCUCKOO_DEFAULT_MINIMUM_LOAD_FACTOR),
maximum_hashpower_(LIBCUCKOO_NO_MAXIMUM_HASHPOWER),
max_num_worker_threads_(0) {
all_locks_.emplace_back(std::min(bucket_count(), size_type(kMaxNumLocks)),
spinlock(), get_allocator());
}
/**
* Constructs the map with the contents of the range @c [first, last]. If
* multiple elements in the range have equivalent keys, it is unspecified
* which element is inserted.
*
* @param first the beginning of the range to copy from
* @param last the end of the range to copy from
* @param n the number of elements to reserve space for initially
* @param hf hash function instance to use
* @param equal equality function instance to use
* @param alloc allocator instance to use
*/
template <typename InputIt>
cuckoohash_map(InputIt first, InputIt last,
size_type n = LIBCUCKOO_DEFAULT_SIZE, const Hash &hf = Hash(),
const KeyEqual &equal = KeyEqual(),
const Allocator &alloc = Allocator())
: cuckoohash_map(n, hf, equal, alloc) {
for (; first != last; ++first) {
insert(first->first, first->second);
}
}
/**
* Copy constructor. If @p other is being modified concurrently, behavior is
* unspecified.
*
* @param other the map being copied
*/
cuckoohash_map(const cuckoohash_map &other)
: cuckoohash_map(other, std::allocator_traits<allocator_type>::
select_on_container_copy_construction(
other.get_allocator())) {}
/**
* Copy constructor with separate allocator. If @p other is being modified
* concurrently, behavior is unspecified.
*
* @param other the map being copied
* @param alloc the allocator instance to use with the map
*/
cuckoohash_map(const cuckoohash_map &other, const Allocator &alloc)
: hash_fn_(other.hash_fn_), eq_fn_(other.eq_fn_),
buckets_(other.buckets_, alloc),
old_buckets_(other.old_buckets_, alloc), all_locks_(alloc),
num_remaining_lazy_rehash_locks_(
other.num_remaining_lazy_rehash_locks()),
minimum_load_factor_(other.minimum_load_factor()),
maximum_hashpower_(other.maximum_hashpower()),
max_num_worker_threads_(other.max_num_worker_threads()) {
if (other.get_allocator() == alloc) {
all_locks_ = other.all_locks_;
} else {
add_locks_from_other(other);
}
}
/**
* Move constructor. If @p other is being modified concurrently, behavior is
* unspecified.
*
* @param other the map being moved
*/
cuckoohash_map(cuckoohash_map &&other)
: cuckoohash_map(std::move(other), other.get_allocator()) {}
/**
* Move constructor with separate allocator. If the map being moved is being
* modified concurrently, behavior is unspecified.
*
* @param other the map being moved
* @param alloc the allocator instance to use with the map
*/
cuckoohash_map(cuckoohash_map &&other, const Allocator &alloc)
: hash_fn_(std::move(other.hash_fn_)), eq_fn_(std::move(other.eq_fn_)),
buckets_(std::move(other.buckets_), alloc),
old_buckets_(std::move(other.old_buckets_), alloc),
all_locks_(alloc),
num_remaining_lazy_rehash_locks_(
other.num_remaining_lazy_rehash_locks()),
minimum_load_factor_(other.minimum_load_factor()),
maximum_hashpower_(other.maximum_hashpower()),
max_num_worker_threads_(other.max_num_worker_threads()) {
if (other.get_allocator() == alloc) {
all_locks_ = std::move(other.all_locks_);
} else {
add_locks_from_other(other);
}
}
/**
* Constructs the map with the contents of initializer list @c init.
*
* @param init initializer list to initialize the elements of the map with
* @param n the number of elements to reserve space for initially
* @param hf hash function instance to use
* @param equal equality function instance to use
* @param alloc allocator instance to use
*/
cuckoohash_map(std::initializer_list<value_type> init,
size_type n = LIBCUCKOO_DEFAULT_SIZE, const Hash &hf = Hash(),
const KeyEqual &equal = KeyEqual(),
const Allocator &alloc = Allocator())
: cuckoohash_map(init.begin(), init.end(), n, hf, equal, alloc) {}
/**
* Exchanges the contents of the map with those of @p other
*
* @param other the map to exchange contents with
*/
void swap(cuckoohash_map &other) noexcept {
std::swap(hash_fn_, other.hash_fn_);
std::swap(eq_fn_, other.eq_fn_);
buckets_.swap(other.buckets_);
all_locks_.swap(other.all_locks_);
other.minimum_load_factor_.store(
minimum_load_factor_.exchange(other.minimum_load_factor(),
std::memory_order_release),
std::memory_order_release);
other.maximum_hashpower_.store(
maximum_hashpower_.exchange(other.maximum_hashpower(),
std::memory_order_release),
std::memory_order_release);
}
/**
* Copy assignment operator. If @p other is being modified concurrently,
* behavior is unspecified.
*
* @param other the map to assign from
* @return @c *this
*/
cuckoohash_map &operator=(const cuckoohash_map &other) {
hash_fn_ = other.hash_fn_;
eq_fn_ = other.eq_fn_;
buckets_ = other.buckets_;
old_buckets_ = other.old_buckets_;
all_locks_ = other.all_locks_;
num_remaining_lazy_rehash_locks_ = other.num_remaining_lazy_rehash_locks();
minimum_load_factor_ = other.minimum_load_factor();
maximum_hashpower_ = other.maximum_hashpower();
max_num_worker_threads_ = other.max_num_worker_threads();
return *this;
}
/**
* Move assignment operator. If @p other is being modified concurrently,
* behavior is unspecified.
*
* @param other the map to assign from
* @return @c *this
*/
cuckoohash_map &operator=(cuckoohash_map &&other) {
hash_fn_ = std::move(other.hash_fn_);
eq_fn_ = std::move(other.eq_fn_);
buckets_ = std::move(other.buckets_);
old_buckets_ = std::move(other.old_buckets_);
all_locks_ = std::move(other.all_locks_);
num_remaining_lazy_rehash_locks_ = std::move(
other.num_remaining_lazy_rehash_locks());
minimum_load_factor_ = std::move(other.minimum_load_factor());
maximum_hashpower_ = std::move(other.maximum_hashpower());
max_num_worker_threads_ = std::move(other.max_num_worker_threads());
return *this;
}
/**
* Initializer list assignment operator
*
* @param ilist an initializer list to assign from
* @return @c *this
*/
cuckoohash_map &operator=(std::initializer_list<value_type> ilist) {
clear();
for (const auto &item : ilist) {
insert(item.first, item.second);
}
return *this;
}
/**@}*/
/** @name Table Details
*
* Methods for getting information about the table. Methods that query
* changing properties of the table are not synchronized with concurrent
* operations, and may return out-of-date information if the table is being
* concurrently modified. They will also continue to work after the container
* has been moved.
*
*/
/**@{*/
/**
* Returns the function that hashes the keys
*
* @return the hash function
*/
hasher hash_function() const { return hash_fn_; }
/**
* Returns the function that compares keys for equality
*
* @return the key comparison function
*/
key_equal key_eq() const { return eq_fn_; }
/**
* Returns the allocator associated with the map
*
* @return the associated allocator
*/
allocator_type get_allocator() const { return buckets_.get_allocator(); }
/**
* Returns the hashpower of the table, which is log<SUB>2</SUB>(@ref
* bucket_count()).
*
* @return the hashpower
*/
size_type hashpower() const { return buckets_.hashpower(); }
/**
* Returns the number of buckets in the table.
*
* @return the bucket count
*/
size_type bucket_count() const { return buckets_.size(); }
/**
* Returns whether the table is empty or not.
*
* @return true if the table is empty, false otherwise
*/
bool empty() const { return size() == 0; }
/**
* Returns the number of elements in the table.
*
* @return number of elements in the table
*/
size_type size() const {
if (all_locks_.size() == 0) {
return 0;
}
counter_type s = 0;
for (spinlock &lock : get_current_locks()) {
s += lock.elem_counter();
}
assert(s >= 0);
return static_cast<size_type>(s);
}
/** Returns the current capacity of the table, that is, @ref bucket_count()
* × @ref slot_per_bucket().
*
* @return capacity of table
*/
size_type capacity() const { return bucket_count() * slot_per_bucket(); }
/**
* Returns the percentage the table is filled, that is, @ref size() ÷
* @ref capacity().
*
* @return load factor of the table
*/
double load_factor() const {
return static_cast<double>(size()) / static_cast<double>(capacity());
}
/**
* Sets the minimum load factor allowed for automatic expansions. If an
* expansion is needed when the load factor of the table is lower than this
* threshold, @ref libcuckoo_load_factor_too_low is thrown. It will not be
* thrown for an explicitly-triggered expansion.
*
* @param mlf the load factor to set the minimum to
* @throw std::invalid_argument if the given load factor is less than 0.0
* or greater than 1.0
*/
void minimum_load_factor(const double mlf) {
if (mlf < 0.0) {
throw std::invalid_argument("load factor " + std::to_string(mlf) +
" cannot be "
"less than 0");
} else if (mlf > 1.0) {
throw std::invalid_argument("load factor " + std::to_string(mlf) +
" cannot be "
"greater than 1");
}
minimum_load_factor_.store(mlf, std::memory_order_release);
}
/**
* Returns the minimum load factor of the table
*
* @return the minimum load factor
*/
double minimum_load_factor() const {
return minimum_load_factor_.load(std::memory_order_acquire);
}
/**
* Sets the maximum hashpower the table can be. If set to @ref
* LIBCUCKOO_NO_MAXIMUM_HASHPOWER, there will be no limit on the hashpower.
* Otherwise, the table will not be able to expand beyond the given
* hashpower, either by an explicit or an automatic expansion.
*
* @param mhp the hashpower to set the maximum to
* @throw std::invalid_argument if the current hashpower exceeds the limit
*/
void maximum_hashpower(size_type mhp) {
if (hashpower() > mhp) {
throw std::invalid_argument("maximum hashpower " + std::to_string(mhp) +
" is less than current hashpower");
}
maximum_hashpower_.store(mhp, std::memory_order_release);
}
/**
* Returns the maximum hashpower of the table
*
* @return the maximum hashpower
*/
size_type maximum_hashpower() const {
return maximum_hashpower_.load(std::memory_order_acquire);
}
/**
* Set the maximum number of extra worker threads the table can spawn when
* doing large batch operations. Currently batch operations occur in the
* following scenarios.
* - Any resizing operation which invokes cuckoo_expand_simple. This
* includes any explicit rehash/resize operation, or any general resize if
* the data is not nothrow-move-constructible.
* - Creating a locked_table or resizing within a locked_table.
*
* @param num_threads the number of extra threads
*/
void max_num_worker_threads(size_type extra_threads) {
max_num_worker_threads_.store(extra_threads, std::memory_order_release);
}
/**
* Returns the maximum number of extra worker threads.
*/
size_type max_num_worker_threads() const {
return max_num_worker_threads_.load(std::memory_order_acquire);
}
/**@}*/
/** @name Table Operations
*
* These are operations that affect the data in the table. They are safe to
* call concurrently with each other.
*
*/
/**@{*/
/**
* Searches the table for @p key, and invokes @p fn on the value. @p fn is
* not allowed to modify the contents of the value if found.
*
* @tparam K type of the key. This can be any type comparable with @c key_type
* @tparam F type of the functor. It should implement the method
* <tt>void operator()(const mapped_type&)</tt>.
* @param key the key to search for
* @param fn the functor to invoke if the element is found
* @return true if the key was found and functor invoked, false otherwise
*/
template <typename K, typename F> bool find_fn(const K &key, F fn) const {
const hash_value hv = hashed_key(key);
const auto b = snapshot_and_lock_two<normal_mode>(hv);
const table_position pos = cuckoo_find(key, hv.partial, b.i1, b.i2);
if (pos.status == ok) {
fn(buckets_[pos.index].mapped(pos.slot));
return true;
} else {
return false;
}
}
/**
* Searches the table for @p key, and invokes @p fn on the value. @p fn is
* allow to modify the contents of the value if found.
*
* @tparam K type of the key. This can be any type comparable with @c key_type
* @tparam F type of the functor. It should implement the method
* <tt>void operator()(mapped_type&)</tt>.
* @param key the key to search for
* @param fn the functor to invoke if the element is found
* @return true if the key was found and functor invoked, false otherwise
*/
template <typename K, typename F> bool update_fn(const K &key, F fn) {
const hash_value hv = hashed_key(key);
const auto b = snapshot_and_lock_two<normal_mode>(hv);
const table_position pos = cuckoo_find(key, hv.partial, b.i1, b.i2);
if (pos.status == ok) {
fn(buckets_[pos.index].mapped(pos.slot));
return true;
} else {
return false;
}
}
/**
* Searches for @p key in the table, and invokes @p fn on the value if the
* key is found. The functor can mutate the value, and should return @c true
* in order to erase the element, and @c false otherwise.
*
* @tparam K type of the key
* @tparam F type of the functor. It should implement the method
* <tt>bool operator()(mapped_type&)</tt>.
* @param key the key to possibly erase from the table
* @param fn the functor to invoke if the element is found
* @return true if @p key was found and @p fn invoked, false otherwise
*/
template <typename K, typename F> bool erase_fn(const K &key, F fn) {
const hash_value hv = hashed_key(key);
const auto b = snapshot_and_lock_two<normal_mode>(hv);
const table_position pos = cuckoo_find(key, hv.partial, b.i1, b.i2);
if (pos.status == ok) {
if (fn(buckets_[pos.index].mapped(pos.slot))) {
del_from_bucket(pos.index, pos.slot);
}
return true;
} else {
return false;
}
}
/**
* Searches for @p key in the table. If the key is found, then @p fn is
* called on the existing value, and nothing happens to the passed-in key and
* values. The functor can mutate the value, and should return @c true in
* order to erase the element, and @c false otherwise. If the key is not
* found and must be inserted, the pair will be constructed by forwarding the
* given key and values. If there is no room left in the table, it will be
* automatically expanded. Expansion may throw exceptions.
*
* @tparam K type of the key
* @tparam F type of the functor. It should implement the method
* <tt>bool operator()(mapped_type&)</tt>.
* @tparam Args list of types for the value constructor arguments
* @param key the key to insert into the table
* @param fn the functor to invoke if the element is found. If your @p fn
* needs more data that just the value being modified, consider implementing
* it as a lambda with captured arguments.
* @param val a list of constructor arguments with which to create the value
* @return true if a new key was inserted, false if the key was already in
* the table
*/
template <typename K, typename F, typename... Args>
bool uprase_fn(K &&key, F fn, Args &&... val) {
hash_value hv = hashed_key(key);
auto b = snapshot_and_lock_two<normal_mode>(hv);
table_position pos = cuckoo_insert_loop<normal_mode>(hv, b, key);
if (pos.status == ok) {
add_to_bucket(pos.index, pos.slot, hv.partial, std::forward<K>(key),
std::forward<Args>(val)...);
} else {
if (fn(buckets_[pos.index].mapped(pos.slot))) {
del_from_bucket(pos.index, pos.slot);
}
}
return pos.status == ok;
}
/**
* Equivalent to calling @ref uprase_fn with a functor that modifies the
* given value and always returns false (meaning the element is not removed).
* The passed-in functor must implement the method <tt>void
* operator()(mapped_type&)</tt>.
*/
template <typename K, typename F, typename... Args>
bool upsert(K &&key, F fn, Args &&... val) {
return uprase_fn(std::forward<K>(key),
[&fn](mapped_type &v) {
fn(v);
return false;
},
std::forward<Args>(val)...);
}
/**
* Copies the value associated with @p key into @p val. Equivalent to
* calling @ref find_fn with a functor that copies the value into @p val. @c
* mapped_type must be @c CopyAssignable.
*/
template <typename K> bool find(const K &key, mapped_type &val) const {
return find_fn(key, [&val](const mapped_type &v) mutable { val = v; });
}
/** Searches the table for @p key, and returns the associated value it
* finds. @c mapped_type must be @c CopyConstructible.
*
* @tparam K type of the key
* @param key the key to search for
* @return the value associated with the given key
* @throw std::out_of_range if the key is not found
*/
template <typename K> mapped_type find(const K &key) const {
const hash_value hv = hashed_key(key);
const auto b = snapshot_and_lock_two<normal_mode>(hv);
const table_position pos = cuckoo_find(key, hv.partial, b.i1, b.i2);
if (pos.status == ok) {
return buckets_[pos.index].mapped(pos.slot);
} else {
throw std::out_of_range("key not found in table");
}
}
/**
* Returns whether or not @p key is in the table. Equivalent to @ref
* find_fn with a functor that does nothing.
*/
template <typename K> bool contains(const K &key) const {
return find_fn(key, [](const mapped_type &) {});
}
/**
* Updates the value associated with @p key to @p val. Equivalent to
* calling @ref update_fn with a functor that assigns the existing mapped
* value to @p val. @c mapped_type must be @c MoveAssignable or @c
* CopyAssignable.
*/
template <typename K, typename V> bool update(const K &key, V &&val) {
return update_fn(key, [&val](mapped_type &v) { v = std::forward<V>(val); });
}
/**
* Inserts the key-value pair into the table. Equivalent to calling @ref
* upsert with a functor that does nothing.
*/
template <typename K, typename... Args> bool insert(K &&key, Args &&... val) {
return upsert(std::forward<K>(key), [](mapped_type &) {},
std::forward<Args>(val)...);
}
/**
* Inserts the key-value pair into the table. If the key is already in the
* table, assigns the existing mapped value to @p val. Equivalent to
* calling @ref upsert with a functor that assigns the mapped value to @p
* val.
*/
template <typename K, typename V> bool insert_or_assign(K &&key, V &&val) {
return upsert(std::forward<K>(key), [&val](mapped_type &m) { m = val; },
std::forward<V>(val));
}
/**
* Erases the key from the table. Equivalent to calling @ref erase_fn with a
* functor that just returns true.
*/
template <typename K> bool erase(const K &key) {
return erase_fn(key, [](mapped_type &) { return true; });
}
/**
* Resizes the table to the given hashpower. If this hashpower is not larger
* than the current hashpower, then it decreases the hashpower to the
* maximum of the specified value and the smallest hashpower that can hold
* all the elements currently in the table.
*
* @param n the hashpower to set for the table
* @return true if the table changed size, false otherwise
*/
bool rehash(size_type n) { return cuckoo_rehash<normal_mode>(n); }
/**
* Reserve enough space in the table for the given number of elements. If
* the table can already hold that many elements, the function will shrink
* the table to the smallest hashpower that can hold the maximum of the
* specified amount and the current table size.
*
* @param n the number of elements to reserve space for
* @return true if the size of the table changed, false otherwise
*/
bool reserve(size_type n) { return cuckoo_reserve<normal_mode>(n); }
/**
* Removes all elements in the table, calling their destructors.
*/
void clear() {
auto all_locks_manager = lock_all(normal_mode());
cuckoo_clear();
}
/**
* Construct a @ref locked_table object that owns all the locks in the
* table.
*
* @return a \ref locked_table instance
*/
locked_table lock_table() { return locked_table(*this); }
/**@}*/
private:
// Constructor helpers
void add_locks_from_other(const cuckoohash_map &other) {
locks_t &other_locks = other.get_current_locks();
all_locks_.emplace_back(other_locks.size(), spinlock(), get_allocator());
std::copy(other_locks.begin(), other_locks.end(),
get_current_locks().begin());
}
// Hashing types and functions
// true if the key is small and simple, which means using partial keys for
// lookup would probably slow us down
static constexpr bool is_simple() {
return std::is_pod<key_type>::value && sizeof(key_type) <= 8;
}
// Whether or not the data is nothrow-move-constructible.
static constexpr bool is_data_nothrow_move_constructible() {
return std::is_nothrow_move_constructible<key_type>::value &&
std::is_nothrow_move_constructible<mapped_type>::value;
}
// Contains a hash and partial for a given key. The partial key is used for
// partial-key cuckoohashing, and for finding the alternate bucket of that a
// key hashes to.
struct hash_value {
size_type hash;
partial_t partial;
};
template <typename K> hash_value hashed_key(const K &key) const {
const size_type hash = hash_function()(key);
return {hash, partial_key(hash)};
}
template <typename K> size_type hashed_key_only_hash(const K &key) const {
return hash_function()(key);
}
// hashsize returns the number of buckets corresponding to a given
// hashpower.
static inline size_type hashsize(const size_type hp) {
return size_type(1) << hp;
}
// hashmask returns the bitmask for the buckets array corresponding to a
// given hashpower.
static inline size_type hashmask(const size_type hp) {
return hashsize(hp) - 1;
}
// The partial key must only depend on the hash value. It cannot change with
// the hashpower, because, in order for `cuckoo_fast_double` to work
// properly, the alt_index must only grow by one bit at the top each time we
// expand the table.
static partial_t partial_key(const size_type hash) {
const uint64_t hash_64bit = hash;
const uint32_t hash_32bit = (static_cast<uint32_t>(hash_64bit) ^
static_cast<uint32_t>(hash_64bit >> 32));
const uint16_t hash_16bit = (static_cast<uint16_t>(hash_32bit) ^
static_cast<uint16_t>(hash_32bit >> 16));
const uint8_t hash_8bit = (static_cast<uint8_t>(hash_16bit) ^
static_cast<uint8_t>(hash_16bit >> 8));
return hash_8bit;
}
// index_hash returns the first possible bucket that the given hashed key
// could be.
static inline size_type index_hash(const size_type hp, const size_type hv) {
return hv & hashmask(hp);
}
// alt_index returns the other possible bucket that the given hashed key
// could be. It takes the first possible bucket as a parameter. Note that
// this function will return the first possible bucket if index is the
// second possible bucket, so alt_index(ti, partial, alt_index(ti, partial,
// index_hash(ti, hv))) == index_hash(ti, hv).
static inline size_type alt_index(const size_type hp, const partial_t partial,
const size_type index) {
// ensure tag is nonzero for the multiply. 0xc6a4a7935bd1e995 is the
// hash constant from 64-bit MurmurHash2
const size_type nonzero_tag = static_cast<size_type>(partial) + 1;
return (index ^ (nonzero_tag * 0xc6a4a7935bd1e995)) & hashmask(hp);
}
// Locking types
// Counter type
using counter_type = int64_t;
// A fast, lightweight spinlock
//
// Per-spinlock, we also maintain some metadata about the contents of the
// table. Storing data per-spinlock avoids false sharing issues when multiple
// threads need to update this metadata. We store the following information:
//
// - elem_counter: A counter indicating how many elements in the table are
// under this lock. One can compute the size of the table by summing the
// elem_counter over all locks.
//
// - is_migrated: When resizing with cuckoo_fast_doulbe, we do not
// immediately rehash elements from the old buckets array to the new one.
// Instead, we'll mark all of the locks as not migrated. So anybody trying to
// acquire the lock must also migrate the corresponding buckets if
// !is_migrated.
LIBCUCKOO_SQUELCH_PADDING_WARNING
class LIBCUCKOO_ALIGNAS(64) spinlock {
public:
spinlock() : elem_counter_(0), is_migrated_(true) { lock_.clear(); }
spinlock(const spinlock &other)
: elem_counter_(other.elem_counter()),
is_migrated_(other.is_migrated()) {
lock_.clear();
}
spinlock &operator=(const spinlock &other) {
elem_counter() = other.elem_counter();
is_migrated() = other.is_migrated();
return *this;
}
void lock() noexcept {
while (lock_.test_and_set(std::memory_order_acq_rel))
;
}
void unlock() noexcept { lock_.clear(std::memory_order_release); }
bool try_lock() noexcept {
return !lock_.test_and_set(std::memory_order_acq_rel);
}
counter_type &elem_counter() noexcept { return elem_counter_; }
counter_type elem_counter() const noexcept { return elem_counter_; }
bool &is_migrated() noexcept { return is_migrated_; }
bool is_migrated() const noexcept { return is_migrated_; }
private:
std::atomic_flag lock_;
counter_type elem_counter_;
bool is_migrated_;
};
template <typename U>
using rebind_alloc =
typename std::allocator_traits<allocator_type>::template rebind_alloc<U>;
using locks_t = std::vector<spinlock, rebind_alloc<spinlock>>;
using all_locks_t = std::list<locks_t, rebind_alloc<locks_t>>;
// Classes for managing locked buckets. By storing and moving around sets of
// locked buckets in these classes, we can ensure that they are unlocked
// properly.
struct LockDeleter {
void operator()(spinlock *l) const { l->unlock(); }
};
using LockManager = std::unique_ptr<spinlock, LockDeleter>;
// Each of the locking methods can operate in two modes: locked_table_mode
// and normal_mode. When we're in locked_table_mode, we assume the caller has
// already taken all locks on the buckets. We also require that all data is
// rehashed immediately, so that the caller never has to look through any
// locks. In normal_mode, we actually do take locks, and can rehash lazily.
using locked_table_mode = std::integral_constant<bool, true>;
using normal_mode = std::integral_constant<bool, false>;
class TwoBuckets {
public:
TwoBuckets() {}
TwoBuckets(size_type i1_, size_type i2_, locked_table_mode)
: i1(i1_), i2(i2_) {}
TwoBuckets(locks_t &locks, size_type i1_, size_type i2_, normal_mode)
: i1(i1_), i2(i2_), first_manager_(&locks[lock_ind(i1)]),
second_manager_((lock_ind(i1) != lock_ind(i2)) ? &locks[lock_ind(i2)]
: nullptr) {}
void unlock() {
first_manager_.reset();
second_manager_.reset();
}
size_type i1, i2;
private:
LockManager first_manager_, second_manager_;
};
struct AllUnlocker {
void operator()(cuckoohash_map *map) const {
for (auto it = first_locked; it != map->all_locks_.end(); ++it) {
locks_t &locks = *it;
for (spinlock &lock : locks) {
lock.unlock();
}
}
}
typename all_locks_t::iterator first_locked;
};
using AllLocksManager = std::unique_ptr<cuckoohash_map, AllUnlocker>;
// This exception is thrown whenever we try to lock a bucket, but the
// hashpower is not what was expected
class hashpower_changed {};
// After taking a lock on the table for the given bucket, this function will
// check the hashpower to make sure it is the same as what it was before the
// lock was taken. If it isn't unlock the bucket and throw a
// hashpower_changed exception.
inline void check_hashpower(size_type hp, spinlock &lock) const {
if (hashpower() != hp) {
lock.unlock();
LIBCUCKOO_DBG("%s", "hashpower changed\n");
throw hashpower_changed();
}
}
// If necessary, rehashes the buckets corresponding to the given lock index,
// and sets the is_migrated flag to true. We should only ever do migrations
// if the data is nothrow move constructible, so this function is noexcept.
//
// This only works if our current locks array is at the maximum size, because
// otherwise, rehashing could require taking other locks. Assumes the lock at
// the given index is taken.
//
// If IS_LAZY is true, we assume the lock is being rehashed in a lazy
// (on-demand) fashion, so we additionally decrement the number of locks we
// need to lazy_rehash. This may trigger false sharing with other
// lazy-rehashing threads, but the hope is that the fraction of such
// operations is low-enough to not significantly impact overall performance.
static constexpr bool kIsLazy = true;
static constexpr bool kIsNotLazy = false;
template <bool IS_LAZY>
void rehash_lock(size_t l) const noexcept {
locks_t &locks = get_current_locks();
spinlock &lock = locks[l];
if (lock.is_migrated()) return;
assert(is_data_nothrow_move_constructible());
assert(locks.size() == kMaxNumLocks);
assert(old_buckets_.hashpower() + 1 == buckets_.hashpower());
assert(old_buckets_.size() >= kMaxNumLocks);
// Iterate through all buckets in old_buckets that are controlled by this
// lock, and move them into the current buckets array.
for (size_type bucket_ind = l; bucket_ind < old_buckets_.size();
bucket_ind += kMaxNumLocks) {
move_bucket(old_buckets_, buckets_, bucket_ind);
}
lock.is_migrated() = true;
if (IS_LAZY) {
decrement_num_remaining_lazy_rehash_locks();
}
}
// locks the given bucket index.
//
// throws hashpower_changed if it changed after taking the lock.
LockManager lock_one(size_type, size_type, locked_table_mode) const {
return LockManager();
}
LockManager lock_one(size_type hp, size_type i, normal_mode) const {
locks_t &locks = get_current_locks();
const size_type l = lock_ind(i);
spinlock &lock = locks[l];
lock.lock();
check_hashpower(hp, lock);
rehash_lock<kIsLazy>(l);
return LockManager(&lock);
}
// locks the two bucket indexes, always locking the earlier index first to
// avoid deadlock. If the two indexes are the same, it just locks one.
//
// throws hashpower_changed if it changed after taking the lock.
TwoBuckets lock_two(size_type, size_type i1, size_type i2,