HashMap

struct HashMap (
K
V
Allocator = Mallocator
) {
enum initial_buckets_num;
enum grow_factor;
enum inlineValues;
enum EMPTY_HASH;
enum DELETED_HASH;
enum ALLOCATED_HASH;
enum TYPE_MASK;
enum HASH_MASK;
enum EMPTY_HASH;
enum DELETED_HASH;
enum ALLOCATED_HASH;
enum TYPE_MASK;
enum HASH_MASK;
}

Destructor

A destructor is present on this object, but not explicitly documented in the source.

Members

Functions

get
V get(K k, T defaultValue)

Attention: this can't return ref as default value can be rvalue

opBinaryRight
V* opBinaryRight(in K k)

Lookup methods

opIndex
V opIndex(in K k)

Attention: you can't use this method in @nogc code. Usual aakey method. Throws exception if key not found

opIndexAssign
void opIndexAssign(V v, K k)

Modifiers

put
V* put(K k, V v)

put pair (k,v) into hash. it must be @safe, it inherits @nogc properties from K and V It can resize hashtable it is overloaded or has too much deleted entries

Examples

Tests test immutable struct and class as Key type

1 () @nogc
2 {
3     struct S
4     {
5         int s;
6     }
7     HashMap!(immutable S, int) hs1;
8     immutable ss = S(1);
9     hs1[ss] = 1;
10     assert(ss in hs1 && *(ss in hs1) == 1);
11     HashMap!(int, immutable S) hs2;
12     hs2[1] = ss;
13     assert(1 in hs2 && *(1 in hs2) == ss);
14     assert(!(2 in hs2));
15 }();
16 
17 // class
18 class C
19 {
20     int v;
21     this(int _v) pure inout
22     {
23         v = _v;
24     }
25     bool opEquals(const C o) pure const @safe @nogc nothrow {
26         return v == o.v;
27     }
28     override hash_t toHash() const @safe @nogc {
29         return hash_function(v);
30     }
31 }
32 HashMap!(immutable C, int) hc1;
33 immutable cc = new immutable C(1);
34 hc1[cc] = 1;
35 assert(hc1[cc] == 1);
36 HashMap!(int, immutable C) hc2;
37 hc2[1] = cc;
38 assert(hc2[1] is cc);

Test if we can work with non-@nogc opEquals for class-key. opEquals anyway must be non-@system.

1 class c {
2     int a;
3     this(int a)
4     {
5         this.a = a;
6     }
7     override hash_t toHash() const pure @safe
8     {
9         int[] _ = [1, 2, 3]; // this cause GC
10         return hash_function(a);
11     }
12 
13     bool opEquals(const c other) const pure @safe
14     {
15         auto _ = [1,2,3]; // this cause GC
16         return this is other || this.a == other.a;
17     }
18 }
19 alias K = c;
20 alias V = int;
21 HashMap!(K,V) h;
22 K k0 = new c(0);
23 V v0 = 1;
24 h.put(k0, v0);
25 int *v = k0 in h;
26 assert(v);
27 assert(*v == 1);

Meta