/
hashmap.d
676 lines (602 loc) · 14.6 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
/**
* Hash Map
* Copyright: © 2015 Economic Modeling Specialists, Intl.
* Authors: Brian Schott
* License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
*/
module containers.hashmap;
private import containers.internal.hash : generateHash;
private import containers.internal.node : shouldAddGCRange;
private import stdx.allocator.mallocator : Mallocator;
private import std.traits : isBasicType, Unqual;
/**
* Associative array / hash map.
* Params:
* K = the key type
* V = the value type
* Allocator = the allocator type to use. Defaults to `Mallocator`
* hashFunction = the hash function to use on the keys
* supportGC = true if the container should support holding references to
* GC-allocated memory.
*/
struct HashMap(K, V, Allocator = Mallocator, alias hashFunction = generateHash!K,
bool supportGC = shouldAddGCRange!K || shouldAddGCRange!V)
{
this(this) @disable;
private import stdx.allocator.common : stateSize;
static if (stateSize!Allocator != 0)
{
this() @disable;
/**
* Use the given `allocator` for allocations.
*/
this(Allocator allocator) pure nothrow @nogc @safe
in
{
assert(allocator !is null, "Allocator must not be null");
}
body
{
this.allocator = allocator;
}
/**
* Constructs an HashMap with an initial bucket count of bucketCount. bucketCount
* must be a power of two.
*/
this(size_t bucketCount, Allocator allocator)
in
{
assert(allocator !is null, "Allocator must not be null");
assert((bucketCount & (bucketCount - 1)) == 0, "bucketCount must be a power of two");
}
body
{
this.allocator = allocator;
initialize(bucketCount);
}
invariant
{
assert(allocator !is null);
}
}
else
{
/**
* Constructs an HashMap with an initial bucket count of bucketCount. bucketCount
* must be a power of two.
*/
this(size_t bucketCount)
in
{
assert((bucketCount & (bucketCount - 1)) == 0, "bucketCount must be a power of two");
}
body
{
initialize(bucketCount);
}
}
~this() nothrow
{
scope (failure) assert(false);
clear();
}
/**
* Removes all items from the map
*/
void clear()
{
import stdx.allocator : dispose;
// always remove ranges from GC first before disposing of buckets, to
// prevent segfaults when the GC collects at an unfortunate time
static if (useGC)
GC.removeRange(buckets.ptr);
allocator.dispose(buckets);
buckets = null;
_length = 0;
}
/**
* Supports `aa[key]` syntax.
*/
ref opIndex(this This)(K key)
{
import std.conv : text;
import std.exception : enforce;
alias CET = ContainerElementType!(This, V);
size_t i;
auto n = find(key, i);
enforce(n !is null, "'" ~ text(key) ~ "' not found in HashMap");
return *cast(CET*) &n.value;
}
/**
* Returns: `true` if there is an entry in this map for the given `key`,
* false otherwise.
*/
bool containsKey(this This)(K key) inout pure @nogc @safe
{
return find(key) !is null;
}
/**
* Gets the value for the given key, or returns `defaultValue` if the given
* key is not present.
*
* Params:
* key = the key to look up
* value = the default value
* Returns: the value indexed by `key`, if present, or `defaultValue` otherwise.
*/
auto get(this This)(K key, lazy V defaultValue)
{
alias CET = ContainerElementType!(This, V);
size_t i;
auto n = find(key, i);
if (n is null)
return defaultValue;
return cast(CET) n.value;
}
/**
* If the given key does not exist in the HashMap, adds it with
* the value `defaultValue`.
*
* Params:
* key = the key to look up
* value = the default value
* Returns: a pointer to the value stored in the HashMap with the given key.
* The pointer is guaranteed to be valid only until the next HashMap
* modification.
*/
auto getOrAdd(this This)(K key, lazy V defaultValue)
{
alias CET = ContainerElementType!(This, V);
Hash hash = hashFunction(key);
auto n = find(key, hash);
if (n is null)
return cast(CET*) &insert(key, defaultValue).value;
else
return cast(CET*) &n.value;
}
/**
* Supports $(B aa[key] = value;) syntax.
*/
void opIndexAssign(V value, const K key)
{
insert(key, value);
}
/**
* Supports $(B key in aa) syntax.
*
* Returns: pointer to the value corresponding to the given key,
* or null if the key is not present in the HashMap.
*/
inout(V)* opBinaryRight(string op)(const K key) inout nothrow @trusted if (op == "in")
{
size_t i;
auto n = find(key, i);
if (n is null)
return null;
return &(cast(inout) n).value;
}
/**
* Removes the value associated with the given key
* Returns: true if a value was actually removed.
*/
bool remove(K key)
{
size_t i;
auto n = find(key, i);
if (n is null)
return false;
immutable bool removed = buckets[i].remove(Node(n.hash, n.key));
if (removed)
_length--;
return removed;
}
/**
* Returns: the number of key/value pairs in this container.
*/
size_t length() const nothrow pure @property @safe @nogc
{
return _length;
}
/**
* Returns: `true` if there are no items in this container.
*/
bool empty() const nothrow pure @property @safe @nogc
{
return _length == 0;
}
/**
* Returns: a range of the keys in this map.
*/
auto byKey(this This)() inout @trusted
{
return MapRange!(This, IterType.key)(cast(Unqual!(This)*) &this);
}
/**
* Returns: a GC-allocated array filled with the keys contained in this map.
*/
K[] keys() const @property
out(result)
{
assert (result.length == _length);
}
body
{
import std.array : appender;
auto app = appender!(K[])();
foreach (ref const bucket; buckets)
{
foreach (item; bucket)
app.put(cast(K) item.key);
}
return app.data;
}
/**
* Returns: a range of the values in this map.
*/
auto byValue(this This)() inout @trusted
{
return MapRange!(This, IterType.value)(cast(Unqual!(This)*) &this);
}
/// ditto
alias opSlice = byValue;
/**
* Returns: a GC-allocated array containing the values contained in this map.
*/
auto values(this This)() const @property
out(result)
{
assert (result.length == _length);
}
body
{
import std.array : appender;
auto app = appender!(ContainerElementType!(This, V)[])();
foreach (ref const bucket; buckets)
{
foreach (item; bucket)
app.put(cast(ContainerElementType!(This, V)) item.value);
}
return app.data;
}
/**
* Returns: a range of the kev/value pairs in this map. The element type of
* this range is a struct with `key` and `value` fields.
*/
auto byKeyValue(this This)() inout @trusted
{
return MapRange!(This, IterType.both)(cast(Unqual!(This)*) &this);
}
mixin AllocatorState!Allocator;
private:
import stdx.allocator : make, makeArray;
import containers.unrolledlist : UnrolledList;
import containers.internal.storage_type : ContainerStorageType;
import containers.internal.element_type : ContainerElementType;
import containers.internal.mixins : AllocatorState;
import core.memory : GC;
enum bool useGC = supportGC && (shouldAddGCRange!K || shouldAddGCRange!V);
alias Hash = typeof({ K k = void; return hashFunction(k); }());
enum IterType: ubyte
{
key, value, both
}
static struct MapRange(MapType, IterType Type)
{
static if (Type == IterType.both)
{
struct FrontType
{
ContainerElementType!(MapType, K) key;
ContainerElementType!(MapType, V) value;
}
}
else static if (Type == IterType.value)
alias FrontType = ContainerElementType!(MapType, V);
else static if (Type == IterType.key)
alias FrontType = ContainerElementType!(MapType, K);
else
static assert(false);
FrontType front()
{
static if (Type == IterType.both)
return FrontType(cast(ContainerElementType!(MapType, K)) bucketRange.front.key,
cast(ContainerElementType!(MapType, V)) bucketRange.front.value);
else static if (Type == IterType.value)
return cast(ContainerElementType!(MapType, V)) bucketRange.front.value;
else static if (Type == IterType.key)
return cast(ContainerElementType!(MapType, K)) bucketRange.front.key;
else
static assert(false);
}
bool empty() const pure nothrow @nogc @property
{
return _empty;
}
void popFront() pure nothrow @nogc
{
bucketRange.popFront();
if (bucketRange.empty)
{
while (bucketRange.empty)
{
bucketIndex++;
if (bucketIndex >= hm.buckets.length)
{
_empty = true;
break;
}
else
bucketRange = hm.buckets[bucketIndex][];
}
}
}
private:
this(Unqual!(MapType)* hm)
{
this.hm = hm;
this.bucketIndex = 0;
bucketRange = typeof(bucketRange).init;
this._empty = false;
while (true)
{
if (bucketIndex >= hm.buckets.length)
{
_empty = true;
break;
}
bucketRange = hm.buckets[bucketIndex][];
if (bucketRange.empty)
bucketIndex++;
else
break;
}
}
Unqual!(MapType)* hm;
size_t bucketIndex;
typeof(hm.buckets[0].opSlice()) bucketRange;
bool _empty;
}
void initialize(size_t bucketCount = 4)
{
import std.conv : emplace;
assert((bucketCount & (bucketCount - 1)) == 0, "bucketCount must be a power of two");
buckets = makeArray!Bucket(allocator, bucketCount);
static if (useGC)
GC.addRange(buckets.ptr, buckets.length * Bucket.sizeof);
foreach (ref bucket; buckets)
{
static if (stateSize!Allocator == 0)
emplace(&bucket);
else
emplace(&bucket, allocator);
}
}
Node* insert(const K key, V value)
{
return insert(key, value, hashFunction(key));
}
Node* insert(const K key, V value, const Hash hash, const bool modifyLength = true)
{
if (buckets.length == 0)
initialize();
immutable size_t index = hashToIndex(hash);
foreach (ref item; buckets[index])
{
if (item.hash == hash && item.key == key)
{
item.value = value;
return &item;
}
}
Node* n;
n = buckets[index].insertAnywhere(Node(hash, cast(ContainerStorageType!K) key, value));
if (modifyLength)
_length++;
if (shouldRehash())
rehash();
return n;
}
/**
* Returns: true if the load factor has been exceeded
*/
bool shouldRehash() const pure nothrow @safe @nogc
{
// We let this be greater than one because each bucket is an unrolled
// list that has more than one element per linked list node.
return (float(_length) / float(buckets.length)) > 1.33f;
}
/**
* Rehash the map.
*/
void rehash() @trusted
{
import std.conv : emplace;
immutable size_t newLength = buckets.length << 1;
immutable size_t newSize = newLength * Bucket.sizeof;
Bucket[] oldBuckets = buckets;
assert (oldBuckets.ptr == buckets.ptr);
buckets = cast(Bucket[]) allocator.allocate(newSize);
static if (useGC)
GC.addRange(buckets.ptr, buckets.length * Bucket.sizeof);
assert (buckets);
assert (buckets.length == newLength);
foreach (ref bucket; buckets)
{
static if (stateSize!Allocator == 0)
emplace(&bucket);
else
emplace(&bucket, allocator);
}
foreach (ref bucket; oldBuckets)
{
foreach (node; bucket)
insert(cast(K) node.key, node.value, node.hash, false);
typeid(typeof(bucket)).destroy(&bucket);
}
static if (useGC)
GC.removeRange(oldBuckets.ptr);
allocator.deallocate(cast(void[]) oldBuckets);
}
size_t hashToIndex(Hash hash) const pure nothrow @safe @nogc
in
{
assert (buckets.length > 0);
}
out (result)
{
assert (result < buckets.length);
}
body
{
return cast(size_t)hash & (buckets.length - 1);
}
inout(Node)* find(const K key, ref size_t index) inout
{
return find(key, index, hashFunction(key));
}
inout(Node)* find(const K key, ref size_t index, const Hash hash) inout
{
import std.array : empty;
if (buckets.empty)
return null;
index = hashToIndex(hash);
foreach (ref r; buckets[index])
{
if (r.hash == hash && r == key)
return cast(inout(Node)*) &r;
}
return null;
}
struct Node
{
bool opEquals(ref const K key) const
{
return key == this.key;
}
bool opEquals(ref const Node n) const
{
return this.hash == n.hash && this.key == n.key;
}
Hash hash;
ContainerStorageType!K key;
ContainerStorageType!V value;
}
alias Bucket = UnrolledList!(Node, Allocator, useGC);
Bucket[] buckets;
size_t _length;
}
///
unittest
{
import std.uuid : randomUUID;
import std.range.primitives : walkLength;
auto hm = HashMap!(string, int)(16);
assert (hm.length == 0);
assert (!hm.remove("abc"));
hm["answer"] = 42;
assert (hm.length == 1);
assert ("answer" in hm);
hm.remove("answer");
assert (hm.length == 0);
hm["one"] = 1;
hm["one"] = 1;
assert (hm.length == 1);
assert (hm["one"] == 1);
hm["one"] = 2;
assert(hm["one"] == 2);
foreach (i; 0 .. 1000)
{
hm[randomUUID().toString] = i;
}
assert (hm.length == 1001);
assert (hm.keys().length == hm.length);
assert (hm.values().length == hm.length);
() @nogc {
assert (hm.byKey().walkLength == hm.length);
assert (hm.byValue().walkLength == hm.length);
assert (hm[].walkLength == hm.length);
assert (hm.byKeyValue().walkLength == hm.length);
}();
foreach (v; hm) {}
auto hm2 = HashMap!(char, char)(4);
hm2['a'] = 'a';
HashMap!(int, int) hm3;
assert (hm3.get(100, 20) == 20);
hm3[100] = 1;
assert (hm3.get(100, 20) == 1);
auto pValue = 100 in hm3;
assert(*pValue == 1);
}
version(emsi_containers_unittest) unittest
{
static class Foo
{
string name;
}
void someFunc(ref in HashMap!(string,Foo) map) @safe
{
foreach (kv; map.byKeyValue())
{
assert (kv.key == "foo");
assert (kv.value.name == "Foo");
}
}
auto hm = HashMap!(string, Foo)(16);
auto f = new Foo;
f.name = "Foo";
hm.insert("foo", f);
assert("foo" in hm);
}
// Issue #54
version(emsi_containers_unittest) unittest
{
HashMap!(string, int) map;
map.insert("foo", 0);
map.insert("bar", 0);
foreach (key; map.keys())
map[key] = 1;
foreach (key; map.byKey())
map[key] = 1;
foreach (value; map.byValue())
assert(value == 1);
foreach (value; map.values())
assert(value == 1);
}
version(emsi_containers_unittest) unittest
{
HashMap!(int, int) map;
auto p = map.getOrAdd(1, 1);
assert(*p == 1);
*p = 2;
assert(map[1] == 2);
}
debug (EMSI_CONTAINERS) version(emsi_containers_unittest) unittest
{
import std.uuid : randomUUID;
import std.algorithm.iteration : walkLength;
import std.stdio;
auto hm = HashMap!(string, int)(16);
foreach (i; 0 .. 1_000_000)
{
auto str = randomUUID().toString;
//writeln("Inserting ", str);
hm[str] = i;
//if (i > 0 && i % 100 == 0)
//writeln(i);
}
writeln(hm.buckets.length);
import std.algorithm.sorting:sort;
ulong[ulong] counts;
foreach (i, ref bucket; hm.buckets[])
counts[bucket.length]++;
foreach (k; counts.keys.sort())
writeln(k, "=>", counts[k]);
}
// #74
version(emsi_containers_unittest) unittest
{
HashMap!(string, size_t) aa;
aa["b"] = 0;
++aa["b"];
assert(aa["b"] == 1);
}