pub fn HashMap(
comptime K: type,
comptime V: type,
comptime Context: type,
comptime max_load_percentage: u64,
) type The type of the unmanaged hash map underlying this wrapper
An entry, containing pointers to a key and value stored in the map
A copy of a key and value which are no longer in the map
The integer type that is the result of hashing
The iterator type returned by iterator()
The integer type used to store the size of the map
The type returned from getOrPut and variants
pub fn init(allocator: Allocator) SelfCreate a managed hash map with an empty context. If the context is not zero-sized, you must use initContext(allocator, ctx) instead.
pub fn initContext(allocator: Allocator, ctx: Context) SelfCreate a managed hash map with a context
pub fn lockPointers(self: *Self) voidPuts the hash map into a state where any method call that would cause an existing key or value pointer to become invalidated will instead trigger an assertion.
An additional call to lockPointers in such state also triggers an assertion.
unlockPointers returns the hash map to the previous state.
pub fn unlockPointers(self: *Self) voidUndoes a call to lockPointers.
pub fn deinit(self: *Self) voidRelease the backing array and invalidate this map. This does not deinit keys, values, or the context! If your keys or values need to be released, ensure that that is done before calling this function.
pub fn clearRetainingCapacity(self: *Self) voidEmpty the map, but keep the backing allocation for future use. This does not free keys or values! Be sure to release them if they need deinitialization before calling this function.
pub fn clearAndFree(self: *Self) voidEmpty the map and release the backing allocation. This does not free keys or values! Be sure to release them if they need deinitialization before calling this function.
pub fn count(self: Self) SizeReturn the number of items in the map.
pub fn iterator(self: *const Self) IteratorCreate an iterator over the entries in the map. The iterator is invalidated if the map is modified.
pub fn keyIterator(self: Self) KeyIteratorCreate an iterator over the keys in the map. The iterator is invalidated if the map is modified.
pub fn valueIterator(self: Self) ValueIteratorCreate an iterator over the values in the map. The iterator is invalidated if the map is modified.
pub fn getOrPut(self: *Self, key: K) Allocator.Error!GetOrPutResultIf key exists this function cannot fail. If there is an existing item with key, then the result's Entry pointers point to it, and found_existing is true. Otherwise, puts a new item with undefined value, and the Entry pointers point to it. Caller should then initialize the value (but not the key).
pub fn getOrPutAdapted(self: *Self, key: anytype, ctx: anytype) Allocator.Error!GetOrPutResultIf key exists this function cannot fail. If there is an existing item with key, then the result's Entry pointers point to it, and found_existing is true. Otherwise, puts a new item with undefined key and value, and the Entry pointers point to it. Caller must then initialize the key and value.
pub fn getOrPutAssumeCapacity(self: *Self, key: K) GetOrPutResultIf there is an existing item with key, then the result's Entry pointers point to it, and found_existing is true. Otherwise, puts a new item with undefined value, and the Entry pointers point 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 getOrPutAssumeCapacityAdapted(self: *Self, key: anytype, ctx: anytype) GetOrPutResultIf there is an existing item with key, then the result's Entry pointers point to it, and found_existing is true. Otherwise, puts a new item with undefined value, and the Entry pointers point to it. Caller must then initialize the key and value. If a new entry needs to be stored, this function asserts there is enough capacity to store it.
pub fn getOrPutValue(self: *Self, key: K, value: V) Allocator.Error!Entrypub fn ensureTotalCapacity(self: *Self, expected_count: Size) Allocator.Error!voidIncreases capacity, guaranteeing that insertions up until the expected_count will not cause an allocation, and therefore cannot fail.
pub fn ensureUnusedCapacity(self: *Self, additional_count: Size) Allocator.Error!voidIncreases capacity, guaranteeing that insertions up until additional_count more items will not cause an allocation, and therefore cannot fail.
pub fn capacity(self: Self) SizeReturns the number of total elements which may be present before it is no longer guaranteed that no allocations will be performed.
pub fn put(self: *Self, key: K, value: V) Allocator.Error!voidClobbers any existing data. To detect if a put would clobber existing data, see getOrPut.
pub fn putNoClobber(self: *Self, key: K, value: V) Allocator.Error!voidInserts a key-value pair into the hash map, asserting that no previous entry with the same key is already present
pub fn putAssumeCapacity(self: *Self, key: K, value: V) voidAsserts 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 putAssumeCapacityNoClobber(self: *Self, key: K, value: V) voidAsserts 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 fetchPut(self: *Self, key: K, value: V) Allocator.Error!?KVInserts a new Entry into the hash map, returning the previous one, if any.
pub fn fetchPutAssumeCapacity(self: *Self, key: K, value: V) ?KVInserts 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 fetchRemove(self: *Self, key: K) ?KVRemoves a value from the map and returns the removed kv pair.
pub fn fetchRemoveAdapted(self: *Self, key: anytype, ctx: anytype) ?KVpub fn get(self: Self, key: K) ?VFinds the value associated with a key in the map
pub fn getAdapted(self: Self, key: anytype, ctx: anytype) ?Vpub fn getPtr(self: Self, key: K) ?*Vpub fn getPtrAdapted(self: Self, key: anytype, ctx: anytype) ?*Vpub fn getKey(self: Self, key: K) ?KFinds the actual key associated with an adapted key in the map
pub fn getKeyAdapted(self: Self, key: anytype, ctx: anytype) ?Kpub fn getKeyPtr(self: Self, key: K) ?*Kpub fn getKeyPtrAdapted(self: Self, key: anytype, ctx: anytype) ?*Kpub fn getEntry(self: Self, key: K) ?EntryFinds the key and value associated with a key in the map
pub fn getEntryAdapted(self: Self, key: anytype, ctx: anytype) ?Entrypub fn contains(self: Self, key: K) boolCheck if the map contains a key
pub fn containsAdapted(self: Self, key: anytype, ctx: anytype) boolpub fn remove(self: *Self, key: K) boolIf there is an Entry with a matching key, it is deleted from the hash map, and this function returns true. Otherwise this function returns false.
TODO: answer the question in these doc comments, does this increase the unused capacity by one?
pub fn removeAdapted(self: *Self, key: anytype, ctx: anytype) boolTODO: answer the question in these doc comments, does this increase the unused capacity by one?
pub fn removeByPtr(self: *Self, key_ptr: *K) voidDelete the entry with key pointed to by key_ptr from the hash map. key_ptr is assumed to be a valid pointer to a key that is present in the hash map.
TODO: answer the question in these doc comments, does this increase the unused capacity by one?
pub fn clone(self: Self) Allocator.Error!SelfCreates a copy of this map, using the same allocator
pub fn cloneWithAllocator(self: Self, new_allocator: Allocator) Allocator.Error!SelfCreates a copy of this map, using a specified allocator
pub fn cloneWithContext(self: Self, new_ctx: anytype) Allocator.Error!HashMap(K, V, @TypeOf(new_ctx), max_load_percentage)Creates a copy of this map, using a specified context
pub fn cloneWithAllocatorAndContext(self: Self, new_allocator: Allocator, new_ctx: anytype) Allocator.Error!HashMap(K, V, @TypeOf(new_ctx), max_load_percentage)Creates a copy of this map, using a specified allocator and context.
pub fn move(self: *Self) SelfSet the map to an empty state, making deinitialization a no-op, and returning a copy of the original.
pub fn rehash(self: *Self) voidRehash the map, in-place.
Over time, due to the current tombstone-based implementation, a HashMap could become fragmented due to the buildup of tombstone entries that causes a performance degradation due to excessive probing. The kind of pattern that might cause this is a long-lived HashMap with repeated inserts and deletes.
After this function is called, there will be no tombstones in the HashMap, each of the entries is rehashed and any existing key/value pointers into the HashMap are invalidated.
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
492pub fn HashMap(
comptime K: type,
comptime V: type,
comptime Context: type,
comptime max_load_percentage: u64,
) type {
return struct {
unmanaged: Unmanaged,
allocator: Allocator,
ctx: Context,
/// The type of the unmanaged hash map underlying this wrapper
pub const Unmanaged = HashMapUnmanaged(K, V, Context, max_load_percentage);
/// An entry, containing pointers to a key and value stored in the map
pub const Entry = Unmanaged.Entry;
/// A copy of a key and value which are no longer in the map
pub const KV = Unmanaged.KV;
/// The integer type that is the result of hashing
pub const Hash = Unmanaged.Hash;
/// The iterator type returned by iterator()
pub const Iterator = Unmanaged.Iterator;
pub const KeyIterator = Unmanaged.KeyIterator;
pub const ValueIterator = Unmanaged.ValueIterator;
/// The integer type used to store the size of the map
pub const Size = Unmanaged.Size;
/// The type returned from getOrPut and variants
pub const GetOrPutResult = Unmanaged.GetOrPutResult;
const Self = @This();
/// Create a managed hash map with an empty context.
/// If the context is not zero-sized, you must use
/// initContext(allocator, ctx) instead.
pub fn init(allocator: Allocator) Self {
if (@sizeOf(Context) != 0) {
@compileError("Context must be specified! Call initContext(allocator, ctx) instead.");
}
return .{
.unmanaged = .empty,
.allocator = allocator,
.ctx = undefined, // ctx is zero-sized so this is safe.
};
}
/// Create a managed hash map with a context
pub fn initContext(allocator: Allocator, ctx: Context) Self {
return .{
.unmanaged = .empty,
.allocator = allocator,
.ctx = ctx,
};
}
/// Puts the hash map into a state where any method call that would
/// cause an existing key or value pointer to become invalidated will
/// instead trigger an assertion.
///
/// An additional call to `lockPointers` in such state also triggers an
/// assertion.
///
/// `unlockPointers` returns the hash map to the previous state.
pub fn lockPointers(self: *Self) void {
self.unmanaged.lockPointers();
}
/// Undoes a call to `lockPointers`.
pub fn unlockPointers(self: *Self) void {
self.unmanaged.unlockPointers();
}
/// Release the backing array and invalidate this map.
/// This does *not* deinit keys, values, or the context!
/// If your keys or values need to be released, ensure
/// that that is done before calling this function.
pub fn deinit(self: *Self) void {
self.unmanaged.deinit(self.allocator);
self.* = undefined;
}
/// Empty the map, but keep the backing allocation for future use.
/// This does *not* free keys or values! Be sure to
/// release them if they need deinitialization before
/// calling this function.
pub fn clearRetainingCapacity(self: *Self) void {
return self.unmanaged.clearRetainingCapacity();
}
/// Empty the map and release the backing allocation.
/// This does *not* free keys or values! Be sure to
/// release them if they need deinitialization before
/// calling this function.
pub fn clearAndFree(self: *Self) void {
return self.unmanaged.clearAndFree(self.allocator);
}
/// Return the number of items in the map.
pub fn count(self: Self) Size {
return self.unmanaged.count();
}
/// Create an iterator over the entries in the map.
/// The iterator is invalidated if the map is modified.
pub fn iterator(self: *const Self) Iterator {
return self.unmanaged.iterator();
}
/// Create an iterator over the keys in the map.
/// The iterator is invalidated if the map is modified.
pub fn keyIterator(self: Self) KeyIterator {
return self.unmanaged.keyIterator();
}
/// Create an iterator over the values in the map.
/// The iterator is invalidated if the map is modified.
pub fn valueIterator(self: Self) ValueIterator {
return self.unmanaged.valueIterator();
}
/// If key exists this function cannot fail.
/// If there is an existing item with `key`, then the result's
/// `Entry` pointers point to it, and found_existing is true.
/// Otherwise, puts a new item with undefined value, and
/// the `Entry` pointers point to it. Caller should then initialize
/// the value (but not the key).
pub fn getOrPut(self: *Self, key: K) Allocator.Error!GetOrPutResult {
return self.unmanaged.getOrPutContext(self.allocator, key, self.ctx);
}
/// If key exists this function cannot fail.
/// If there is an existing item with `key`, then the result's
/// `Entry` pointers point to it, and found_existing is true.
/// Otherwise, puts a new item with undefined key and value, and
/// the `Entry` pointers point to it. Caller must then initialize
/// the key and value.
pub fn getOrPutAdapted(self: *Self, key: anytype, ctx: anytype) Allocator.Error!GetOrPutResult {
return self.unmanaged.getOrPutContextAdapted(self.allocator, key, ctx, self.ctx);
}
/// If there is an existing item with `key`, then the result's
/// `Entry` pointers point to it, and found_existing is true.
/// Otherwise, puts a new item with undefined value, and
/// the `Entry` pointers point 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.getOrPutAssumeCapacityContext(key, self.ctx);
}
/// If there is an existing item with `key`, then the result's
/// `Entry` pointers point to it, and found_existing is true.
/// Otherwise, puts a new item with undefined value, and
/// the `Entry` pointers point to it. Caller must then initialize
/// the key and value.
/// If a new entry needs to be stored, this function asserts there
/// is enough capacity to store it.
pub fn getOrPutAssumeCapacityAdapted(self: *Self, key: anytype, ctx: anytype) GetOrPutResult {
return self.unmanaged.getOrPutAssumeCapacityAdapted(key, ctx);
}
pub fn getOrPutValue(self: *Self, key: K, value: V) Allocator.Error!Entry {
return self.unmanaged.getOrPutValueContext(self.allocator, key, value, self.ctx);
}
/// Increases capacity, guaranteeing that insertions up until the
/// `expected_count` will not cause an allocation, and therefore cannot fail.
pub fn ensureTotalCapacity(self: *Self, expected_count: Size) Allocator.Error!void {
return self.unmanaged.ensureTotalCapacityContext(self.allocator, expected_count, self.ctx);
}
/// Increases capacity, guaranteeing that insertions up until
/// `additional_count` **more** items will not cause an allocation, and
/// therefore cannot fail.
pub fn ensureUnusedCapacity(self: *Self, additional_count: Size) Allocator.Error!void {
return self.unmanaged.ensureUnusedCapacityContext(self.allocator, additional_count, self.ctx);
}
/// 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) Allocator.Error!void {
return self.unmanaged.putContext(self.allocator, key, value, self.ctx);
}
/// 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) Allocator.Error!void {
return self.unmanaged.putNoClobberContext(self.allocator, key, value, self.ctx);
}
/// 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.putAssumeCapacityContext(key, value, self.ctx);
}
/// 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.putAssumeCapacityNoClobberContext(key, value, self.ctx);
}
/// Inserts a new `Entry` into the hash map, returning the previous one, if any.
pub fn fetchPut(self: *Self, key: K, value: V) Allocator.Error!?KV {
return self.unmanaged.fetchPutContext(self.allocator, key, value, self.ctx);
}
/// 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) ?KV {
return self.unmanaged.fetchPutAssumeCapacityContext(key, value, self.ctx);
}
/// Removes a value from the map and returns the removed kv pair.
pub fn fetchRemove(self: *Self, key: K) ?KV {
return self.unmanaged.fetchRemoveContext(key, self.ctx);
}
pub fn fetchRemoveAdapted(self: *Self, key: anytype, ctx: anytype) ?KV {
return self.unmanaged.fetchRemoveAdapted(key, ctx);
}
/// Finds the value associated with a key in the map
pub fn get(self: Self, key: K) ?V {
return self.unmanaged.getContext(key, self.ctx);
}
pub fn getAdapted(self: Self, key: anytype, ctx: anytype) ?V {
return self.unmanaged.getAdapted(key, ctx);
}
pub fn getPtr(self: Self, key: K) ?*V {
return self.unmanaged.getPtrContext(key, self.ctx);
}
pub fn getPtrAdapted(self: Self, key: anytype, ctx: anytype) ?*V {
return self.unmanaged.getPtrAdapted(key, ctx);
}
/// Finds the actual key associated with an adapted key in the map
pub fn getKey(self: Self, key: K) ?K {
return self.unmanaged.getKeyContext(key, self.ctx);
}
pub fn getKeyAdapted(self: Self, key: anytype, ctx: anytype) ?K {
return self.unmanaged.getKeyAdapted(key, ctx);
}
pub fn getKeyPtr(self: Self, key: K) ?*K {
return self.unmanaged.getKeyPtrContext(key, self.ctx);
}
pub fn getKeyPtrAdapted(self: Self, key: anytype, ctx: anytype) ?*K {
return self.unmanaged.getKeyPtrAdapted(key, ctx);
}
/// Finds the key and value associated with a key in the map
pub fn getEntry(self: Self, key: K) ?Entry {
return self.unmanaged.getEntryContext(key, self.ctx);
}
pub fn getEntryAdapted(self: Self, key: anytype, ctx: anytype) ?Entry {
return self.unmanaged.getEntryAdapted(key, ctx);
}
/// Check if the map contains a key
pub fn contains(self: Self, key: K) bool {
return self.unmanaged.containsContext(key, self.ctx);
}
pub fn containsAdapted(self: Self, key: anytype, ctx: anytype) bool {
return self.unmanaged.containsAdapted(key, ctx);
}
/// If there is an `Entry` with a matching key, it is deleted from
/// the hash map, and this function returns true. Otherwise this
/// function returns false.
///
/// TODO: answer the question in these doc comments, does this
/// increase the unused capacity by one?
pub fn remove(self: *Self, key: K) bool {
return self.unmanaged.removeContext(key, self.ctx);
}
/// TODO: answer the question in these doc comments, does this
/// increase the unused capacity by one?
pub fn removeAdapted(self: *Self, key: anytype, ctx: anytype) bool {
return self.unmanaged.removeAdapted(key, ctx);
}
/// Delete the entry with key pointed to by key_ptr from the hash map.
/// key_ptr is assumed to be a valid pointer to a key that is present
/// in the hash map.
///
/// TODO: answer the question in these doc comments, does this
/// increase the unused capacity by one?
pub fn removeByPtr(self: *Self, key_ptr: *K) void {
self.unmanaged.removeByPtr(key_ptr);
}
/// Creates a copy of this map, using the same allocator
pub fn clone(self: Self) Allocator.Error!Self {
var other = try self.unmanaged.cloneContext(self.allocator, self.ctx);
return other.promoteContext(self.allocator, self.ctx);
}
/// Creates a copy of this map, using a specified allocator
pub fn cloneWithAllocator(self: Self, new_allocator: Allocator) Allocator.Error!Self {
var other = try self.unmanaged.cloneContext(new_allocator, self.ctx);
return other.promoteContext(new_allocator, self.ctx);
}
/// Creates a copy of this map, using a specified context
pub fn cloneWithContext(self: Self, new_ctx: anytype) Allocator.Error!HashMap(K, V, @TypeOf(new_ctx), max_load_percentage) {
var other = try self.unmanaged.cloneContext(self.allocator, new_ctx);
return other.promoteContext(self.allocator, new_ctx);
}
/// Creates a copy of this map, using a specified allocator and context.
pub fn cloneWithAllocatorAndContext(
self: Self,
new_allocator: Allocator,
new_ctx: anytype,
) Allocator.Error!HashMap(K, V, @TypeOf(new_ctx), max_load_percentage) {
var other = try self.unmanaged.cloneContext(new_allocator, new_ctx);
return other.promoteContext(new_allocator, new_ctx);
}
/// Set the map to an empty state, making deinitialization a no-op, and
/// returning a copy of the original.
pub fn move(self: *Self) Self {
self.unmanaged.pointer_stability.assertUnlocked();
const result = self.*;
self.unmanaged = .empty;
return result;
}
/// Rehash the map, in-place.
///
/// Over time, due to the current tombstone-based implementation, a
/// HashMap could become fragmented due to the buildup of tombstone
/// entries that causes a performance degradation due to excessive
/// probing. The kind of pattern that might cause this is a long-lived
/// HashMap with repeated inserts and deletes.
///
/// After this function is called, there will be no tombstones in
/// the HashMap, each of the entries is rehashed and any existing
/// key/value pointers into the HashMap are invalidated.
pub fn rehash(self: *Self) void {
self.unmanaged.rehash(self.ctx);
}
};
}
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 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 alternativestd.ArrayHashMap. Context must be a struct type with two member functions: hash(self, K) u64 eql(self, K, K) bool Adapted variants of many functions are provided. These variants take a pseudo key instead of a key. Their context must have the functions: hash(self, PseudoKey) u64 eql(self, PseudoKey, K) bool