forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash_map.zig
1364 lines (1118 loc) · 46.9 KB
/
hash_map.zig
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
// This is the previous version of the hash map implementation built in to zig
// except, with a getWithHash(key: K)
// and a hash getWithHash(key: K)
// This improved JS parser performance due to being able to reuse hash keys when looking up symbol table entries
const std = @import("std");
const assert = debug.assert;
const autoHash = std.hash.autoHash;
const debug = std.debug;
const warn = debug.warn;
const math = std.math;
const mem = std.mem;
const meta = std.meta;
const trait = meta.trait;
const Allocator = mem.Allocator;
const Wyhash = std.hash.Wyhash;
pub fn getAutoHashFn(comptime K: type) (fn (K) u64) {
comptime {
assert(@hasDecl(std, "StringHashMap")); // detect when the following message needs updated
if (K == []const u8) {
@compileError("std.auto_hash.autoHash does not allow slices here (" ++
@typeName(K) ++
") because the intent is unclear. " ++
"Consider using std.StringHashMap for hashing the contents of []const u8. " ++
"Alternatively, consider using std.auto_hash.hash or providing your own hash function instead.");
}
}
return struct {
fn hash(key: K) u64 {
if (comptime trait.hasUniqueRepresentation(K)) {
return Wyhash.hash(0, std.mem.asBytes(&key));
} else {
var hasher = Wyhash.init(0);
autoHash(&hasher, key);
return hasher.final();
}
}
}.hash;
}
const autoEqlTrait = std.meta.trait.hasFn("eql");
pub fn getAutoEqlFn(comptime K: type) (fn (K, K) bool) {
if (comptime autoEqlTrait(K)) {
return @field(K, "eql");
}
return struct {
fn eql(a: K, b: K) bool {
return meta.eql(a, b);
}
}.eql;
}
pub fn AutoHashMap(comptime K: type, comptime V: type) type {
return HashMap(K, V, getAutoHashFn(K), getAutoEqlFn(K), default_max_load_percentage);
}
pub fn AutoHashMapUnmanaged(comptime K: type, comptime V: type) type {
return HashMapUnmanaged(K, V, getAutoHashFn(K), getAutoEqlFn(K), default_max_load_percentage);
}
/// Builtin hashmap for strings as keys.
pub fn StringHashMap(comptime V: type) type {
return HashMap([]const u8, V, hashString, eqlString, default_max_load_percentage);
}
pub fn StringHashMapUnmanaged(comptime V: type) type {
return HashMapUnmanaged([]const u8, V, hashString, eqlString, default_max_load_percentage);
}
// ❯ hyperfine "./bun.stringEqlNoPtrCheck --resolve=dev --cwd /Users/jarred/Code/bun/bench/rome/src entry --platform=node --outdir=/Users/jarred/Code/bun/bench/rome/src/out --origin=https://hello.com/" "./bun-fd-rel-hash --resolve=dev --cwd /Users/jarred/Code/bun/bench/rome/src entry --platform=node --outdir=/Users/jarred/Code/bun/bench/rome/src/out --origin=https://hello.com/" --min-runs=50
// Benchmark #1: ./bun.stringEqlNoPtrCheck --resolve=dev --cwd /Users/jarred/Code/bun/bench/rome/src entry --platform=node --outdir=/Users/jarred/Code/bun/bench/rome/src/out --origin=https://hello.com/
// Time (mean ± σ): 251.5 ms ± 7.8 ms [User: 110.0 ms, System: 135.7 ms]
// Range (min … max): 239.0 ms … 281.1 ms 50 runs
// Benchmark #2: ./bun-fd-rel-hash --resolve=dev --cwd /Users/jarred/Code/bun/bench/rome/src entry --platform=node --outdir=/Users/jarred/Code/bun/bench/rome/src/out --origin=https://hello.com/
// Time (mean ± σ): 249.3 ms ± 8.3 ms [User: 110.8 ms, System: 134.0 ms]
// Range (min … max): 239.8 ms … 288.7 ms 50 runs
// Summary
// './bun-fd-rel-hash --resolve=dev --cwd /Users/jarred/Code/bun/bench/rome/src entry --platform=node --outdir=/Users/jarred/Code/bun/bench/rome/src/out --origin=https://hello.com/' ran
// 1.01 ± 0.05 times faster than './bun.stringEqlNoPtrCheck --resolve=dev --cwd /Users/jarred/Code/bun/bench/rome/src entry --platform=node --outdir=/Users/jarred/Code/bun/bench/rome/src/out --origin=https://hello.com/'
pub fn eqlString(a: []const u8, b: []const u8) bool {
return mem.eql(u8, a, b);
}
pub fn hashString(s: []const u8) u64 {
return std.hash.Wyhash.hash(0, s);
}
/// Deprecated use `default_max_load_percentage`
pub const DefaultMaxLoadPercentage = default_max_load_percentage;
pub const default_max_load_percentage = 80;
/// General purpose hash table.
/// No order is guaranteed and any modification invalidates live iterators.
/// It provides fast operations (lookup, insertion, deletion) with quite high
/// load factors (up to 80% by default) for a low memory usage.
/// For a hash map that can be initialized directly that does not store an Allocator
/// field, see `HashMapUnmanaged`.
/// If iterating over the table entries is a strong usecase and needs to be fast,
/// prefer the alternative `std.ArrayHashMap`.
pub fn HashMap(
comptime K: type,
comptime V: type,
comptime hashFn: fn (key: K) u64,
comptime eqlFn: fn (a: K, b: K) bool,
comptime max_load_percentage: u64,
) type {
return struct {
unmanaged: Unmanaged,
allocator: Allocator,
pub const Unmanaged = HashMapUnmanaged(K, V, hashFn, eqlFn, max_load_percentage);
pub const Entry = Unmanaged.Entry;
pub const Hash = Unmanaged.Hash;
pub const Iterator = Unmanaged.Iterator;
pub const Size = Unmanaged.Size;
pub const GetOrPutResult = Unmanaged.GetOrPutResult;
const Self = @This();
pub fn init(allocator: Allocator) Self {
return .{
.unmanaged = .{},
.allocator = allocator,
};
}
pub fn deinit(self: *Self) void {
self.unmanaged.deinit(self.allocator);
self.* = undefined;
}
pub fn clearRetainingCapacity(self: *Self) void {
return self.unmanaged.clearRetainingCapacity();
}
pub fn clearAndFree(self: *Self) void {
return self.unmanaged.clearAndFree(self.allocator);
}
pub fn count(self: Self) Size {
return self.unmanaged.count();
}
pub fn iterator(self: *const Self) Iterator {
return self.unmanaged.iterator();
}
/// Get an optional pointer to the value associated with key, if present.
pub fn getHash(key: K) u64 {
return hashFn(key);
}
/// If key exists this function cannot fail.
/// If there is an existing item with `key`, then the result
/// `Entry` pointer points to it, and found_existing is true.
/// Otherwise, puts a new item with undefined value, and
/// the `Entry` pointer points to it. Caller should then initialize
/// the value (but not the key).
pub fn getOrPut(self: *Self, key: K) !GetOrPutResult {
return self.unmanaged.getOrPut(self.allocator, key);
}
/// If key exists this function cannot fail.
/// If there is an existing item with `key`, then the result
/// `Entry` pointer points to it, and found_existing is true.
/// Otherwise, puts a new item with undefined value, and
/// the `Entry` pointer points to it. Caller should then initialize
/// the value (but not the key).
pub fn getOrPutWithHash(self: *Self, key: K, hash: u64) !GetOrPutResult {
return self.unmanaged.getOrPutWithHash(self.allocator, key, hash);
}
/// If there is an existing item with `key`, then the result
/// `Entry` pointer points to it, and found_existing is true.
/// Otherwise, puts a new item with undefined value, and
/// the `Entry` pointer points to it. Caller should then initialize
/// the value (but not the key).
/// If a new entry needs to be stored, this function asserts there
/// is enough capacity to store it.
pub fn getOrPutAssumeCapacity(self: *Self, key: K) GetOrPutResult {
return self.unmanaged.getOrPutAssumeCapacity(key);
}
pub fn getOrPutValue(self: *Self, key: K, value: V) !*Entry {
return self.unmanaged.getOrPutValue(self.allocator, key, value);
}
/// Increases capacity, guaranteeing that insertions up until the
/// `expected_count` will not cause an allocation, and therefore cannot fail.
pub fn ensureCapacity(self: *Self, expected_count: Size) !void {
return self.unmanaged.ensureCapacity(self.allocator, expected_count);
}
/// Returns the number of total elements which may be present before it is
/// no longer guaranteed that no allocations will be performed.
pub fn capacity(self: *Self) Size {
return self.unmanaged.capacity();
}
/// Clobbers any existing data. To detect if a put would clobber
/// existing data, see `getOrPut`.
pub fn put(self: *Self, key: K, value: V) !void {
return self.unmanaged.put(self.allocator, key, value);
}
/// Clobbers any existing data. To detect if a put would clobber
/// existing data, see `getOrPut`.
pub fn putWithHash(self: *Self, key: K, hash: u64, value: V) !void {
return self.unmanaged.putWithHash(self.allocator, key, hash, value);
}
/// Inserts a key-value pair into the hash map, asserting that no previous
/// entry with the same key is already present
pub fn putNoClobber(self: *Self, key: K, value: V) !void {
return self.unmanaged.putNoClobber(self.allocator, key, value);
}
/// Asserts there is enough capacity to store the new key-value pair.
/// Clobbers any existing data. To detect if a put would clobber
/// existing data, see `getOrPutAssumeCapacity`.
pub fn putAssumeCapacity(self: *Self, key: K, value: V) void {
return self.unmanaged.putAssumeCapacity(key, value);
}
/// Asserts there is enough capacity to store the new key-value pair.
/// Asserts that it does not clobber any existing data.
/// To detect if a put would clobber existing data, see `getOrPutAssumeCapacity`.
pub fn putAssumeCapacityNoClobber(self: *Self, key: K, value: V) void {
return self.unmanaged.putAssumeCapacityNoClobber(key, value);
}
/// Asserts there is enough capacity to store the new key-value pair.
/// Asserts that it does not clobber any existing data.
/// To detect if a put would clobber existing data, see `getOrPutAssumeCapacity`.
pub fn putAssumeCapacityNoClobberWithHash(self: *Self, key: K, hash: u64, value: V) void {
return self.unmanaged.putAssumeCapacityNoClobberWithHash(key, hash, value);
}
/// Inserts a new `Entry` into the hash map, returning the previous one, if any.
pub fn fetchPut(self: *Self, key: K, value: V) !?Entry {
return self.unmanaged.fetchPut(self.allocator, key, value);
}
/// Inserts a new `Entry` into the hash map, returning the previous one, if any.
/// If insertion happuns, asserts there is enough capacity without allocating.
pub fn fetchPutAssumeCapacity(self: *Self, key: K, value: V) ?Entry {
return self.unmanaged.fetchPutAssumeCapacity(key, value);
}
pub fn get(self: Self, key: K) ?V {
return self.unmanaged.get(key);
}
pub fn getWithHash(self: Self, key: K, hash: u64) ?V {
return self.unmanaged.getWithHash(key, hash);
}
pub fn getEntry(self: Self, key: K) ?*Entry {
return self.unmanaged.getEntry(key);
}
pub fn getEntryWithHash(self: Self, key: K, hash: u64) ?*Entry {
return self.unmanaged.getEntryWithHash(key, hash);
}
pub fn contains(self: Self, key: K) bool {
return self.unmanaged.contains(key);
}
/// If there is an `Entry` with a matching key, it is deleted from
/// the hash map, and then returned from this function.
pub fn remove(self: *Self, key: K) ?Entry {
return self.unmanaged.remove(key);
}
/// Asserts there is an `Entry` with matching key, deletes it from the hash map,
/// and discards it.
pub fn removeAssertDiscard(self: *Self, key: K) void {
return self.unmanaged.removeAssertDiscard(key);
}
pub fn clone(self: Self) !Self {
var other = try self.unmanaged.clone(self.allocator);
return other.promote(self.allocator);
}
};
}
/// A HashMap based on open addressing and linear probing.
/// A lookup or modification typically occurs only 2 cache misses.
/// No order is guaranteed and any modification invalidates live iterators.
/// It achieves good performance with quite high load factors (by default,
/// grow is triggered at 80% full) and only one byte of overhead per element.
/// The struct itself is only 16 bytes for a small footprint. This comes at
/// the price of handling size with u32, which should be reasonnable enough
/// for almost all uses.
/// Deletions are achieved with tombstones.
pub fn HashMapUnmanaged(
comptime K: type,
comptime V: type,
hashFn: fn (key: K) u64,
eqlFn: fn (a: K, b: K) bool,
comptime max_load_percentage: u64,
) type {
comptime assert(max_load_percentage > 0 and max_load_percentage < 100);
return struct {
const Self = @This();
// This is actually a midway pointer to the single buffer containing
// a `Header` field, the `Metadata`s and `Entry`s.
// At `-@sizeOf(Header)` is the Header field.
// At `sizeOf(Metadata) * capacity + offset`, which is pointed to by
// self.header().entries, is the array of entries.
// This means that the hashmap only holds one live allocation, to
// reduce memory fragmentation and struct size.
/// Pointer to the metadata.
metadata: ?[*]Metadata = null,
/// Current number of elements in the hashmap.
size: Size = 0,
// Having a countdown to grow reduces the number of instructions to
// execute when determining if the hashmap has enough capacity already.
/// Number of available slots before a grow is needed to satisfy the
/// `max_load_percentage`.
available: Size = 0,
// This is purely empirical and not a /very smart magic constant™/.
/// Capacity of the first grow when bootstrapping the hashmap.
const minimal_capacity = 8;
// This hashmap is specially designed for sizes that fit in a u32.
const Size = u32;
// u64 hashes guarantee us that the fingerprint bits will never be used
// to compute the index of a slot, maximizing the use of entropy.
const Hash = u64;
pub const Entry = struct {
key: K,
value: V,
};
const Header = packed struct {
entries: [*]Entry,
capacity: Size,
};
/// Metadata for a slot. It can be in three states: empty, used or
/// tombstone. Tombstones indicate that an entry was previously used,
/// they are a simple way to handle removal.
/// To this state, we add 7 bits from the slot's key hash. These are
/// used as a fast way to disambiguate between entries without
/// having to use the equality function. If two fingerprints are
/// different, we know that we don't have to compare the keys at all.
/// The 7 bits are the highest ones from a 64 bit hash. This way, not
/// only we use the `log2(capacity)` lowest bits from the hash to determine
/// a slot index, but we use 7 more bits to quickly resolve collisions
/// when multiple elements with different hashes end up wanting to be in the same slot.
/// Not using the equality function means we don't have to read into
/// the entries array, likely avoiding a cache miss and a potentially
/// costly function call.
const Metadata = packed struct {
const FingerPrint = u7;
const free: FingerPrint = 0;
const tombstone: FingerPrint = 1;
fingerprint: FingerPrint = free,
used: u1 = 0,
pub fn isUsed(self: Metadata) bool {
return self.used == 1;
}
pub fn isTombstone(self: Metadata) bool {
return !self.isUsed() and self.fingerprint == tombstone;
}
pub fn takeFingerprint(hash: Hash) FingerPrint {
const hash_bits = @typeInfo(Hash).Int.bits;
const fp_bits = @typeInfo(FingerPrint).Int.bits;
return @truncate(FingerPrint, hash >> (hash_bits - fp_bits));
}
pub fn fill(self: *Metadata, fp: FingerPrint) void {
self.used = 1;
self.fingerprint = fp;
}
pub fn remove(self: *Metadata) void {
self.used = 0;
self.fingerprint = tombstone;
}
};
comptime {
assert(@sizeOf(Metadata) == 1);
assert(@alignOf(Metadata) == 1);
}
const Iterator = struct {
hm: *const Self,
index: Size = 0,
pub fn next(it: *Iterator) ?*Entry {
if (@import("builtin").mode != .ReleaseFast) assert(it.index <= it.hm.capacity());
if (it.hm.size == 0) return null;
const cap = it.hm.capacity();
const end = it.hm.metadata.? + cap;
var metadata = it.hm.metadata.? + it.index;
while (metadata != end) : ({
metadata += 1;
it.index += 1;
}) {
if (metadata[0].isUsed()) {
const entry = &it.hm.entries()[it.index];
it.index += 1;
return entry;
}
}
return null;
}
};
pub const GetOrPutResult = struct {
entry: *Entry,
found_existing: bool,
};
pub const Managed = HashMap(K, V, hashFn, eqlFn, max_load_percentage);
pub fn promote(self: Self, allocator: Allocator) Managed {
return .{
.unmanaged = self,
.allocator = allocator,
};
}
fn isUnderMaxLoadPercentage(size: Size, cap: Size) bool {
return size * 100 < max_load_percentage * cap;
}
pub fn deinit(self: *Self, allocator: Allocator) void {
self.deallocate(allocator);
self.* = undefined;
}
fn deallocate(self: *Self, allocator: Allocator) void {
if (self.metadata == null) return;
const cap = self.capacity();
const meta_size = @sizeOf(Header) + cap * @sizeOf(Metadata);
const alignment = @alignOf(Entry) - 1;
const entries_size = @as(usize, cap) * @sizeOf(Entry) + alignment;
const total_size = meta_size + entries_size;
var slice: []u8 = undefined;
slice.ptr = @intToPtr([*]u8, @ptrToInt(self.header()));
slice.len = total_size;
allocator.free(slice);
self.metadata = null;
self.available = 0;
}
fn capacityForSize(size: Size) Size {
var new_cap = @truncate(u32, (@as(u64, size) * 100) / max_load_percentage + 1);
new_cap = math.ceilPowerOfTwo(u32, new_cap) catch unreachable;
return new_cap;
}
pub fn ensureCapacity(self: *Self, allocator: Allocator, new_size: Size) !void {
if (new_size > self.size)
try self.growIfNeeded(allocator, new_size - self.size);
}
pub fn clearRetainingCapacity(self: *Self) void {
if (self.metadata) |_| {
self.initMetadatas();
self.size = 0;
self.available = @truncate(u32, (self.capacity() * max_load_percentage) / 100);
}
}
pub fn clearAndFree(self: *Self, allocator: Allocator) void {
self.deallocate(allocator);
self.size = 0;
self.available = 0;
}
pub fn count(self: *const Self) Size {
return self.size;
}
fn header(self: *const Self) *Header {
return @ptrCast(*Header, @ptrCast([*]Header, self.metadata.?) - 1);
}
fn entries(self: *const Self) [*]Entry {
return self.header().entries;
}
pub fn capacity(self: *const Self) Size {
if (self.metadata == null) return 0;
return self.header().capacity;
}
pub fn iterator(self: *const Self) Iterator {
return .{ .hm = self };
}
/// Insert an entry in the map. Assumes it is not already present.
pub fn putNoClobber(self: *Self, allocator: Allocator, key: K, value: V) !void {
if (@import("builtin").mode != .ReleaseFast) assert(!self.contains(key));
try self.growIfNeeded(allocator, 1);
self.putAssumeCapacityNoClobber(key, value);
}
/// Asserts there is enough capacity to store the new key-value pair.
/// Clobbers any existing data. To detect if a put would clobber
/// existing data, see `getOrPutAssumeCapacity`.
pub fn putAssumeCapacity(self: *Self, key: K, value: V) void {
const gop = self.getOrPutAssumeCapacity(key);
gop.entry.value = value;
}
/// Insert an entry in the map. Assumes it is not already present,
/// and that no allocation is needed.
pub fn putAssumeCapacityNoClobber(self: *Self, key: K, value: V) void {
if (@import("builtin").mode != .ReleaseFast) assert(!self.contains(key));
const hash = hashFn(key);
putAssumeCapacityNoClobberWithHash(self, key, hash, value);
}
/// Insert an entry in the map. Assumes it is not already present,
/// and that no allocation is needed.
pub fn putAssumeCapacityNoClobberWithHash(self: *Self, key: K, hash: u64, value: V) void {
const mask = self.capacity() - 1;
var idx = @truncate(usize, hash & mask);
var metadata = self.metadata.? + idx;
while (metadata[0].isUsed()) {
idx = (idx + 1) & mask;
metadata = self.metadata.? + idx;
}
if (!metadata[0].isTombstone()) {
if (@import("builtin").mode != .ReleaseFast) assert(self.available > 0);
self.available -= 1;
}
const fingerprint = Metadata.takeFingerprint(hash);
metadata[0].fill(fingerprint);
self.entries()[idx] = Entry{ .key = key, .value = value };
self.size += 1;
}
/// Inserts a new `Entry` into the hash map, returning the previous one, if any.
pub fn fetchPut(self: *Self, allocator: Allocator, key: K, value: V) !?Entry {
const gop = try self.getOrPut(allocator, key);
var result: ?Entry = null;
if (gop.found_existing) {
result = gop.entry.*;
}
gop.entry.value = value;
return result;
}
/// Inserts a new `Entry` into the hash map, returning the previous one, if any.
/// If insertion happens, asserts there is enough capacity without allocating.
pub fn fetchPutAssumeCapacity(self: *Self, key: K, value: V) ?Entry {
const gop = self.getOrPutAssumeCapacity(key);
var result: ?Entry = null;
if (gop.found_existing) {
result = gop.entry.*;
}
gop.entry.value = value;
return result;
}
pub fn getEntryWithHash(self: Self, key: K, hash: u64) ?*Entry {
if (self.size == 0) {
return null;
}
return @call(.{ .modifier = .always_inline }, _getEntryWithHash, .{ self, key, hash });
}
fn _getEntryWithHash(self: Self, key: K, hash: u64) ?*Entry {
const mask = self.capacity() - 1;
const fingerprint = Metadata.takeFingerprint(hash);
var idx = @truncate(usize, hash & mask);
var metadata = self.metadata.? + idx;
while (metadata[0].isUsed() or metadata[0].isTombstone()) {
if (metadata[0].isUsed() and metadata[0].fingerprint == fingerprint) {
const entry = &self.entries()[idx];
if (eqlFn(entry.key, key)) {
return entry;
}
}
idx = (idx + 1) & mask;
metadata = self.metadata.? + idx;
}
return null;
}
pub fn getEntry(self: Self, key: K) ?*Entry {
if (self.size == 0) {
return null;
}
return @call(.{ .modifier = .always_inline }, _getEntryWithHash, .{ self, key, hashFn(key) });
}
/// Insert an entry if the associated key is not already present, otherwise update preexisting value.
pub fn put(self: *Self, allocator: Allocator, key: K, value: V) !void {
const result = try self.getOrPut(allocator, key);
result.entry.value = value;
}
/// Insert an entry if the associated key is not already present, otherwise update preexisting value.
pub fn putWithHash(self: *Self, allocator: Allocator, key: K, hash: u64, value: V) !void {
const result = try self.getOrPutWithHash(allocator, key, hash);
result.entry.value = value;
}
/// Get an optional pointer to the value associated with key, if present.
pub fn getHash(key: K) u64 {
return hashFn(key);
}
/// Get an optional pointer to the value associated with key, if present.
pub fn getWithHash(self: Self, key: K, hash: u64) ?V {
if (self.size == 0) {
return null;
}
const mask = self.capacity() - 1;
const fingerprint = Metadata.takeFingerprint(hash);
var idx = @truncate(usize, hash & mask);
var metadata = self.metadata.? + idx;
while (metadata[0].isUsed() or metadata[0].isTombstone()) {
if (metadata[0].isUsed() and metadata[0].fingerprint == fingerprint) {
const entry = &self.entries()[idx];
if (eqlFn(entry.key, key)) {
return entry.value;
}
}
idx = (idx + 1) & mask;
metadata = self.metadata.? + idx;
}
return null;
}
/// Get an optional pointer to the value associated with key, if present.
pub fn get(self: Self, key: K) ?V {
if (self.size == 0) {
return null;
}
const hash = hashFn(key);
const mask = self.capacity() - 1;
const fingerprint = Metadata.takeFingerprint(hash);
var idx = @truncate(usize, hash & mask);
var metadata = self.metadata.? + idx;
while (metadata[0].isUsed() or metadata[0].isTombstone()) {
if (metadata[0].isUsed() and metadata[0].fingerprint == fingerprint) {
const entry = &self.entries()[idx];
if (eqlFn(entry.key, key)) {
return entry.value;
}
}
idx = (idx + 1) & mask;
metadata = self.metadata.? + idx;
}
return null;
}
pub fn getOrPut(self: *Self, allocator: Allocator, key: K) !GetOrPutResult {
try self.growIfNeeded(allocator, 1);
return self.getOrPutAssumeCapacity(key);
}
pub fn getOrPutWithHash(self: *Self, allocator: Allocator, key: K, hash: u64) !GetOrPutResult {
try self.growIfNeeded(allocator, 1);
return self.getOrPutAssumeCapacityWithHash(key, hash);
}
pub fn getOrPutAssumeCapacity(self: *Self, key: K) GetOrPutResult {
return @call(.{ .modifier = .always_inline }, Self.getOrPutAssumeCapacityWithHash, .{ self, key, hashFn(key) });
}
pub fn getOrPutAssumeCapacityWithHash(self: *Self, key: K, hash: u64) GetOrPutResult {
const mask = self.capacity() - 1;
const fingerprint = Metadata.takeFingerprint(hash);
var idx = @truncate(usize, hash & mask);
var first_tombstone_idx: usize = self.capacity(); // invalid index
var metadata = self.metadata.? + idx;
while (metadata[0].isUsed() or metadata[0].isTombstone()) {
if (metadata[0].isUsed() and metadata[0].fingerprint == fingerprint) {
const entry = &self.entries()[idx];
if (eqlFn(entry.key, key)) {
return GetOrPutResult{ .entry = entry, .found_existing = true };
}
} else if (first_tombstone_idx == self.capacity() and metadata[0].isTombstone()) {
first_tombstone_idx = idx;
}
idx = (idx + 1) & mask;
metadata = self.metadata.? + idx;
}
if (first_tombstone_idx < self.capacity()) {
// Cheap try to lower probing lengths after deletions. Recycle a tombstone.
idx = first_tombstone_idx;
metadata = self.metadata.? + idx;
} else {
// We're using a slot previously free.
self.available -= 1;
}
metadata[0].fill(fingerprint);
const entry = &self.entries()[idx];
entry.* = .{ .key = key, .value = undefined };
self.size += 1;
return GetOrPutResult{ .entry = entry, .found_existing = false };
}
pub fn getOrPutValue(self: *Self, allocator: Allocator, key: K, value: V) !*Entry {
const res = try self.getOrPut(allocator, key);
if (!res.found_existing) res.entry.value = value;
return res.entry;
}
/// Return true if there is a value associated with key in the map.
pub fn contains(self: *const Self, key: K) bool {
return self.get(key) != null;
}
/// If there is an `Entry` with a matching key, it is deleted from
/// the hash map, and then returned from this function.
pub fn remove(self: *Self, key: K) ?Entry {
if (self.size == 0) return null;
const hash = hashFn(key);
const mask = self.capacity() - 1;
const fingerprint = Metadata.takeFingerprint(hash);
var idx = @truncate(usize, hash & mask);
var metadata = self.metadata.? + idx;
while (metadata[0].isUsed() or metadata[0].isTombstone()) {
if (metadata[0].isUsed() and metadata[0].fingerprint == fingerprint) {
const entry = &self.entries()[idx];
if (eqlFn(entry.key, key)) {
const removed_entry = entry.*;
metadata[0].remove();
entry.* = undefined;
self.size -= 1;
return removed_entry;
}
}
idx = (idx + 1) & mask;
metadata = self.metadata.? + idx;
}
return null;
}
/// Asserts there is an `Entry` with matching key, deletes it from the hash map,
/// and discards it.
pub fn removeAssertDiscard(self: *Self, key: K) void {
if (@import("builtin").mode != .ReleaseFast) assert(self.contains(key));
const hash = hashFn(key);
const mask = self.capacity() - 1;
const fingerprint = Metadata.takeFingerprint(hash);
var idx = @truncate(usize, hash & mask);
var metadata = self.metadata.? + idx;
while (metadata[0].isUsed() or metadata[0].isTombstone()) {
if (metadata[0].isUsed() and metadata[0].fingerprint == fingerprint) {
const entry = &self.entries()[idx];
if (eqlFn(entry.key, key)) {
metadata[0].remove();
entry.* = undefined;
self.size -= 1;
return;
}
}
idx = (idx + 1) & mask;
metadata = self.metadata.? + idx;
}
unreachable;
}
fn initMetadatas(self: *Self) void {
@memset(@ptrCast([*]u8, self.metadata.?), 0, @sizeOf(Metadata) * self.capacity());
}
// This counts the number of occupied slots, used + tombstones, which is
// what has to stay under the max_load_percentage of capacity.
fn load(self: *const Self) Size {
const max_load = (self.capacity() * max_load_percentage) / 100;
if (@import("builtin").mode != .ReleaseFast) assert(max_load >= self.available);
return @truncate(Size, max_load - self.available);
}
fn growIfNeeded(self: *Self, allocator: Allocator, new_count: Size) !void {
if (new_count > self.available) {
try self.grow(allocator, capacityForSize(self.load() + new_count));
}
}
pub fn clone(self: Self, allocator: Allocator) !Self {
var other = Self{};
if (self.size == 0)
return other;
const new_cap = capacityForSize(self.size);
try other.allocate(allocator, new_cap);
other.initMetadatas();
other.available = @truncate(u32, (new_cap * max_load_percentage) / 100);
var i: Size = 0;
var metadata = self.metadata.?;
var entr = self.entries();
while (i < self.capacity()) : (i += 1) {
if (metadata[i].isUsed()) {
const entry = &entr[i];
other.putAssumeCapacityNoClobber(entry.key, entry.value);
if (other.size == self.size)
break;
}
}
return other;
}
fn grow(self: *Self, allocator: Allocator, new_capacity: Size) !void {
const new_cap = std.math.max(new_capacity, minimal_capacity);
if (@import("builtin").mode != .ReleaseFast) assert(new_cap > self.capacity());
if (@import("builtin").mode != .ReleaseFast) assert(std.math.isPowerOfTwo(new_cap));
var map = Self{};
defer map.deinit(allocator);
try map.allocate(allocator, new_cap);
map.initMetadatas();
map.available = @truncate(u32, (new_cap * max_load_percentage) / 100);
if (self.size != 0) {
const old_capacity = self.capacity();
var i: Size = 0;
var metadata = self.metadata.?;
var entr = self.entries();
while (i < old_capacity) : (i += 1) {
if (metadata[i].isUsed()) {
const entry = &entr[i];
map.putAssumeCapacityNoClobber(entry.key, entry.value);
if (map.size == self.size)
break;
}
}
}
self.size = 0;
std.mem.swap(Self, self, &map);
}
fn allocate(self: *Self, allocator: Allocator, new_capacity: Size) !void {
const meta_size = @sizeOf(Header) + new_capacity * @sizeOf(Metadata);
const alignment = @alignOf(Entry) - 1;
const entries_size = @as(usize, new_capacity) * @sizeOf(Entry) + alignment;
const total_size = meta_size + entries_size;
const slice = try allocator.alignedAlloc(u8, @alignOf(Header), total_size);
const ptr = @ptrToInt(slice.ptr);
const metadata = ptr + @sizeOf(Header);
var entry_ptr = ptr + meta_size;
entry_ptr = (entry_ptr + alignment) & ~@as(usize, alignment);
if (@import("builtin").mode != .ReleaseFast) assert(entry_ptr + @as(usize, new_capacity) * @sizeOf(Entry) <= ptr + total_size);
const hdr = @intToPtr(*Header, ptr);
hdr.entries = @intToPtr([*]Entry, entry_ptr);
hdr.capacity = new_capacity;
self.metadata = @intToPtr([*]Metadata, metadata);
}
};
}
const testing = std.testing;
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
test "std.hash_map basic usage" {
var map = AutoHashMap(u32, u32).init(std.testing.allocator);
defer map.deinit();
const count = 5;
var i: u32 = 0;
var total: u32 = 0;
while (i < count) : (i += 1) {
try map.put(i, i);
total += i;
}
var sum: u32 = 0;
var it = map.iterator();
while (it.next()) |kv| {
sum += kv.key;
}
try expect(sum == total);
i = 0;
sum = 0;
while (i < count) : (i += 1) {
try expectEqual(map.get(i).?, i);
sum += map.get(i).?;
}
try expectEqual(total, sum);
}
test "std.hash_map ensureCapacity" {
var map = AutoHashMap(i32, i32).init(std.testing.allocator);
defer map.deinit();
try map.ensureCapacity(20);
const initial_capacity = map.capacity();
try testing.expect(initial_capacity >= 20);
var i: i32 = 0;
while (i < 20) : (i += 1) {
try testing.expect(map.fetchPutAssumeCapacity(i, i + 10) == null);
}
// shouldn't resize from putAssumeCapacity
try testing.expect(initial_capacity == map.capacity());
}
test "std.hash_map ensureCapacity with tombstones" {
var map = AutoHashMap(i32, i32).init(std.testing.allocator);
defer map.deinit();
var i: i32 = 0;
while (i < 100) : (i += 1) {
try map.ensureCapacity(@intCast(u32, map.count() + 1));
map.putAssumeCapacity(i, i);
// Remove to create tombstones that still count as load in the hashmap.
_ = map.remove(i);
}
}
test "std.hash_map clearRetainingCapacity" {
var map = AutoHashMap(u32, u32).init(std.testing.allocator);
defer map.deinit();
map.clearRetainingCapacity();
try map.put(1, 1);
try expectEqual(map.get(1).?, 1);
try expectEqual(map.count(), 1);
map.clearRetainingCapacity();
map.putAssumeCapacity(1, 1);
try expectEqual(map.get(1).?, 1);
try expectEqual(map.count(), 1);
const cap = map.capacity();
try expect(cap > 0);
map.clearRetainingCapacity();
map.clearRetainingCapacity();