-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathLinearOpenAddressingHashTable.hpp
1581 lines (1407 loc) · 67.3 KB
/
LinearOpenAddressingHashTable.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
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
**/
#ifndef QUICKSTEP_STORAGE_LINEAR_OPEN_ADDRESSING_HASH_TABLE_HPP_
#define QUICKSTEP_STORAGE_LINEAR_OPEN_ADDRESSING_HASH_TABLE_HPP_
#include <algorithm>
#include <atomic>
#include <cstddef>
#include <cstring>
#include <limits>
#include <memory>
#include <type_traits>
#include <utility>
#include <vector>
#include "storage/HashTable.hpp"
#include "storage/HashTableKeyManager.hpp"
#include "storage/StorageBlob.hpp"
#include "storage/StorageBlockInfo.hpp"
#include "storage/StorageConstants.hpp"
#include "storage/StorageManager.hpp"
#include "threading/SpinSharedMutex.hpp"
#include "types/Type.hpp"
#include "types/TypedValue.hpp"
#include "utility/Alignment.hpp"
#include "utility/Macros.hpp"
#include "utility/PrimeNumber.hpp"
namespace quickstep {
/** \addtogroup Storage
* @{
*/
/**
* @brief A hash table implementation which uses open addressing with linear
* (distance 1) probing.
**/
template <typename ValueT,
bool resizable,
bool serializable,
bool force_key_copy,
bool allow_duplicate_keys>
class LinearOpenAddressingHashTable : public HashTable<ValueT,
resizable,
serializable,
force_key_copy,
allow_duplicate_keys> {
public:
// Bring in constants from HashTable.
static constexpr unsigned char kEmptyHashByte
= HashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys>::kEmptyHashByte;
static constexpr std::size_t kEmptyHash
= HashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys>::kEmptyHash;
static constexpr std::size_t kPendingHash
= HashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys>::kPendingHash;
LinearOpenAddressingHashTable(const std::vector<const Type*> &key_types,
const std::size_t num_entries,
StorageManager *storage_manager);
LinearOpenAddressingHashTable(const std::vector<const Type*> &key_types,
void *hash_table_memory,
const std::size_t hash_table_memory_size,
const bool new_hash_table,
const bool hash_table_memory_zeroed);
// Delegating constructors for single scalar keys.
LinearOpenAddressingHashTable(const Type &key_type,
const std::size_t num_entries,
StorageManager *storage_manager)
: LinearOpenAddressingHashTable(std::vector<const Type*>(1, &key_type),
num_entries,
storage_manager) {
}
LinearOpenAddressingHashTable(const Type &key_type,
void *hash_table_memory,
const std::size_t hash_table_memory_size,
const bool new_hash_table,
const bool hash_table_memory_zeroed)
: LinearOpenAddressingHashTable(std::vector<const Type*>(1, &key_type),
hash_table_memory,
hash_table_memory_size,
new_hash_table,
hash_table_memory_zeroed) {
}
~LinearOpenAddressingHashTable() override {
DestroyValues(hash_buckets_,
header_->num_buckets + header_->num_overflow_buckets,
bucket_size_);
}
void clear() override;
std::size_t numEntries() const override;
const ValueT* getSingle(const TypedValue &key) const override;
const ValueT* getSingleCompositeKey(const std::vector<TypedValue> &key) const override;
void getAll(const TypedValue &key,
std::vector<const ValueT*> *values) const override;
void getAllCompositeKey(const std::vector<TypedValue> &key,
std::vector<const ValueT*> *values) const override;
std::size_t getHashTableMemorySizeBytes() const override {
return sizeof(Header) + numEntries() * bucket_size_;
}
protected:
HashTablePutResult putInternal(const TypedValue &key,
const std::size_t variable_key_size,
const ValueT &value,
HashTablePreallocationState *prealloc_state) override;
HashTablePutResult putCompositeKeyInternal(const std::vector<TypedValue> &key,
const std::size_t variable_key_size,
const ValueT &value,
HashTablePreallocationState *prealloc_state) override;
ValueT* upsertInternal(const TypedValue &key,
const std::size_t variable_key_size,
const ValueT &initial_value) override;
ValueT* upsertCompositeKeyInternal(const std::vector<TypedValue> &key,
const std::size_t variable_key_size,
const ValueT &initial_value) override;
bool getNextEntry(TypedValue *key,
const ValueT **value,
std::size_t *entry_num) const override;
bool getNextEntryCompositeKey(std::vector<TypedValue> *key,
const ValueT **value,
std::size_t *entry_num) const override;
bool getNextEntryForKey(const TypedValue &key,
const std::size_t hash_code,
const ValueT **value,
std::size_t *entry_num) const override;
bool getNextEntryForCompositeKey(const std::vector<TypedValue> &key,
const std::size_t hash_code,
const ValueT **value,
std::size_t *entry_num) const override;
bool hasKey(const TypedValue &key) const override;
bool hasCompositeKey(const std::vector<TypedValue> &key) const override;
void resize(const std::size_t extra_buckets,
const std::size_t extra_variable_storage,
const std::size_t retry_num = 0) override;
private:
struct Header {
// Number of ordinary (non-overflow) buckets in the hash table.
std::size_t num_buckets;
// Number of extra overflow buckets.
std::size_t num_overflow_buckets;
// Bytes actually allocated to hold variable length keys (or key segments).
// This is placed on its own cache line to avoid false sharing.
alignas(kCacheLineBytes)
std::atomic<std::size_t> variable_length_bytes_allocated;
};
// Write kEmptyHash to every bucket. Typically 'num_buckets' will be the
// TOTAL number of buckets (i.e. header_->num_buckets
// + header_->num_overflow_buckets). If 'memory_already_zeroed' is true,
// assume that bucket memory has already been zeroed out.
static void InitializeBuckets(void *buckets,
const std::size_t num_buckets,
const std::size_t bucket_size,
const bool memory_already_zeroed);
// If ValueT is not trivially destructible, invoke its destructor for all
// values held in the specified buckets (including those in "empty" buckets
// that were default constructed). If ValueT is trivially destructible, this
// is a no-op.
static void DestroyValues(void *buckets,
const std::size_t num_buckets,
const std::size_t bucket_size);
// Bucket size always rounds up to the alignment requirement of the atomic
// size_t hash at the front or a ValueT, whichever is larger.
//
// Make sure that the larger of the two alignment requirements also satisfies
// the smaller.
static_assert(alignof(std::atomic<std::size_t>) < alignof(ValueT)
? alignof(ValueT) % alignof(std::atomic<std::size_t>) == 0
: alignof(std::atomic<std::size_t>) % alignof(ValueT) == 0,
"Alignment requirement of std::atomic<std::size_t> does not "
"evenly divide with alignment requirement of ValueT.");
static constexpr std::size_t kBucketAlignment
= alignof(std::atomic<std::size_t>) < alignof(ValueT) ? alignof(ValueT)
: alignof(std::atomic<std::size_t>);
// Value's offset in a bucket is the first alignof(ValueT) boundary after the
// hash code.
static constexpr std::size_t kValueOffset
= (((sizeof(std::atomic<std::size_t>) - 1) / alignof(ValueT)) + 1) * alignof(ValueT);
// Round bucket size up to a multiple of kBucketAlignment.
static constexpr std::size_t ComputeBucketSize(const std::size_t fixed_key_size) {
return (((kValueOffset + sizeof(ValueT) + fixed_key_size - 1) / kBucketAlignment) + 1)
* kBucketAlignment;
}
// Attempt to find an empty bucket to insert 'hash_code' into, starting from
// '*bucket_num'. Returns true and stores kPendingHash in bucket if an empty
// bucket is found. Returns false if 'allow_duplicate_keys' is false and a
// hash collision is found (caller should then check whether there is a
// genuine key collision or the hash collision is spurious). Returns false if
// no empty buckets are available past the initial position of '*bucket_num'.
inline bool locateBucketForInsertion(const std::size_t hash_code,
std::size_t *bucket_num,
void **bucket);
// Write a scalar 'key' and its 'hash_code' into the '*bucket', which was
// found by locateBucketForInsertion(). Assumes that storage for a
// variable-length key copy (if any) was already allocated by a successful
// call to allocateVariableLengthKeyStorage().
inline void writeScalarKeyToBucket(const TypedValue &key,
const std::size_t hash_code,
void *bucket);
// Write a composite 'key' and its 'hash_code' into the '*bucket', which was
// found by locateBucketForInsertion(). Assumes that storage for
// variable-length key copies (if any) was already allocated by a successful
// call to allocateVariableLengthKeyStorage().
inline void writeCompositeKeyToBucket(const std::vector<TypedValue> &key,
const std::size_t hash_code,
void *bucket);
// Determine whether it is actually necessary to resize this hash table.
// Checks that there is at least one empty overflow bucket, and that there is
// at least 'extra_variable_storage' bytes of variable-length storage free.
bool isFull(const std::size_t extra_variable_storage) const;
// Helper object to manage key storage.
HashTableKeyManager<serializable, force_key_copy> key_manager_;
// In-memory structure is as follows:
// - LinearOpenAddressingHashTable::Header
// - Array of hash buckets, each of which is:
// - size_t hash value
// - possibly some unused bytes as needed so that ValueT's alignment
// requirement is met
// - ValueT value slot
// - fixed-length key storage (which may include pointers to external
// memory or offsets of variable length keys stored within this hash
// table)
// - possibly some additional unused bytes so that bucket size is a
// multiple of both alignof(std::atomic<std::size_t>) and
// alignof(ValueT)
// - Variable-length key storage region (referenced by offsets stored in
// fixed-length keys).
Header *header_;
void *hash_buckets_;
const std::size_t bucket_size_;
DISALLOW_COPY_AND_ASSIGN(LinearOpenAddressingHashTable);
};
/** @} */
// ----------------------------------------------------------------------------
// Implementations of template class methods follow.
template <typename ValueT,
bool resizable,
bool serializable,
bool force_key_copy,
bool allow_duplicate_keys>
LinearOpenAddressingHashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys>
::LinearOpenAddressingHashTable(const std::vector<const Type*> &key_types,
const std::size_t num_entries,
StorageManager *storage_manager)
: HashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys>(
key_types,
num_entries,
storage_manager,
true,
false,
false),
key_manager_(this->key_types_, kValueOffset + sizeof(ValueT)),
bucket_size_(ComputeBucketSize(key_manager_.getFixedKeySize())) {
// Give base HashTable information about what key components are stored
// inline from 'key_manager_'.
this->setKeyInline(key_manager_.getKeyInline());
// Pick out a prime number of buckets and calculate storage requirements.
std::size_t num_buckets_tmp = get_next_prime_number(num_entries * kHashTableLoadFactor);
std::size_t required_memory = sizeof(Header)
+ (num_buckets_tmp + kLinearOpenAddressingHashTableNumOverflowBuckets)
* (bucket_size_ + key_manager_.getEstimatedVariableKeySize());
std::size_t num_slots = this->storage_manager_->SlotsNeededForBytes(required_memory);
if (num_slots == 0) {
FATAL_ERROR("Storage requirement for LinearOpenAddressingHashTable "
"exceeds maximum allocation size.");
}
// Get a StorageBlob to hold the hash table.
const block_id blob_id = this->storage_manager_->createBlob(num_slots);
this->blob_ = this->storage_manager_->getBlobMutable(blob_id);
void *aligned_memory_start = this->blob_->getMemoryMutable();
std::size_t available_memory = num_slots * kSlotSizeBytes;
if (align(alignof(Header),
sizeof(Header),
aligned_memory_start,
available_memory)
== nullptr) {
// With current values from StorageConstants.hpp, this should be
// impossible. A blob is at least 1 MB, while a Header has alignment
// requirement of just kCacheLineBytes (64 bytes).
FATAL_ERROR("StorageBlob used to hold resizable "
"LinearOpenAddressingHashTable is too small to meet alignment "
"requirements of LinearOpenAddressingHashTableHeader.");
} else if (aligned_memory_start != this->blob_->getMemoryMutable()) {
// This should also be impossible, since the StorageManager allocates slots
// aligned to kCacheLineBytes.
DEV_WARNING("StorageBlob memory adjusted by "
<< (num_slots * kSlotSizeBytes - available_memory)
<< " bytes to meet alignment requirement for "
<< "LinearOpenAddressingHashTable::Header.");
}
// Locate the header.
header_ = static_cast<Header*>(aligned_memory_start);
available_memory -= sizeof(Header);
hash_buckets_ = static_cast<char*>(aligned_memory_start)
+ sizeof(Header);
// Extra-paranoid: sizeof(Header) should almost certainly be a multiple of
// kBucketAlignment, unless ValueT has some members with seriously big
// (> kCacheLineBytes) alignment requirements specified using alignas().
if (align(kBucketAlignment,
bucket_size_,
hash_buckets_,
available_memory)
== nullptr) {
FATAL_ERROR("StorageBlob used to hold resizable "
"LinearOpenAddressingHashTable is too small to meet "
"alignment requirements of buckets.");
} else if (hash_buckets_
!= reinterpret_cast<const char*>(header_) + sizeof(Header)) {
DEV_WARNING("Bucket array start position adjusted to meet alignment "
"requirement for LinearOpenAddressingHashTable's value type.");
}
// Recompute the number of buckets using the actual available memory. Most
// likely, we got some extra free bucket space due to "rounding up" to the
// storage blob's size. It's also possible (though very unlikely) that we
// will wind up with fewer buckets than we initially wanted because of screwy
// alignment requirements for ValueT, as noted above.
num_buckets_tmp
= get_previous_prime_number((available_memory / (bucket_size_ + key_manager_.getEstimatedVariableKeySize()))
- kLinearOpenAddressingHashTableNumOverflowBuckets);
DEBUG_ASSERT(num_buckets_tmp > 0);
// Fill in the header and initialize buckets.
header_->num_buckets = num_buckets_tmp;
header_->num_overflow_buckets = kLinearOpenAddressingHashTableNumOverflowBuckets;
available_memory -= bucket_size_ * (header_->num_buckets + header_->num_overflow_buckets);
InitializeBuckets(hash_buckets_,
header_->num_buckets + header_->num_overflow_buckets,
bucket_size_,
true);
// There may be some leftover memory from going down to a prime number of
// ordinary buckets. This will be used as extra storage for variable-length
// key segments. Although we could fill it with additional overflow buckets,
// we don't, because it is preferable to resize a HashTable rather than let
// its overflow chain grow very long.
// Locate variable-length key storage region, and give it all the remaining
// bytes in the blob.
header_->variable_length_bytes_allocated.store(0, std::memory_order_relaxed);
key_manager_.setVariableLengthStorageInfo(
static_cast<char*>(hash_buckets_)
+ (header_->num_buckets + header_->num_overflow_buckets) * bucket_size_,
available_memory,
&(header_->variable_length_bytes_allocated));
}
template <typename ValueT,
bool resizable,
bool serializable,
bool force_key_copy,
bool allow_duplicate_keys>
LinearOpenAddressingHashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys>
::LinearOpenAddressingHashTable(const std::vector<const Type*> &key_types,
void *hash_table_memory,
const std::size_t hash_table_memory_size,
const bool new_hash_table,
const bool hash_table_memory_zeroed)
: HashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys>(
key_types,
hash_table_memory,
hash_table_memory_size,
new_hash_table,
hash_table_memory_zeroed,
true,
false,
false),
key_manager_(this->key_types_, kValueOffset + sizeof(ValueT)),
bucket_size_(ComputeBucketSize(key_manager_.getFixedKeySize())) {
// Give base HashTable information about what key components are stored
// inline from 'key_manager_'.
this->setKeyInline(key_manager_.getKeyInline());
// FIXME(chasseur): If we are reconstituting a HashTable using a block of
// memory whose start was aligned differently than the memory block that was
// originally used (modulo alignof(Header)), we could wind up with all of our
// data structures misaligned. If memory is inside a
// StorageBlock/StorageBlob, this will never occur, since the StorageManager
// always allocates slots aligned to kCacheLineBytes. Similarly, this isn't
// a problem for memory inside any other allocation aligned to at least
// alignof(Header) == kCacheLineBytes.
void *aligned_memory_start = this->hash_table_memory_;
std::size_t available_memory = this->hash_table_memory_size_;
if (align(alignof(Header),
sizeof(Header),
aligned_memory_start,
available_memory)
== nullptr) {
FATAL_ERROR("Attempted to create a non-resizable "
<< "LinearOpenAddressingHashTable with "
<< available_memory << " bytes of memory at "
<< aligned_memory_start << " which either can not fit a "
<< "LinearOpenAddressingHashTable::Header or meet its "
<< "alignment requirement.");
} else if (aligned_memory_start != this->hash_table_memory_) {
// In general, we could get memory of any alignment, although at least
// cache-line aligned would be nice.
DEV_WARNING("StorageBlob memory adjusted by "
<< (this->hash_table_memory_size_ - available_memory)
<< " bytes to meet alignment requirement for "
<< "LinearOpenAddressingHashTable::Header.");
}
header_ = static_cast<Header*>(aligned_memory_start);
hash_buckets_ = static_cast<char*>(aligned_memory_start) + sizeof(Header);
// Extra-paranoid: sizeof(Header) should almost certainly be a multiple of
// kBucketAlignment, unless ValueT has some members with seriously big
// (> kCacheLineBytes) alignment requirements specified using alignas().
if (align(kBucketAlignment,
bucket_size_,
hash_buckets_,
available_memory)
== nullptr) {
FATAL_ERROR("Attempted to create a non-resizable "
<< "LinearOpenAddressingHashTable with "
<< this->hash_table_memory_size_ << " bytes of memory at "
<< this->hash_table_memory_ << ", which can hold an aligned "
<< "LinearOpenAddressingHashTable::Header but does not have "
<< "enough remaining space for even a single hash bucket.");
} else if (hash_buckets_ != reinterpret_cast<const char*>(header_) + sizeof(Header)) {
DEV_WARNING("Bucket array start position adjusted to meet alignment "
"requirement for LinearOpenAddressingHashTable's value type.");
}
if (new_hash_table) {
std::size_t estimated_bucket_capacity
= (available_memory - sizeof(Header))
/ (bucket_size_ + key_manager_.getEstimatedVariableKeySize());
std::size_t estimated_overflow_buckets
= estimated_bucket_capacity * kFixedSizeLinearOpenAddressingHashTableOverflowFactor
> kLinearOpenAddressingHashTableNumOverflowBuckets
? kLinearOpenAddressingHashTableNumOverflowBuckets
: estimated_bucket_capacity * kFixedSizeLinearOpenAddressingHashTableOverflowFactor;
std::size_t regular_buckets = get_next_prime_number(
estimated_bucket_capacity - estimated_overflow_buckets);
if (regular_buckets > estimated_bucket_capacity) {
// Next prime was too large. Try the previous prime instead.
regular_buckets = get_previous_prime_number(
estimated_bucket_capacity - estimated_overflow_buckets);
}
// Initialize the header.
header_->num_buckets = regular_buckets;
header_->num_overflow_buckets = estimated_bucket_capacity - regular_buckets;
header_->variable_length_bytes_allocated.store(0, std::memory_order_relaxed);
InitializeBuckets(hash_buckets_,
header_->num_buckets + header_->num_overflow_buckets,
bucket_size_,
hash_table_memory_zeroed);
}
available_memory -= bucket_size_ * (header_->num_buckets + header_->num_overflow_buckets);
// Locate variable-length key storage region.
key_manager_.setVariableLengthStorageInfo(
static_cast<char*>(hash_buckets_)
+ (header_->num_buckets + header_->num_overflow_buckets) * bucket_size_,
available_memory,
&(header_->variable_length_bytes_allocated));
}
template <typename ValueT,
bool resizable,
bool serializable,
bool force_key_copy,
bool allow_duplicate_keys>
void LinearOpenAddressingHashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys>
::clear() {
header_->variable_length_bytes_allocated.store(0, std::memory_order_relaxed);
key_manager_.zeroNextVariableLengthKeyOffset();
DestroyValues(hash_buckets_,
header_->num_buckets + header_->num_overflow_buckets,
bucket_size_);
InitializeBuckets(hash_buckets_,
header_->num_buckets + header_->num_overflow_buckets,
bucket_size_,
false);
}
template <typename ValueT,
bool resizable,
bool serializable,
bool force_key_copy,
bool allow_duplicate_keys>
std::size_t LinearOpenAddressingHashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys>
::numEntries() const {
std::size_t count = 0;
const char *endpos = static_cast<const char*>(hash_buckets_)
+ (header_->num_buckets + header_->num_overflow_buckets) * bucket_size_;
for (const char *bucket = static_cast<const char*>(hash_buckets_);
bucket < endpos;
bucket += bucket_size_) {
count += (reinterpret_cast<const std::atomic<std::size_t>*>(bucket)->load(std::memory_order_relaxed)
!= kEmptyHash);
}
return count;
}
template <typename ValueT,
bool resizable,
bool serializable,
bool force_key_copy,
bool allow_duplicate_keys>
const ValueT* LinearOpenAddressingHashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys>
::getSingle(const TypedValue &key) const {
DEBUG_ASSERT(!allow_duplicate_keys);
DEBUG_ASSERT(this->key_types_.size() == 1);
DEBUG_ASSERT(key.isPlausibleInstanceOf(this->key_types_.front()->getSignature()));
const std::size_t hash_code = this->AdjustHash(key.getHash());
for (std::size_t bucket_num = hash_code % header_->num_buckets;
bucket_num < header_->num_buckets + header_->num_overflow_buckets;
++bucket_num) {
const char *bucket = static_cast<const char*>(hash_buckets_) + bucket_num * bucket_size_;
const std::size_t bucket_hash
= reinterpret_cast<const std::atomic<std::size_t>*>(bucket)->load(std::memory_order_relaxed);
if (bucket_hash == kEmptyHash) {
// Hit an empty bucket without finding 'key'.
return nullptr;
}
// None of the get methods should be called while inserts are still taking
// place.
DEBUG_ASSERT(bucket_hash != kPendingHash);
if ((bucket_hash == hash_code) && key_manager_.scalarKeyCollisionCheck(key, bucket)) {
// Match located.
return reinterpret_cast<const ValueT*>(bucket + kValueOffset);
}
}
// Reached the end of buckets and didn't find a match.
return nullptr;
}
template <typename ValueT,
bool resizable,
bool serializable,
bool force_key_copy,
bool allow_duplicate_keys>
const ValueT* LinearOpenAddressingHashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys>
::getSingleCompositeKey(const std::vector<TypedValue> &key) const {
DEBUG_ASSERT(!allow_duplicate_keys);
DEBUG_ASSERT(this->key_types_.size() == key.size());
const std::size_t hash_code = this->AdjustHash(this->hashCompositeKey(key));
for (std::size_t bucket_num = hash_code % header_->num_buckets;
bucket_num < header_->num_buckets + header_->num_overflow_buckets;
++bucket_num) {
const char *bucket = static_cast<const char*>(hash_buckets_) + bucket_num * bucket_size_;
const std::size_t bucket_hash
= reinterpret_cast<const std::atomic<std::size_t>*>(bucket)->load(std::memory_order_relaxed);
if (bucket_hash == kEmptyHash) {
// Hit an empty bucket without finding 'key'.
return nullptr;
}
// None of the get methods should be called while inserts are still taking
// place.
DEBUG_ASSERT(bucket_hash != kPendingHash);
if ((bucket_hash == hash_code) && key_manager_.compositeKeyCollisionCheck(key, bucket)) {
// Match located.
return reinterpret_cast<const ValueT*>(bucket + kValueOffset);
}
}
// Reached the end of buckets and didn't find a match.
return nullptr;
}
template <typename ValueT,
bool resizable,
bool serializable,
bool force_key_copy,
bool allow_duplicate_keys>
void LinearOpenAddressingHashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys>
::getAll(const TypedValue &key, std::vector<const ValueT*> *values) const {
DEBUG_ASSERT(this->key_types_.size() == 1);
DEBUG_ASSERT(key.isPlausibleInstanceOf(this->key_types_.front()->getSignature()));
const std::size_t hash_code = this->AdjustHash(key.getHash());
for (std::size_t bucket_num = hash_code % header_->num_buckets;
bucket_num < header_->num_buckets + header_->num_overflow_buckets;
++bucket_num) {
const char *bucket = static_cast<const char*>(hash_buckets_) + bucket_num * bucket_size_;
const std::size_t bucket_hash
= reinterpret_cast<const std::atomic<std::size_t>*>(bucket)->load(std::memory_order_relaxed);
if (bucket_hash == kEmptyHash) {
// Hit an empty bucket, so we're finished.
return;
}
// None of the get methods should be called while inserts are still taking
// place.
DEBUG_ASSERT(bucket_hash != kPendingHash);
if ((bucket_hash == hash_code) && key_manager_.scalarKeyCollisionCheck(key, bucket)) {
// Match located.
values->push_back(reinterpret_cast<const ValueT*>(bucket + kValueOffset));
if (!allow_duplicate_keys) {
return;
}
}
}
}
template <typename ValueT,
bool resizable,
bool serializable,
bool force_key_copy,
bool allow_duplicate_keys>
void LinearOpenAddressingHashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys>
::getAllCompositeKey(const std::vector<TypedValue> &key, std::vector<const ValueT*> *values) const {
DEBUG_ASSERT(this->key_types_.size() == key.size());
const std::size_t hash_code = this->AdjustHash(this->hashCompositeKey(key));
for (std::size_t bucket_num = hash_code % header_->num_buckets;
bucket_num < header_->num_buckets + header_->num_overflow_buckets;
++bucket_num) {
const char *bucket = static_cast<const char*>(hash_buckets_) + bucket_num * bucket_size_;
const std::size_t bucket_hash
= reinterpret_cast<const std::atomic<std::size_t>*>(bucket)->load(std::memory_order_relaxed);
if (bucket_hash == kEmptyHash) {
// Hit an empty bucket, so we're finished.
return;
}
// None of the get methods should be called while inserts are still taking
// place.
DEBUG_ASSERT(bucket_hash != kPendingHash);
if ((bucket_hash == hash_code) && key_manager_.compositeKeyCollisionCheck(key, bucket)) {
// Match located.
values->push_back(reinterpret_cast<const ValueT*>(bucket + kValueOffset));
if (!allow_duplicate_keys) {
return;
}
}
}
}
template <typename ValueT,
bool resizable,
bool serializable,
bool force_key_copy,
bool allow_duplicate_keys>
HashTablePutResult
LinearOpenAddressingHashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys>
::putInternal(const TypedValue &key,
const std::size_t variable_key_size,
const ValueT &value,
HashTablePreallocationState *prealloc_state) {
DEBUG_ASSERT(this->key_types_.size() == 1);
DEBUG_ASSERT(key.isPlausibleInstanceOf(this->key_types_.front()->getSignature()));
DEBUG_ASSERT(prealloc_state == nullptr);
// TODO(chasseur): If allow_duplicate_keys is true, avoid storing more than
// one copy of the same variable-length key.
if (!key_manager_.allocateVariableLengthKeyStorage(variable_key_size)) {
// Ran out of variable-length key storage space.
return HashTablePutResult::kOutOfSpace;
}
const std::size_t hash_code = this->AdjustHash(key.getHash());
std::size_t bucket_num = hash_code % header_->num_buckets;
void *bucket = nullptr;
while (bucket_num < header_->num_buckets + header_->num_overflow_buckets) {
if (locateBucketForInsertion(hash_code, &bucket_num, &bucket)) {
// Found an empty bucket.
break;
}
// Found at least a hash collision. Check for duplicate keys if necessary.
if (!allow_duplicate_keys
&& (bucket_num < header_->num_buckets + header_->num_overflow_buckets)
&& key_manager_.scalarKeyCollisionCheck(key, bucket)) {
// Duplicate key. Deallocate any variable storage space and return.
key_manager_.deallocateVariableLengthKeyStorage(variable_key_size);
return HashTablePutResult::kDuplicateKey;
} else {
// Duplicates are allowed, or the hash collision was spurious.
++bucket_num;
}
}
if (bucket_num >= header_->num_buckets + header_->num_overflow_buckets) {
// Ran out of buckets. Deallocate any variable space that we were unable to
// use.
key_manager_.deallocateVariableLengthKeyStorage(variable_key_size);
return HashTablePutResult::kOutOfSpace;
}
writeScalarKeyToBucket(key, hash_code, bucket);
// Store the value by using placement new with ValueT's copy constructor.
new(static_cast<char*>(bucket) + kValueOffset) ValueT(value);
// We're all done.
return HashTablePutResult::kOK;
}
template <typename ValueT,
bool resizable,
bool serializable,
bool force_key_copy,
bool allow_duplicate_keys>
HashTablePutResult
LinearOpenAddressingHashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys>
::putCompositeKeyInternal(const std::vector<TypedValue> &key,
const std::size_t variable_key_size,
const ValueT &value,
HashTablePreallocationState *prealloc_state) {
DEBUG_ASSERT(this->key_types_.size() == key.size());
DEBUG_ASSERT(prealloc_state == nullptr);
// TODO(chasseur): If allow_duplicate_keys is true, avoid storing more than
// one copy of the same variable-length key.
if (!key_manager_.allocateVariableLengthKeyStorage(variable_key_size)) {
// Ran out of variable-length key storage space.
return HashTablePutResult::kOutOfSpace;
}
const std::size_t hash_code = this->AdjustHash(this->hashCompositeKey(key));
std::size_t bucket_num = hash_code % header_->num_buckets;
void *bucket = nullptr;
while (bucket_num < header_->num_buckets + header_->num_overflow_buckets) {
if (locateBucketForInsertion(hash_code, &bucket_num, &bucket)) {
// Found an empty bucket.
break;
}
// Found at least a hash collision. Check for duplicate keys if
// necessary.
if (!allow_duplicate_keys
&& (bucket_num < header_->num_buckets + header_->num_overflow_buckets)
&& key_manager_.compositeKeyCollisionCheck(key, bucket)) {
// Duplicate key. Deallocate any variable storage space and return.
key_manager_.deallocateVariableLengthKeyStorage(variable_key_size);
return HashTablePutResult::kDuplicateKey;
} else {
// Duplicates are allowed, or the hash collision was spurious.
++bucket_num;
}
}
if (bucket_num >= header_->num_buckets + header_->num_overflow_buckets) {
// Ran out of buckets. Deallocate any variable space that we were unable to
// use.
key_manager_.deallocateVariableLengthKeyStorage(variable_key_size);
return HashTablePutResult::kOutOfSpace;
}
writeCompositeKeyToBucket(key, hash_code, bucket);
// Store the value by using placement new with ValueT's copy constructor.
new(static_cast<char*>(bucket) + kValueOffset) ValueT(value);
// We're all done.
return HashTablePutResult::kOK;
}
template <typename ValueT,
bool resizable,
bool serializable,
bool force_key_copy,
bool allow_duplicate_keys>
ValueT* LinearOpenAddressingHashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys>
::upsertInternal(const TypedValue &key,
const std::size_t variable_key_size,
const ValueT &initial_value) {
DEBUG_ASSERT(!allow_duplicate_keys);
DEBUG_ASSERT(this->key_types_.size() == 1);
DEBUG_ASSERT(key.isPlausibleInstanceOf(this->key_types_.front()->getSignature()));
// Block is do/while(false) so we can use break.
do {
if (variable_key_size > 0) {
// Don't allocate yet, since the key may already be present. However, we
// do check if either the allocated variable storage space OR the free
// space is big enough to hold the key (at least one must be true: either
// the key is already present and allocated, or we need to be able to
// allocate enough space for it).
std::size_t allocated_bytes = header_->variable_length_bytes_allocated.load(std::memory_order_relaxed);
if ((allocated_bytes < variable_key_size)
&& (allocated_bytes + variable_key_size > key_manager_.getVariableLengthKeyStorageSize())) {
break;
}
}
const std::size_t hash_code = this->AdjustHash(key.getHash());
std::size_t bucket_num = hash_code % header_->num_buckets;
void *bucket = nullptr;
while (bucket_num < header_->num_buckets + header_->num_overflow_buckets) {
if (locateBucketForInsertion(hash_code, &bucket_num, &bucket)) {
// Found an empty bucket.
break;
} else if ((bucket_num < header_->num_buckets + header_->num_overflow_buckets)
&& key_manager_.scalarKeyCollisionCheck(key, bucket)) {
// Found an already-existing entry for this key.
return reinterpret_cast<ValueT*>(static_cast<char*>(bucket) + kValueOffset);
} else {
++bucket_num;
}
}
if (bucket_num >= header_->num_buckets + header_->num_overflow_buckets) {
// Ran out of buckets.
break;
}
// We are now writing to an empty bucket. Allocate storage for
// variable-length key, if needed.
if (!key_manager_.allocateVariableLengthKeyStorage(variable_key_size)) {
// Allocation failed. Abandon this insert.
static_cast<std::atomic<std::size_t>*>(bucket)->store(kEmptyHash,
std::memory_order_release);
break;
}
// Copy the supplied 'initial_value' into place.
ValueT *value = new(static_cast<char*>(bucket) + kValueOffset) ValueT(initial_value);
// Write the key.
writeScalarKeyToBucket(key, hash_code, bucket);
// Return the value.
return value;
} while (false);
// If we have reached this point without returning, the key was not already
// present and we either failed to find an empty bucket to insert into or
// we failed to allocate enough space to store a variable-length key.
return nullptr;
}
template <typename ValueT,
bool resizable,
bool serializable,
bool force_key_copy,
bool allow_duplicate_keys>
ValueT* LinearOpenAddressingHashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys>
::upsertCompositeKeyInternal(const std::vector<TypedValue> &key,
const std::size_t variable_key_size,
const ValueT &initial_value) {
DEBUG_ASSERT(!allow_duplicate_keys);
DEBUG_ASSERT(this->key_types_.size() == key.size());
// Block is do/while(false) so we can use break.
do {
if (variable_key_size > 0) {
// Don't allocate yet, since the key may already be present. However, we
// do check if either the allocated variable storage space OR the free
// space is big enough to hold the key (at least one must be true: either
// the key is already present and allocated, or we need to be able to
// allocate enough space for it).
std::size_t allocated_bytes = header_->variable_length_bytes_allocated.load(std::memory_order_relaxed);
if ((allocated_bytes < variable_key_size)
&& (allocated_bytes + variable_key_size > key_manager_.getVariableLengthKeyStorageSize())) {
break;
}
}
const std::size_t hash_code = this->AdjustHash(this->hashCompositeKey(key));
std::size_t bucket_num = hash_code % header_->num_buckets;
void *bucket = nullptr;
while (bucket_num < header_->num_buckets + header_->num_overflow_buckets) {
if (locateBucketForInsertion(hash_code, &bucket_num, &bucket)) {
// Found an empty bucket.
break;
} else if ((bucket_num < header_->num_buckets + header_->num_overflow_buckets)
&& key_manager_.compositeKeyCollisionCheck(key, bucket)) {
// Found an already-existing entry for this key.
return reinterpret_cast<ValueT*>(static_cast<char*>(bucket) + kValueOffset);
} else {
++bucket_num;
}
}
if (bucket_num >= header_->num_buckets + header_->num_overflow_buckets) {
// Ran out of buckets.
break;
}
// We are now writing to an empty bucket. Allocate storage for
// variable-length key, if needed.
if (!key_manager_.allocateVariableLengthKeyStorage(variable_key_size)) {
// Allocation failed. Abandon this insert.
static_cast<std::atomic<std::size_t>*>(bucket)->store(kEmptyHash,
std::memory_order_release);
break;
}
// Copy the supplied 'initial_value' into place.
ValueT *value = new(static_cast<char*>(bucket) + kValueOffset) ValueT(initial_value);
// Write the key.
writeCompositeKeyToBucket(key, hash_code, bucket);
// Return the value.
return value;
} while (false);
// If we have reached this point without returning, the key was not already
// present and we either failed to find an empty bucket to insert into or
// we failed to allocate enough space to store a variable-length key.
return nullptr;
}
template <typename ValueT,
bool resizable,
bool serializable,
bool force_key_copy,
bool allow_duplicate_keys>
bool LinearOpenAddressingHashTable<ValueT, resizable, serializable, force_key_copy, allow_duplicate_keys>
::getNextEntry(TypedValue *key, const ValueT **value, std::size_t *entry_num) const {
DEBUG_ASSERT(this->key_types_.size() == 1);
while (*entry_num < header_->num_buckets + header_->num_overflow_buckets) {
const char *bucket = static_cast<const char*>(hash_buckets_) + (*entry_num) * bucket_size_;
const std::size_t bucket_hash
= reinterpret_cast<const std::atomic<std::size_t>*>(bucket)->load(std::memory_order_relaxed);
if (bucket_hash != kEmptyHash) {
DEBUG_ASSERT(bucket_hash != kPendingHash);
*key = key_manager_.getKeyComponentTyped(bucket, 0);
*value = reinterpret_cast<const ValueT*>(bucket + kValueOffset);
// Increment '*entry_num' before returning so that the next call will
// start looking at the next bucket.
++(*entry_num);
return true;
} else {
++(*entry_num);
}
}
return false;
}
template <typename ValueT,
bool resizable,