-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap.h
2508 lines (2290 loc) · 80.9 KB
/
map.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
/**
* \file map.h
*
* This file contains the hash_set, hash_map, and array_map data structures. It
* also defines the default_hash function, which provides a default hash
* algorithm (currently implemented using [xxhash](https://github.com/Cyan4973/xxHash)).
*
* <!-- Created on: May 28, 2014
* Author: asaparov -->
*/
#ifndef MAP_H_
#define MAP_H_
#include <time.h>
#include <initializer_list>
#define XXH_INLINE_ALL
#include "array.h"
#include "xxhash.h"
namespace core {
/**
* For hash_set and hash_map, `capacity` is the size of the underlying array
* (i.e. the number of buckets), whereas `size` is the number of elements (i.e.
* number of non-empty buckets). The functions hash_set::check_size and
* hash_map::check_size compute the load factor `size / capacity` and compare
* it to RESIZE_THRESHOLD. If the load factor is too large, the hashtable is
* resized and the capacity is increased.
*/
#define RESIZE_THRESHOLD 1 / 2
/**
* The multiplicative inverse of RESIZE_THRESHOLD.
*/
#define RESIZE_THRESHOLD_INVERSE 2 / 1
/**
* The multiplicative factor by which hash_set, hash_map, and array_map capacity is changed.
*/
#define RESIZE_FACTOR 2
/**
* A function pointer type describing a function that returns a pointer to
* allocated memory. The first argument is the number of elements to allocate,
* and the second argument is the number of bytes for each element.
* [calloc](http://en.cppreference.com/w/c/memory/calloc) is an example of a
* function with this type.
*/
typedef void*(alloc_keys_func)(size_t, size_t);
/* forward declarations */
#if !defined(DOXYGEN_IGNORE)
template<typename T>
struct hash_set;
template<typename K, typename V>
struct hash_map;
template<typename K, typename V>
struct array_map;
#endif /* DOXYGEN_IGNORE */
#if defined(__LP64__) || defined(_WIN64) || defined(__x86_64__) || defined(__ppc64__)
template<typename K, unsigned int Seed>
inline uint_fast32_t default_hash(const K& key) {
return (uint_fast32_t) XXH64(&key, sizeof(K), Seed);
}
template<typename K, unsigned int Seed>
inline uint_fast32_t default_hash(const K* keys, unsigned int length) {
return (uint_fast32_t) XXH64(keys, sizeof(K) * length, Seed);
}
#else
/**
* Evaluates the hash function of the given value `key` with the given `Seed` using the default implementation.
*/
template<typename K, unsigned int Seed>
inline unsigned int default_hash(const K& key) {
return XXH32(&key, sizeof(K), Seed);
}
/**
* Evaluates the hash function of the given native array of values `keys` with the given `Seed` using the default implementation.
*/
template<typename K, unsigned int Seed>
inline unsigned int default_hash(const K* keys, unsigned int length) {
return XXH32(keys, sizeof(K) * length, Seed);
}
#endif
template<typename KeyMetric, typename ValueMetric>
struct key_value_metric {
const KeyMetric& key_metric;
const ValueMetric& value_metric;
constexpr key_value_metric(const KeyMetric& key_metric, const ValueMetric& value_metric) :
key_metric(key_metric), value_metric(value_metric) { }
};
template<typename KeyMetric, typename ValueMetric>
inline constexpr key_value_metric<KeyMetric, ValueMetric> make_key_value_metric(
const KeyMetric& key_metric, const ValueMetric& value_metric) {
return key_value_metric<KeyMetric, ValueMetric>(key_metric, value_metric);
}
inline constexpr key_value_metric<default_metric, default_metric> make_key_value_metric() {
return make_key_value_metric(default_metric(), default_metric());
}
/**
* <!-- STL-style iterator implementations (useful for range-based for loops). -->
*/
/**
* An iterator implementation, similar to those in the Standard Template
* Library, to enable iteration of elements in a hash_set. This iterator is
* typically initialized using hash_set::begin.
*
* This definition enables the use of range-based for loops.
*/
template<typename T, bool IsConst>
struct hash_set_iterator {
typedef typename std::conditional<IsConst, const hash_set<T>&, hash_set<T>&>::type container_type;
/**
* The type of the entries returned by this iterator. If this is a const
* iterator, `value_type` is `const T&`. Otherwise, `value_type` is `T&`.
*/
typedef typename std::conditional<IsConst, const T&, T&>::type value_type;
container_type set;
unsigned int position;
hash_set_iterator(container_type& set, unsigned int position) : set(set), position(position) { }
/**
* Returns whether this iterator is in the same position as `other`. This
* function assumes the two iterators were created from the same hash_set,
* and that it was not modified.
*/
inline bool operator != (const hash_set_iterator<T, IsConst>& other) const {
return position != other.position;
}
/**
* Returns the element in the hash_set at the current iterator position.
* This function assumes the hash_set was not resized and no element was
* removed since the last call to either the operator `++` or the
* constructor of this iterator, whichever came later.
*/
inline value_type operator * () {
return set.keys[position];
}
/**
* Advances the position of the iterator to the next element in the hash_set.
*/
inline const hash_set_iterator<T, IsConst>& operator ++ () {
do {
++position;
} while (position < set.capacity && hasher<T>::is_empty(set.keys[position]));
return *this;
}
};
/**
* An iterator implementation, similar to those in the Standard Template
* Library, to enable iteration of elements in a hash_map. This iterator is
* typically initialized using hash_map::begin.
*
* This definition enables the use of range-based for loops.
*/
template<typename K, typename V, bool IsConst>
struct hash_map_iterator {
typedef typename std::conditional<IsConst, const hash_map<K, V>&, hash_map<K, V>&>::type container_type;
/**
* The type of the entries returned by this iterator. If this is a const
* iterator, `value_type` is `core::pair<const K&, constV&>`. Otherwise,
* `value_type` is `core::pair<K&, V&>`.
*/
typedef typename std::conditional<IsConst, pair<const K&, const V&>, pair<K&, V&>>::type value_type;
container_type map;
unsigned int position;
hash_map_iterator(container_type& map, unsigned int position) : map(map), position(position) { }
/**
* Returns whether this iterator is in the same position as `other`. This
* function assumes the two iterators were created from the same hash_map,
* and that it was not modified.
*/
inline bool operator != (const hash_map_iterator<K, V, IsConst>& other) const {
return position != other.position;
}
/**
* Returns the entry in the hash_map at the current iterator position. This
* function assumes the hash_map was not resized and no element was removed
* since the last call to either the operator `++` or the constructor of
* this iterator, whichever came later.
*/
inline value_type operator * () {
return { map.table.keys[position], map.values[position] };
}
/**
* Advances the position of the iterator to the next entry in the hash_map.
*/
inline const hash_map_iterator<K, V, IsConst>& operator ++ () {
do {
++position;
} while (position < map.table.capacity && hasher<K>::is_empty(map.table.keys[position]));
return *this;
}
};
/**
* An iterator implementation, similar to those in the Standard Template
* Library, to enable iteration of elements in an array_map. This iterator is
* typically initialized using array_map::begin.
*
* This definition enables the use of range-based for loops.
*/
template<typename K, typename V, bool IsConst>
struct array_map_iterator {
typedef typename std::conditional<IsConst, const array_map<K, V>&, array_map<K, V>&>::type container_type;
/**
* The type of the entries returned by this iterator. If this is a const
* iterator, `value_type` is `core::pair<const K&, constV&>`. Otherwise,
* `value_type` is `core::pair<K&, V&>`.
*/
typedef typename std::conditional<IsConst, pair<const K&, const V&>, pair<K&, V&>>::type value_type;
container_type map;
size_t position;
array_map_iterator(container_type map, size_t position) : map(map), position(position) { }
/**
* Returns whether this iterator is in the same position as `other`. This
* function assumes the two iterators were created from the same array_map,
* and that it was not modified.
*/
inline bool operator != (const array_map_iterator<K, V, IsConst>& other) const {
return position != other.position;
}
/**
* Returns the entry in the array_map at the current iterator position.
* This function assumes the array_map was not resized and no element was
* removed since the last call to either the operator `++` or the
* constructor of this iterator, whichever came later.
*/
inline value_type operator * () {
return{ map.keys[position], map.values[position] };
}
/**
* Advances the position of the iterator to the next entry in the array_map.
*/
inline const array_map_iterator<K, V, IsConst>& operator ++ () {
++position;
return *this;
}
};
/**
* Returns `true` only if `probe > start` and `probe <= end` where `probe`, `start`,
* and `end` are in the additive group of integers modulo the capacity of this set.
*/
inline bool index_between(unsigned int probe, unsigned int start, unsigned int end) {
if (end >= start) {
return (probe > start && probe <= end);
} else {
return (probe <= end || probe > start);
}
}
/**
* An unordered associative container that contains a set of unique elements,
* each of type `T`. The elements are stored in the native array
* hash_set::keys, which has capacity hash_set::capacity. To compute the index
* of an element in hash_set::keys, we first compute its hash. To do so:
* 1. If `T` [is_pointer](http://en.cppreference.com/w/cpp/types/is_pointer),
* [is_fundamental](http://en.cppreference.com/w/cpp/types/is_fundamental),
* or [is_enum](http://en.cppreference.com/w/cpp/types/is_enum),
* core::default_hash() provides the hash.
* 2. For all other types, the `T::hash` function provides the hash.
* Once the hash is computed, the index into hash_set::keys is computed using
* `hash % hash_set::capacity` (modular division by the capacity).
*
* The above approach could produce the same index for distinct elements. This
* event is known as a *collision*. We use
* [linear probing](https://en.wikipedia.org/wiki/Linear_probing)
* to resolve collisions: When adding an element to the hash_set, we compute
* its `index` using the above procedure, then we inspect
* `hash_set::keys[index]` and use core::is_empty() to determine if another
* element already occupies that position. If so, we try the next position
* `(index + 1) % hash_set::capacity`. We continue until we find an empty
* index, and the element is inserted there.
*
* Thus, the function core::is_empty() is used to determine if a position in
* hash_set::keys is occupied or empty. The total number of occupied positions
* is given by hash_set::size. **WARNING:** If hash_set::keys becomes full, the
* above linear probing mechanism could lead to an infinite loop. The function
* hash_set::check_size should be used whenever adding new elements to avoid
* this scenario.
*
* **Performance:** This data structure provides constant-time access and
* modification, given that the load factor (`size / capacity`) is not too
* large.
*
*
* Below is an example of a simple use-case of hash_set, where the expected
* output is `a.contains(2): false, a.contains(3): true, -4 9 3`.
*
* ```{.cpp}
* #include <core/map.h>
* #include <stdio.h>
* using namespace core;
*
* int main() {
* hash_set<int> a = hash_set<int>(8);
* a.add(-1); a.add(-4);
* a.add(3); a.add(9);
* a.remove(-1);
*
* printf("a.contains(2): %s, ", a.contains(2) ? "true" : "false");
* printf("a.contains(3): %s, ", a.contains(3) ? "true" : "false");
* for (int element : a)
* printf("%d ", element);
* }
* ```
*
*
* However, if `a` is not allocated on the stack, the destructor will not be
* automatically called, and so it must be freed manually using `core::free` or
* `hash_set::free`. In the example below, the expected output is the same as
* that of the program above: `a.contains(2): false, a.contains(3): true, -4 9 3`.
*
* ```{.cpp}
* #include <core/map.h>
* #include <stdio.h>
* using namespace core;
*
* int main() {
* hash_set<int>& a = *((hash_set<int>*) alloca(sizeof(hash_set<int>)));
* hash_set_init(a, 8);
* a.add(-1); a.add(-4);
* a.add(3); a.add(9);
* a.remove(-1);
*
* printf("a.contains(2): %s, ", a.contains(2) ? "true" : "false");
* printf("a.contains(3): %s, ", a.contains(3) ? "true" : "false");
* for (int element : a)
* printf("%d ", element);
* free(a);
* }
* ```
*
*
* A number of member functions require `T` to be
* [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable).
* If this is not the case, those operations can be performed directly on the
* public fields, as in the following example. In addition, when using a custom
* struct/class with hash_set, it must implement public static functions, like
* `hash`, `is_empty`, and `move`, as well as the operator `==`. The expected
* output of the following example is `first second `.
*
* ```{.cpp}
* #include <core/map.h>
* #include <stdio.h>
* #include <string.h>
* using namespace core;
*
* struct custom_string {
* char* buffer;
*
* static unsigned int hash(const custom_string& s) {
* return default_hash(s.buffer, strlen(s.buffer));
* }
*
* static bool is_empty(const custom_string& s) {
* return s.buffer == NULL;
* }
*
* static void move(const custom_string& src, custom_string& dst) {
* dst.buffer = src.buffer;
* }
*
* static void free(custom_string& s) {
* core::free(s.buffer);
* }
* };
*
* inline bool operator == (const custom_string& first, const custom_string& second) {
* if (first.buffer == NULL)
* return second.buffer == NULL;
* return strcmp(first.buffer, second.buffer) == 0;
* }
*
* bool init(custom_string& s, const char* src) {
* s.buffer = (char*) malloc(sizeof(char) * (strlen(src) + 1));
* if (s.buffer == NULL)
* return false;
* memcpy(s.buffer, src, sizeof(char) * (strlen(src) + 1));
* return true;
* }
*
* int main() {
* custom_string first, second;
* init(first, "first");
* init(second, "second");
*
* hash_set<custom_string> a = hash_set<custom_string>(8);
* a.check_size(a.size + 2);
*
* bool contains; unsigned int index;
* index = a.index_of(first, contains);
* if (!contains) {
* core::move(first, a.keys[index]);
* a.size++;
* }
*
* index = a.index_of(second, contains);
* if (!contains) {
* core::move(second, a.keys[index]);
* a.size++;
* }
*
* for (const custom_string& s : a)
* printf("%s ", s.buffer);
* for (custom_string& s : a)
* free(s);
* }
* ```
*
* \tparam T the generic type of the elements in the set. `T` must satisfy either:
* 1. [is_fundamental](http://en.cppreference.com/w/cpp/types/is_fundamental),
* 2. [is_enum](http://en.cppreference.com/w/cpp/types/is_enum),
* 3. [is_pointer](http://en.cppreference.com/w/cpp/types/is_pointer),
* 4. implements the public static method `unsigned int hash(const T&)`,
* the public static method `void is_empty(const T&)`, implements the
* operators `==`, and satisfies is_moveable. Some operations also
* require the operator `!=`, and public static methods
* `void set_empty(T&)` and `void set_empty(T*, unsigned int)`.
* **NOTE:** The first argument to the `==` and `!=` operators may be
* empty.
*/
/* TODO: consider other collision resolution mechanisms */
template<typename T>
struct hash_set
{
/**
* The native array of keys underlying the hashtable.
*/
T* keys;
/**
* The capacity of hash_set::keys.
*/
unsigned int capacity;
/**
* The number of elements in the hashtable (i.e. the number of non-empty buckets).
*/
unsigned int size;
/**
* Constructs the hash_set with the given `initial_capacity`.
* \param alloc_keys a memory allocation function with prototype
* `void* alloc_keys(size_t count, size_t size)` that allocates space for
* `count` items, each with size `size`, and initializes them such that
* core::is_empty() returns `true` for each element.
*/
hash_set(unsigned int initial_capacity, alloc_keys_func alloc_keys = calloc) {
if (!initialize(initial_capacity, alloc_keys)) {
fprintf(stderr, "hash_set ERROR: Unable to allocate memory.\n");
exit(EXIT_FAILURE);
}
}
/**
* Constructs the hash_set and inserts the given native array of elements
* `set` with given `length`.
* \param alloc_keys a memory allocation function with prototype
* `void* alloc_keys(size_t count, size_t size)` that allocates space for
* `count` items, each with size `size`, and initializes them such that
* core::is_empty() returns `true` for each element.
*/
hash_set(const T* set, unsigned int length,
alloc_keys_func alloc_keys = calloc) :
hash_set(length * RESIZE_THRESHOLD_INVERSE + 1, alloc_keys)
{
for (unsigned int i = 0; i < length; i++)
insert(set[i]);
}
/**
* Constructs the hash_set and inserts the given
* [initializer_list](http://en.cppreference.com/w/cpp/language/list_initialization)
* of elements `list`.
* \param alloc_keys a memory allocation function with prototype
* `void* alloc_keys(size_t count, size_t size)` that allocates space for
* `count` items, each with size `size`, and initializes them such that
* core::is_empty() returns `true` for each element.
*/
hash_set(const std::initializer_list<T>& list,
alloc_keys_func alloc_keys = calloc) :
hash_set(list.size() * RESIZE_THRESHOLD_INVERSE + 1, alloc_keys)
{
typename std::initializer_list<T>::iterator i;
for (i = list.begin(); i != list.end(); i++)
insert(*i);
}
~hash_set() { free(); }
/**
* Forces the underlying hash_set::keys to be resized to the requested
* `capacity`.
*
* **WARNING:** If `new_capacity <= hash_set::size`, the hashtable could
* become full during the resize process, leading to an infinite loop due
* to the linear probing collision resolution mechanism.
*
* \param alloc_keys a memory allocation function with prototype
* `void* alloc_keys(size_t count, size_t size)` that allocates space for
* `count` items, each with size `size`, and initializes them such that
* core::is_empty() returns `true` for each element.
*/
bool resize(unsigned int new_capacity,
alloc_keys_func alloc_keys = calloc)
{
T* old_keys = keys;
keys = (T*) alloc_keys(new_capacity, sizeof(T));
if (keys == NULL) {
/* revert changes and return error */
keys = old_keys;
return false;
}
/* iterate through keys and re-hash the elements */
unsigned int old_capacity = capacity;
capacity = new_capacity;
for (unsigned int i = 0; i < old_capacity; i++) {
if (!hasher<T>::is_empty(old_keys[i]))
core::move(old_keys[i], keys[next_empty(old_keys[i])]);
}
core::free(old_keys);
return true;
}
/**
* This function first determines whether `hash_set::size < hash_set::capacity * RESIZE_THRESHOLD`.
* If not, the capacity of the underlying hash_set::keys is increased by
* RESIZE_FACTOR until the condition is satisfied. This is useful to ensure
* the hashtable is sufficiently large when preparing to add new elements.
* \param alloc_keys a memory allocation function with prototype
* `void* alloc_keys(size_t count, size_t size)` that allocates space for
* `count` items, each with size `size`, and initializes them such that
* core::is_empty() returns `true` for each element.
* \returns `true` if the resize was successful, and `false` if there is insufficient memory.
*/
inline bool check_size(alloc_keys_func alloc_keys = calloc) {
return check_size(size, alloc_keys);
}
/**
* For a requested number of elements `new_size`, this function first
* determines whether `new_size < hash_set::capacity * RESIZE_THRESHOLD`.
* If not, the capacity of the underlying hashtable is increased by
* RESIZE_FACTOR until the condition is satisfied. This is useful to ensure
* the hashtable is sufficiently large when preparing to add new elements.
* \param alloc_keys a memory allocation function with prototype
* `void* alloc_keys(size_t count, size_t size)` that allocates space for
* `count` items, each with size `size`, and initializes them such that
* core::is_empty() returns `true` for each element.
* \returns `true` if the resize was successful, and `false` if there is insufficient memory.
*/
inline bool check_size(unsigned int new_size, alloc_keys_func alloc_keys = calloc)
{
while (new_size >= capacity * RESIZE_THRESHOLD) {
if (!resize(RESIZE_FACTOR * capacity, alloc_keys)) {
fprintf(stderr, "hash_set.put ERROR: Unable to resize hashtable.\n");
return false;
}
}
return true;
}
/**
* Add the given `element` to this set. The assignment operator is used to
* insert each element, and so this function should not be used if `T` is not
* [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable).
* In such a case, insertion should be performed manually using
* hash_set::index_of to find the appropriate index and directly modifying
* hash_set::keys and hash_set::size. See the example in the hash_set
* description.
* \param alloc_keys a memory allocation function with prototype
* `void* alloc_keys(size_t count, size_t size)` that allocates space for
* `count` items, each with size `size`, and initializes them such that
* core::is_empty() returns `true` for each element.
* \tparam T is [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable).
*/
bool add(const T& element, alloc_keys_func alloc_keys = calloc)
{
if (!check_size(size, alloc_keys)) return false;
insert(element);
return true;
}
/**
* Adds all the elements in the hash_set `elements` to this set. The
* assignment operator is used to insert each element, and so this function
* should not be used if `T` is not
* [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable).
* In such a case, insertion should be performed manually using
* hash_set::index_of or hash_set::index_to_insert to find the appropriate
* index and directly modifying hash_set::keys and hash_set::size. See the
* example in the hash_set description.
* \param alloc_keys a memory allocation function with prototype
* `void* alloc_keys(size_t count, size_t size)` that allocates space for
* `count` items, each with size `size`, and initializes them such that
* core::is_empty() returns `true` for each element.
* \tparam T is [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable).
*/
bool add_all(const hash_set<T>& elements,
alloc_keys_func alloc_keys = calloc)
{
if (!check_size(size + elements.size, alloc_keys)) return false;
for (unsigned int i = 0; i < elements.capacity; i++)
if (!hasher<T>::is_empty(elements.keys[i]))
insert(elements.keys[i]);
return true;
}
/**
* Adds all the elements in the native array `elements` with length `count`
* to this set. The assignment operator is used to insert each element, and
* so this function should not be used if `T` is not
* [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable).
* In such a case, insertion should be performed manually using
* hash_set::index_of or hash_set::index_to_insert and direct modification
* of the public fields.
* \param alloc_keys a memory allocation function with prototype
* `void* alloc_keys(size_t count, size_t size)` that allocates space for
* `count` items, each with size `size`, and initializes them such that
* core::is_empty() returns `true` for each element.
* \tparam T is [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable).
*/
bool add_all(const T* elements, unsigned int count,
alloc_keys_func alloc_keys = calloc)
{
if (!check_size(size + count, alloc_keys)) return false;
for (unsigned int i = 0; i < count; i++)
insert(elements[i]);
return true;
}
/**
* This function removes the given `element` from the set. This function
* does not free the removed element.
* \returns `true` if the element is removed, and `false` if the set does not contain `element`.
*/
bool remove(const T& element)
{
#if !defined(NDEBUG)
if (is_empty(element))
fprintf(stderr, "hash_set.remove WARNING: Specified key is empty.\n");
#endif
unsigned int index = hasher<T>::hash(element) % capacity;
while (true) {
if (keys[index] == element) {
break;
} else if (hasher<T>::is_empty(keys[index]))
return false;
index = (index + 1) % capacity;
}
remove_at(index);
return true;
}
template<typename V>
bool remove(const T& element, V* values)
{
#if !defined(NDEBUG)
if (is_empty(element))
fprintf(stderr, "hash_set.remove WARNING: Specified key is empty.\n");
#endif
unsigned int index = hasher<T>::hash(element) % capacity;
while (true) {
if (keys[index] == element) {
break;
} else if (hasher<T>::is_empty(keys[index]))
return false;
index = (index + 1) % capacity;
}
remove_at(values, index);
return true;
}
/**
* This function removes the element at the bucket given by `index`. This
* function assumes that an element is located at the given bucket with the
* correct provided hash value. This function does not free the removed
* element.
*/
void remove_at(unsigned int index)
{
unsigned int last = index;
unsigned int search = (index + 1) % capacity;
while (!hasher<T>::is_empty(keys[search]))
{
unsigned int search_hash = hasher<T>::hash(keys[search]) % capacity;
if (!index_between(search_hash, last, search)) {
core::move(keys[search], keys[last]);
last = search;
}
search = (search + 1) % capacity;
}
hasher<T>::set_empty(keys[last]);
size--;
}
/**
* Returns `true` if `element` exists in the set, and `false` otherwise.
*/
bool contains(const T& element) const
{
#if !defined(NDEBUG)
if (is_empty(element))
fprintf(stderr, "hashtable.contains WARNING: Specified key is empty.\n");
if (size == capacity)
fprintf(stderr, "hashtable.contains WARNING: Hashtable is full!\n");
#endif
unsigned int index = hasher<T>::hash(element) % capacity;
while (true) {
if (keys[index] == element) {
return true;
} else if (hasher<T>::is_empty(keys[index])) {
return false;
}
index = (index + 1) % capacity;
}
}
/**
* If the given `element` exists in this set, this function returns the
* index of the bucket that contains it. If not, this function returns the
* index where the key would be located, if it had existed in the set.
*/
unsigned int index_of(const T& element) const
{
#if !defined(NDEBUG)
if (is_empty(element))
fprintf(stderr, "hashtable.index_of WARNING: Specified key is empty.\n");
if (size == capacity)
fprintf(stderr, "hashtable.index_of WARNING: Hashtable is full!\n");
#endif
unsigned int index = hasher<T>::hash(element) % capacity;
while (keys[index] != element && !hasher<T>::is_empty(keys[index]))
index = (index + 1) % capacity;
return index;
}
/**
* If the given `element` exists in this set, this function returns the
* index of the bucket that contains it, and sets `contains` to `true`.
* If `element` is not in the set, `contains` is set to false, and this
* function returns the index where the key would be located, if it had
* existed in the set.
*/
inline unsigned int index_of(
const T& element, bool& contains) const
{
unsigned int hash_value;
return index_of(element, contains, hash_value);
}
/**
* If the given `element` exists in this set, this function returns the
* index of the bucket that contains it, and sets `contains` to `true`.
* If `element` is not in the set, `contains` is set to false, and this
* function returns the index where the key would be located, if it had
* existed in the set. In any case, the evaluated hash function of
* `element` is stored in `hash_value`.
*/
unsigned int index_of(const T& element,
bool& contains, unsigned int& hash_value) const
{
#if !defined(NDEBUG)
if (is_empty(element))
fprintf(stderr, "hashtable.index_of WARNING: Specified key is empty.\n");
if (size == capacity)
fprintf(stderr, "hashtable.index_of WARNING: Hashtable is full!\n");
#endif
hash_value = hasher<T>::hash(element);
unsigned int index = hash_value % capacity;
while (true) {
if (keys[index] == element) {
contains = true;
return index;
} else if (hasher<T>::is_empty(keys[index])) {
contains = false;
return index;
}
index = (index + 1) % capacity;
}
}
/**
* For a given `element`, this function computes and returns the index of
* the bucket where the element would be inserted, for example by a call to
* hash_set::add. `contains` is set to `true` if and only if the given
* `element` already exists in the set.
*/
inline unsigned int index_to_insert(const T& element, bool& contains)
{
#if !defined(NDEBUG)
if (size == capacity)
fprintf(stderr, "hashtable.index_to_insert WARNING: Hashtable is full!\n");
#endif
unsigned int index = hasher<T>::hash(element) % capacity;
while (true) {
if (hasher<T>::is_empty(keys[index])) {
contains = false; break;
} if (keys[index] == element) {
contains = true; break;
}
index = (index + 1) % capacity;
}
return index;
}
/**
* For a given `element`, this function computes and returns the index of
* the bucket where the element would be inserted, for example by a call to
* hash_set::add, **assuming** the given element is not in the set.
*/
inline unsigned int index_to_insert(const T& element)
{
#if !defined(NDEBUG)
if (size == capacity)
fprintf(stderr, "hashtable.index_to_insert WARNING: Hashtable is full!\n");
#endif
unsigned int index = hasher<T>::hash(element) % capacity;
while (true) {
if (hasher<T>::is_empty(keys[index])) break;
index = (index + 1) % capacity;
}
return index;
}
/**
* Removes all elements from this hash_set. Note that this function does
* not free each element beforehand.
*/
void clear() {
hasher<T>::set_empty(keys, capacity);
size = 0;
}
/**
* Returns `true` if this hash_set is a subset of `other`.
*/
bool is_subset(const hash_set<T>& other) const
{
for (unsigned int i = 0; i < capacity; i++)
if (!hasher<T>::is_empty(keys[i]) && !other.contains(keys[i]))
return false;
return true;
}
bool equals(const hash_set<T>& other) const
{
if (size != other.size) return false;
return is_subset(other);
}
/**
* Returns a hash_set_iterator pointing to the first element in this container.
*
* **NOTE:** Unlike the libstdc++ [unordered_set](http://en.cppreference.com/w/cpp/container/unordered_set)
* and [unordered_map](http://en.cppreference.com/w/cpp/container/unordered_map)
* iterators, we do not keep a linked list among the elements, so if rapid
* iteration over elements is more critical than rapid queries, consider
* using an array_map.
*/
inline hash_set_iterator<T, false> begin() {
return hash_set_iterator<T, false>(*this, first_empty());
}
/**
* Returns a hash_set_iterator pointing to the end of this container.
*
* **NOTE:** Unlike the libstdc++ [unordered_set](http://en.cppreference.com/w/cpp/container/unordered_set)
* and [unordered_map](http://en.cppreference.com/w/cpp/container/unordered_map)
* iterators, we do not keep a linked list among the elements, so if rapid
* iteration over elements is more critical than rapid queries, consider
* using an array_map.
*/
inline hash_set_iterator<T, false> end() {
return hash_set_iterator<T, false>(*this, capacity);
}
/**
* Returns a const hash_set_iterator pointing to the first element in this container.
*
* **NOTE:** Unlike the libstdc++ [unordered_set](http://en.cppreference.com/w/cpp/container/unordered_set)
* and [unordered_map](http://en.cppreference.com/w/cpp/container/unordered_map)
* iterators, we do not keep a linked list among the elements, so if rapid
* iteration over elements is more critical than rapid queries, consider
* using an array_map.
*/
inline hash_set_iterator<T, true> begin() const {
return hash_set_iterator<T, true>(*this, first_empty());
}
/**
* Returns a const hash_set_iterator pointing to the end of this container.
*
* **NOTE:** Unlike the libstdc++ [unordered_set](http://en.cppreference.com/w/cpp/container/unordered_set)
* and [unordered_map](http://en.cppreference.com/w/cpp/container/unordered_map)
* iterators, we do not keep a linked list among the elements, so if rapid
* iteration over elements is more critical than rapid queries, consider
* using an array_map.
*/
inline hash_set_iterator<T, true> end() const {
return hash_set_iterator<T, true>(*this, capacity);
}
/**
* Swaps the contents of the hash_set `first` with that of `second`.
*/
static void swap(hash_set<T>& first, hash_set<T>& second) {
core::swap(first.keys, second.keys);
core::swap(first.capacity, second.capacity);
core::swap(first.size, second.size);
}
/**
* Moves the contents of the hash_set `src` into `dst`. Note this function
* does not copy the contents of the underlying hash_set::keys, it merely
* copies the pointer.
*/
static inline void move(const hash_set<T>& src, hash_set<T>& dst) {
dst.keys = src.keys;
dst.capacity = src.capacity;
dst.size = src.size;
}
/**
* Copies the contents of the hash_set `src` into `dst`.
* \param alloc_keys a memory allocation function with prototype
* `void* alloc_keys(size_t count, size_t size)` that allocates space for
* `count` items, each with size `size`, and initializes them such that
* core::is_empty() returns `true` for each element.
*/
static inline bool copy(const hash_set<T>& src, hash_set<T>& dst, alloc_keys_func alloc_keys = calloc) {
dst.capacity = src.capacity;
dst.size = src.size;
dst.keys = (T*) alloc_keys(src.capacity, sizeof(T));
if (dst.keys == NULL) return false;
for (unsigned int i = 0; i < src.capacity; i++) {
if (is_empty(src.keys[i])) continue;
if (!copy(src.keys[i], dst.keys[i])) {
free(dst); return false;
}
}
return true;
}
template<typename Metric>
static inline long unsigned int size_of(const hash_set<T>& set, const Metric& metric)
{
long unsigned int sum = core::size_of(set.capacity) + core::size_of(set.size);
for (unsigned int i = 0; i < set.capacity; i++) {