-
Notifications
You must be signed in to change notification settings - Fork 7
/
hashmap.d
2097 lines (1843 loc) · 57.2 KB
/
hashmap.d
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
module cachetools.containers.hashmap;
version(TestingCacheTools) {
import ut;
}
import std.traits;
import std.format;
import std.typecons;
import std.algorithm : map, copy;
import core.memory;
import core.bitop;
import automem: RefCounted, refCounted;
private import std.experimental.allocator;
private import std.experimental.allocator.mallocator : Mallocator;
private import std.experimental.allocator.gc_allocator;
private import cachetools.internal;
private import cachetools.hash;
private import cachetools.containers.lists;
class KeyNotFound : Exception {
this(string msg = "key not found") @safe {
super(msg);
}
}
class KeyRemoved : Exception {
this(string msg = "key not found") @safe {
super(msg);
}
}
static if (hash_t.sizeof == 8) {
enum EMPTY_HASH = 0x00_00_00_00_00_00_00_00;
enum DELETED_HASH = 0x10_00_00_00_00_00_00_00;
enum ALLOCATED_HASH = 0x20_00_00_00_00_00_00_00;
enum TYPE_MASK = 0xF0_00_00_00_00_00_00_00;
enum HASH_MASK = 0x0F_FF_FF_FF_FF_FF_FF_FF;
}
else static if (hash_t.sizeof == 4) {
enum EMPTY_HASH = 0x00_00_00_00;
enum DELETED_HASH = 0x10_00_00_00;
enum ALLOCATED_HASH = 0x20_00_00_00;
enum TYPE_MASK = 0xF0_00_00_00;
enum HASH_MASK = 0x0F_FF_FF_FF;
}
private bool keyEquals(K)(K a, K b) {
static if (is(K == class)) {
if (a is b) {
return true;
}
if (a is null || b is null) {
return false;
}
return a.opEquals(b);
}
else {
return a == b;
}
}
@("L" ~ to!string(__LINE__) ~ ".keyEquals")
@safe nothrow unittest {
class C {
int c;
this(int v) {
c = v;
}
bool opEquals(const C other) const nothrow @safe {
return c == other.c;
}
}
C a = new C(0);
C b = new C(1);
C c = a;
C d = new C(0);
assert(!keyEquals(a, b));
assert(keyEquals(a, c));
assert(keyEquals(a, d));
assert(!keyEquals(null, a));
assert(keyEquals(1, 1));
}
///
struct HashMap(K, V, Allocator = Mallocator, bool GCRangesAllowed = true) {
private enum initial_buckets_num = 32;
alias StoredKeyType = StoredType!K;
alias StoredValueType = StoredType!V;
package {
alias allocator = Allocator.instance;
//
// Bucket is place where we store key, value and hash.
// High bits of hash are used to distinguish between allocated, removed and
// empty buckets.
// Buckets form contigous array. We keep this array refcounted, so that
// we can store reference to it from byPair, byKey, ... even if hashtable itself cleared or
// destroyed.
//
struct _Bucket {
hash_t hash;
StoredKeyType key;
StoredValueType value;
string toString() const {
import std.format;
return "%s, hash: %0x,key: %s, value: %s".format([
EMPTY_HASH: "free",
DELETED_HASH: "deleted",
ALLOCATED_HASH: "allocated"
][cast(long)(hash & TYPE_MASK)], hash, key, value);
}
}
private struct _BucketStorage {
_Bucket[] bs;
this(this) {
auto newbs = makeArray!(_Bucket)(allocator, bs.length);
() @trusted {
static if (UseGCRanges!(Allocator, K, V, GCRangesAllowed)) {
GC.addRange(newbs.ptr, bs.length * _Bucket.sizeof);
}
}();
copy(bs, newbs);
bs = newbs;
}
this(size_t n) {
bs = makeArray!(_Bucket)(allocator, n);
() @trusted {
static if (UseGCRanges!(Allocator, K, V, GCRangesAllowed)) {
GC.addRange(bs.ptr, n * _Bucket.sizeof);
}
}();
}
~this() {
if (!bs.length)
return;
() @trusted {
static if (UseGCRanges!(Allocator, K, V, GCRangesAllowed)) {
GC.removeRange(bs.ptr);
}
}();
dispose(allocator, bs.ptr);
}
}
private alias BucketStorage = RefCounted!(_BucketStorage, Allocator);
BucketStorage _buckets;
int _buckets_num;
int _mask;
int _allocated;
int _deleted;
int _empty;
int _grow_factor = 4;
}
~this() {
clear();
}
this(this) {
auto obuckets = _buckets;
_buckets = BucketStorage(_buckets_num);
copy(obuckets.bs, _buckets.bs);
}
void opAssign(ref typeof(this) rhs) {
auto kv = rhs.byPair; // this will keep current copy of _buckets[]
//
// keep old _buckets_num(to avoid resizes) and _mask;
//
if (rhs is this) {
return;
}
_empty = rhs._empty;
_buckets_num = rhs._buckets_num;
_allocated = rhs._allocated;
_deleted = rhs._deleted;
_mask = rhs._mask;
_grow_factor = rhs.grow_factor;
_buckets = BucketStorage(_buckets_num);
copy(rhs._buckets.bs, _buckets.bs);
}
string toString() {
import std.algorithm, std.array;
auto pairs = byPair;
return "[%s]".format(pairs.map!(p => "%s:%s".format(p.key, p.value)).array.join(", "));
}
invariant {
assert(_allocated >= 0 && _deleted >= 0 && _empty >= 0);
assert(_allocated + _deleted + _empty == _buckets_num);
}
// Find allocated bucket for given key and computed hash starting from start_index
// Returns: index if bucket found or hash_t.max otherwise
//
// Inherits @nogc from K opEquals()
//
private hash_t findEntryIndex(K)(const hash_t start_index, const hash_t hash, ref K key)
in {
assert(hash < DELETED_HASH); // we look for real hash
assert(start_index < _buckets_num); // start position inside array
}
do {
hash_t index = start_index;
do {
immutable h = _buckets.bs[index].hash;
// debug (cachetools)
// safe_tracef("test entry index %d (%s) for key %s", index, _buckets.bs[index], key);
if (h == EMPTY_HASH) {
break;
}
if (h >= ALLOCATED_HASH && (h & HASH_MASK) == hash
&& keyEquals(_buckets.bs[index].key, key)) {
debug (cachetools) safe_tracef("test entry index %d for key %s - success", index, key);
return index;
}
index = (index + 1) & _mask;
}
while (index != start_index);
return hash_t.max;
}
private hash_t findEntryIndex(K)(const hash_t start_index, const hash_t hash, ref K key) const
in {
assert(hash < DELETED_HASH); // we look for real hash
assert(start_index < _buckets_num); // start position inside array
}
do {
hash_t index = start_index;
do {
immutable h = _buckets.bs[index].hash;
// debug (cachetools)
// safe_tracef("test entry index %d (%s) for key %s", index, _buckets.bs[index], key);
if (h == EMPTY_HASH) {
break;
}
if (h >= ALLOCATED_HASH && (h & HASH_MASK) == hash
&& keyEquals(_buckets.bs[index].key, key)) {
debug(cachetools) safe_tracef("test entry index %d for key %s - success", index, key);
return index;
}
index = (index + 1) & _mask;
}
while (index != start_index);
return hash_t.max;
}
//
// Find place where we can insert(DELETED or EMPTY bucket) or update existent (ALLOCATED)
// bucket for key k and precomputed hash starting from start_index
//
//
// Inherits @nogc from K opEquals()
//
private hash_t findUpdateIndex(K)(const hash_t start_index, const hash_t computed_hash, ref K key)
in {
assert(computed_hash < DELETED_HASH);
assert(start_index < _buckets_num);
}
do {
hash_t index = start_index;
do {
immutable h = _buckets.bs[index].hash;
// debug (cachetools)
// safe_tracef("test update index %d (%s) for key %s", index, _buckets.bs[index], key);
if (h <= DELETED_HASH) // empty or deleted
{
// debug (cachetools)
// safe_tracef("test update index %d (%s) for key %s - success",
// index, _buckets.bs[index], key);
return index;
}
assert((h & TYPE_MASK) == ALLOCATED_HASH);
if ((h & HASH_MASK) == computed_hash && keyEquals(_buckets.bs[index].key, key)) {
// debug (cachetools)
// safe_tracef("test update index %d (%s) for key %s - success",
// index, _buckets.bs[index], key);
return index;
}
index = (index + 1) & _mask;
}
while (index != start_index);
return hash_t.max;
}
//
// Find unallocated entry in the buckets slice
// We use this function during resize() only.
//
private long findEmptyIndexExtended(const hash_t start_index,
ref BucketStorage buckets, int new_mask) pure const @safe @nogc
in {
assert(start_index < buckets.bs.length);
}
do {
hash_t index = start_index;
do {
immutable t = buckets.bs[index].hash;
debug (cachetools)
safe_tracef("test empty index %d (%s)", index, buckets.bs[index]);
if (t <= DELETED_HASH) // empty or deleted
{
return index;
}
index = (index + 1) & new_mask;
}
while (index != start_index);
return hash_t.max;
}
private bool tooMuchDeleted() pure const @safe @nogc {
//
// _deleted > _buckets_num / 8
//
//return false;
return _deleted << 3 > _buckets_num;
}
private bool tooHighLoad() pure const @safe @nogc {
//
// _allocated/_buckets_num > 0.8
// 5 * allocated > 4 * buckets_num
//
return _allocated + (_allocated << 2) > _buckets_num << 2;
}
///
/// inserts allowed until next authomatic resize
///
public auto capacity() pure const @safe @nogc {
// capacity = 0.8*buckets_num - _allocated;
return (( _buckets_num << 2 ) / 5) - _allocated;
}
///
/// resize hashmap to new size
///
/// actual new size - closest power of 2
///
public void resize(int new_size) {
if ( new_size <= 0 ) {
assert(0, "new size must be greater than 0");
}
if (popcnt(new_size) > 1) {
immutable p = bsr(new_size);
new_size = 1 << (p + 1);
}
doResize(new_size);
}
private void doResize(int dest) {
immutable _new_buckets_num = dest;
immutable _new_mask = dest - 1;
BucketStorage _new_buckets = BucketStorage(_new_buckets_num);
// iterate over entries
debug (cachetools)
safe_tracef("start resizing: old loadfactor: %s", (1.0 * _allocated) / _buckets_num);
for (int i = 0; i < _buckets_num; i++) {
immutable hash_t h = _buckets.bs[i].hash;
if (h < ALLOCATED_HASH) { // empty or deleted
continue;
}
immutable hash_t start_index = h & _new_mask;
immutable new_position = findEmptyIndexExtended(start_index, _new_buckets, _new_mask);
debug (cachetools)
safe_tracef("old hash: %0x, old pos: %d, new_pos: %d", h, i, new_position);
assert(new_position >= 0);
assert(_new_buckets.bs[cast(hash_t) new_position].hash == EMPTY_HASH);
_new_buckets.bs[cast(hash_t)new_position] = _buckets.bs[i];
}
_buckets = _new_buckets;
_buckets_num = _new_buckets_num;
_mask = _buckets_num - 1;
_deleted = 0;
_empty = _buckets_num - _allocated;
assert(popcnt(_buckets_num) == 1, "Buckets number must be power of 2");
debug (cachetools)
safe_tracef("resizing done: new loadfactor: %s", (1.0 * _allocated) / _buckets_num);
}
//
// Lookup methods
//
private hash_t getLookupIndex(K)(ref K k) {
if (_buckets_num == 0) {
return hash_t.max;
}
immutable computed_hash = hash_function(k) & HASH_MASK;
immutable start_index = computed_hash & _mask;
immutable lookup_index = findEntryIndex(start_index, computed_hash, k);
return lookup_index;
}
private hash_t getLookupIndex(K)(ref K k) const {
if (_buckets_num == 0) {
return hash_t.max;
}
immutable computed_hash = hash_function(k) & HASH_MASK;
immutable start_index = computed_hash & _mask;
immutable lookup_index = findEntryIndex(start_index, computed_hash, k);
return lookup_index;
}
/// key in table
/// Returns: pointer to stored value (if key in table) or null
///
auto opBinaryRight(string op, K)(K k) if (op == "in") {
immutable lookup_index = getLookupIndex(k);
if (lookup_index == hash_t.max) {
return null;
}
static if (is(V == StoredValueType)) {
return &_buckets.bs[lookup_index].value;
}
else {
V* r = cast(V*)&_buckets[lookup_index].value;
return r;
}
}
auto opBinaryRight(string op, K)(K k) const if (op == "in") {
immutable lookup_index = getLookupIndex(k);
if (lookup_index == hash_t.max) {
return null;
}
static if (is(V == StoredValueType)) {
return &_buckets.bs[lookup_index].value;
}
else {
V* r = cast(V*)&_buckets[lookup_index].value;
return r;
}
}
///
/// fetch is safe(do not return pointer) and nogc (do not throw exception)
/// variant of "in" but in exchange of the cost of returning value instead of pointer
/// we return ok = true and value if key in map, ok = false otherwise
///
auto fetch(K)(K k) {
immutable lookup_index = getLookupIndex(k);
if (lookup_index == hash_t.max) {
return tuple!("ok", "value")(false, V.init);
}
return tuple!("ok", "value")(true, _buckets.bs[lookup_index].value);
}
///
/// get value from hash or add if key is not in table. defaultValue can be callable.
/// Returns: ref to value (maybe added)
///
V getOrAdd(K, T)(K k, T defaultValue) {
immutable lookup_index = getLookupIndex(k);
if (lookup_index != hash_t.max) {
return _buckets.bs[lookup_index].value;
}
static if (is(T == V) || isAssignable!(V, T)) {
put(k, defaultValue);
return defaultValue;
}
else static if (isCallable!T && isAssignable!(V, ReturnType!T)) {
auto vv = defaultValue();
put(k, vv);
return vv;
}
else {
static assert(0, "what?");
}
}
///
alias require = getOrAdd;
///
/// Add key/value to hash if key is not in table. value can be lazy/callable.
/// Returns: true if key were added.
///
bool addIfMissed(T)(K k, T value) {
immutable lookup_index = getLookupIndex(k);
if (lookup_index != hash_t.max) {
return false;
}
static if (is(T == V) || isAssignable!(V, T)) {
put(k, value);
return true;
}
else static if (isCallable!T && isAssignable!(V, ReturnType!T)) {
put(k, value());
return true;
}
else {
static assert(0, "Can't assign value");
}
}
/// get current grow factor.
auto grow_factor() const @safe {
return _grow_factor;
}
/// set grow factor (can be between 2, 4 or 8).
void grow_factor(int gf) @safe {
if (gf < 2) {
_grow_factor = 2;
return;
}
if (gf > 8) {
_grow_factor = 8;
return;
}
// enforce new grow_factor is power of 2
if (popcnt(gf) > 1) {
immutable p = bsr(gf);
gf = 1 << (p + 1);
}
_grow_factor = gf;
}
///
/// get with default value
/// it infers @safe, @nogc from user data: do not return ptr and do not thow
///
/// Returns: value from hash, or defaultValue if key not found (see also getOrAdd).
/// defaultValue can be callable.
///
V get(T)(K k, T defaultValue) const {
immutable lookup_index = getLookupIndex(k);
if (lookup_index != hash_t.max) {
return _buckets.bs[lookup_index].value;
}
static if (is(V == T) || isAssignable!(V, T)) {
return defaultValue;
}
else static if (isCallable!T && isAssignable!(V, ReturnType!T)) {
return defaultValue();
}
else {
static assert(0, "You must call 'get' with default value of HashMap 'value' type, or with callable, returning HashMap 'value'");
}
}
V get(T)(K k, T defaultValue) {
immutable lookup_index = getLookupIndex(k);
if (lookup_index != hash_t.max) {
return _buckets.bs[lookup_index].value;
}
static if (is(V == T) || isAssignable!(V, T)) {
return defaultValue;
}
else static if (isCallable!T && isAssignable!(V, ReturnType!T)) {
return defaultValue();
}
else {
static assert(0, "You must call 'get' with default value of HashMap 'value' type, or with callable, returning HashMap 'value'");
}
}
///
/// map[key]
/// Attention: you can't use this method in @nogc code.
/// Usual aa[key] method.
/// Throws exception if key not found
/// Returns: value for given key
///
auto opIndex(K)(K k) inout {
immutable lookup_index = getLookupIndex(k);
if (lookup_index == hash_t.max) {
throw new KeyNotFound();
}
static if (is(V == StoredValueType)) {
return _buckets.bs[lookup_index].value;
}
else {
return cast(V) _buckets.bs[lookup_index].value;
}
}
///
/// map[k] = v;
///
void opIndexAssign(K)(V v, K k)
do {
put(k, v);
}
///
/// put pair (k,v) into hash.
///
/// it must be @safe, it inherits @nogc properties from K and V
/// It can resize table if table is overloaded or has too much deleted entries.
/// Returns: pointer to placed value (pointer is valid until next resize).
///
auto put(K)(K k, V v)
do {
if (!_buckets_num) {
_buckets_num = _empty = initial_buckets_num;
assert(popcnt(_buckets_num) == 1, "Buckets number must be power of 2");
_mask = _buckets_num - 1;
_buckets = BucketStorage(_buckets_num);
}
debug (cachetools)
safe_tracef("put k: %s", k);
if (tooHighLoad) {
doResize(_grow_factor * _buckets_num);
}
immutable computed_hash = hash_function(k) & HASH_MASK;
immutable start_index = computed_hash & _mask;
immutable placement_index = findUpdateIndex(start_index, computed_hash, k);
_Bucket* bucket = &_buckets.bs[placement_index];
immutable h = bucket.hash;
debug (cachetools)
safe_tracef("start_index: %d, placement_index: %d", start_index, placement_index);
//
// Each switch case contains same part of code, so that
// any exception in key or value assignment will not
// leave table in inconsistent state.
//
if (h < ALLOCATED_HASH) {
final switch (h) {
case EMPTY_HASH:
bucket.value = v;
bucket.key = k;
_empty--;
break;
case DELETED_HASH:
bucket.value = v;
bucket.key = k;
_deleted--;
break;
}
bucket.hash = computed_hash | ALLOCATED_HASH;
_allocated++;
return Nullable!(typeof(bucket.value))();
} else {
auto o = nullable(bucket.value);
bucket.value = v;
return o;
}
}
///
/// remomve key from hash.
/// Returns: true if actually removed, false otherwise.
///
bool remove(K k) {
if (tooMuchDeleted) {
// do not shrink, just compact table
doResize(_buckets_num);
}
if (_buckets_num == 0) {
return false;
}
debug (cachetools)
safe_tracef("remove k: %s", k);
immutable lookup_index = getLookupIndex(k);
if (lookup_index == hash_t.max) {
// nothing to remove
return false;
}
assert((_buckets.bs[lookup_index].hash & TYPE_MASK) == ALLOCATED_HASH,
"tried to remove non allocated bucket");
_allocated--;
immutable next_index = (lookup_index + 1) & _mask;
// if next bucket is EMPTY, then we can convert all DELETED buckets down staring from current to EMPTY buckets
if (_buckets.bs[next_index].hash == EMPTY_HASH) {
_empty++;
_buckets.bs[lookup_index].hash = EMPTY_HASH;
auto free_index = (lookup_index - 1) & _mask;
while (free_index != lookup_index) {
if (_buckets.bs[free_index].hash != DELETED_HASH) {
break;
}
_buckets.bs[free_index].hash = EMPTY_HASH;
_deleted--;
_empty++;
free_index = (free_index - 1) & _mask;
}
assert(free_index != lookup_index, "table full of deleted buckets?");
}
else {
_buckets.bs[lookup_index].hash = DELETED_HASH;
_deleted++;
}
return true;
}
/// throw away all keys
void clear() {
_buckets = BucketStorage.init;
_allocated = _deleted = _empty = _buckets_num = 0;
}
/// get numter of keys in table
auto length() const pure nothrow @nogc @safe {
return _allocated;
}
/// get current buckets number
auto size() const pure nothrow @nogc @safe {
return _buckets_num;
}
private struct _kvRange {
int _pos;
size_t _buckets_num;
BucketStorage _buckets;
this(this) {
if (_buckets_num) {
auto _new_buckets = BucketStorage(_buckets_num);
copy(_buckets.bs, _new_buckets.bs);
_buckets = _new_buckets;
_pos = 0;
while (_pos < _buckets_num && _buckets.bs[_pos].hash < ALLOCATED_HASH) {
_pos++;
}
}
}
~this() {
_buckets = BucketStorage.init;
}
this(BucketStorage _b) {
if ( _b !is null ) {
_buckets_num = _b.bs.length;
_buckets = BucketStorage(_buckets_num);
copy(_b.bs, _buckets.bs);
_pos = 0;
while (_pos < _buckets_num && _buckets.bs[_pos].hash < ALLOCATED_HASH) {
_pos++;
}
}
}
bool empty() const pure nothrow @safe @nogc {
return _pos == _buckets_num;
}
auto front() {
return Tuple!(K, "key", V, "value")(_buckets.bs[_pos].key, _buckets.bs[_pos].value);
}
void popFront() pure nothrow @safe @nogc {
_pos++;
while (_pos < _buckets_num && _buckets.bs[_pos].hash < ALLOCATED_HASH) {
_pos++;
}
}
}
/// iterator by keys
auto byKey() {
return _kvRange(_buckets).map!"a.key";
}
/// iterator by values
auto byValue() {
return _kvRange(_buckets).map!"a.value";
}
/// iterator by key/value pairs
auto byPair() {
return _kvRange(_buckets);
}
}
/// Example
@("L" ~ to!string(__LINE__) ~ ".word dictionary")
@safe unittest {
import std.range;
import std.algorithm;
import std.experimental.logger;
HashMap!(string, int) counter;
string[] words = [
"hello", "this", "simple", "example", "should", "succeed", "or", "it",
"should", "fail"
];
// count words, simplest and fastest way
foreach (word; words) {
counter[word] = counter.getOrAdd(word, 0) + 1;
}
assert(counter.capacity == 32*4/5 - counter.length);
assert(!counter.fetch("world").ok);
assert(counter["hello"] == 1);
assert(counter["should"] == 2);
assert(counter.length == words.length - 1);
// clear counter
counter.clear;
assert(counter.length == 0);
// more verbose way to count
foreach (word; words) {
auto w = word in counter;
if (w) {
(*w)++;
}
else {
counter[word] = 1;
}
}
assert(!counter.fetch("world").ok);
assert(counter["hello"] == 1);
assert(counter["should"] == 2);
assert(counter.length == words.length - 1);
// iterators
assert(counter.byKey.count == counter.byValue.count);
assert(words.all!(w => w in counter)); // all words are in table
assert(counter.byValue.sum == words.length); // sum of counters must equals to number of words
}
// Tests
@("L" ~ to!string(__LINE__) ~ ".remove")
@safe unittest {
// test of nogc getOrAdd
import std.experimental.logger;
globalLogLevel = LogLevel.info;
import std.meta;
static foreach (T; AliasSeq!(HashMap!(int, int))) {
() @nogc nothrow{
T hashMap;
debug (cachetools)
safe_tracef("Testing %s", typeid(T));
foreach (i; 0 .. 10) {
hashMap.put(i, i);
}
foreach (i; 0 .. 10) {
hashMap.put(i, i);
}
foreach (i; 0 .. 10) {
auto v = hashMap.fetch(i);
assert(v.ok && v.value == i);
}
assert(hashMap.length == 10);
hashMap.remove(0);
assert(hashMap.length == 9);
assert(!hashMap.fetch(0).ok);
hashMap.remove(1);
assert(hashMap.length == 8);
assert(!hashMap.fetch(1).ok);
assert(hashMap.fetch(8).ok);
hashMap.remove(8);
assert(hashMap.length == 7);
assert(!hashMap.fetch(8).ok);
foreach (i; 0 .. 10) {
hashMap.put(i, i);
}
assert(hashMap.length == 10);
hashMap.remove(8);
hashMap.remove(1);
assert(hashMap.length == 8);
assert(!hashMap.fetch(1).ok);
assert(!hashMap.fetch(8).ok);
assert(hashMap.remove(1) == false);
foreach (i; 0 .. 10) {
hashMap.remove(i);
}
assert(hashMap.length == 0);
}();
}
//auto v = hashMap.getOrAdd(-1, -1);
//assert(-1 in hashMap && v == -1);
globalLogLevel = LogLevel.info;
}
// test get()
@("L" ~ to!string(__LINE__) ~ ".get")
@safe @nogc nothrow unittest {
import std.meta;
static foreach (T; AliasSeq!(HashMap!(int, int))) {
{
T hashMap;
int i = hashMap.get(1, 55);
assert(i == 55);
i = hashMap.get(1, () => 66);
assert(i == 66);
hashMap[1] = 1;
i = hashMap.get(1, () => 66);
assert(i == 1);
}
}
}
// test immutable struct and class as Key type
@("L" ~ to!string(__LINE__) ~ ".immutable struct and class as Key type")
@safe unittest {
import std.experimental.logger;
globalLogLevel = LogLevel.info;
info("Testing hash tables");
import std.meta;
struct S {
int s;
}
static foreach (T; AliasSeq!(HashMap!(immutable S, int))) {
() @nogc nothrow{
T hs1;
immutable ss = S(1);
hs1[ss] = 1;
assert(ss in hs1 && *(ss in hs1) == 1);
}();
}
static foreach (T; AliasSeq!(HashMap!(int, immutable S))) {
() @nogc nothrow{
T hs2;
immutable ss = S(1);
hs2[1] = ss;
// assert(1 in hs2 && *(1 in hs2) == ss);
// assert(!(2 in hs2));
}();
}
// class
class C {
int v;
this(int _v) pure inout {
v = _v;
}
bool opEquals(const C o) pure const @safe @nogc nothrow {
return v == o.v;
}
override hash_t toHash() const @safe @nogc {
return hash_function(v);
}
}
static foreach (T; AliasSeq!(HashMap!(immutable C, int))) {
{
T hc1;
immutable cc = new immutable C(1);
hc1[cc] = 1;
assert(hc1[cc] == 1);
}
}
static foreach (T; AliasSeq!(HashMap!(int, immutable C))) {
{
immutable cc = new immutable C(1);
T hc2;