aboutsummaryrefslogtreecommitdiff
path: root/source/tanya/container/hashtable.d
blob: f2ddc5c2274a7e5f43427e363fb67ecc67112216 (plain)
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/**
 * Hash table.
 *
 * Copyright: Eugene Wissner 2017.
 * License: $(LINK2 https://www.mozilla.org/en-US/MPL/2.0/,
 *                  Mozilla Public License, v. 2.0).
 * Authors: $(LINK2 mailto:info@caraus.de, Eugene Wissner)
 */
module tanya.container.hashtable;

import std.algorithm.comparison;
import std.traits;
import tanya.container.entry;
import tanya.memory;

private int compare(const(char)[] key1, const(char)[] key2)
{
    return cmp(key1, key2);
}

private int compare(K)(K key1, K key2)
    if (isIntegral!K)
{
    return cast(int) (key1 - key2);
}

struct Range(K, V)
{
    private HashEntry!(K, V)*[] table;
    private size_t begin, end;

    invariant
    {
        assert(this.begin <= this.end);
    }

    private this(HashEntry!(K, V)*[] table)
    {
        this.table = table;
    }

    @property bool empty() const
    {
        for (size_t i = this.begin; i < this.begin; ++i)
        {
            if (this.table[i] !is null)
            {
                return false;
            }
        }
        return true;
    }
}

struct HashTable(K, V)
{
    /**
     * Create a new hashtable.
     *
     * Params:
     *  size      = Minimum number of initial buckets.
     *  allocator = Allocator.
     */
    this(const size_t size, shared Allocator allocator = defaultAllocator)
    in
    {
        assert(size >= 1);
    }
    body
    {
        this(allocator);
        this.table = new HashEntry!(K, V)*[size];
    }

    /// Ditto.
    this(shared Allocator allocator)
    in
    {
        assert(allocator !is null);
    }
    body
    {
        this.allocator_ = allocator;
    }

    private size_t calculateHash(const(char)[] key)
    {
        size_t hashval;

        for (int i; hashval < size_t.max && i < key.length; ++i)
        {
            hashval = hashval << 8;
            hashval += key[i];
        }

        return hashval % this.table.length;
    }

    private size_t calculateHash()(K key)
        if (isIntegral!K)
    {
        return key % this.table.length;
    }

    /**
     * Retrieve a key-value pair from a hash table.
     */
    V opIndex(K key)
    {
        auto bin = calculateHash(key);
        auto pair = this.table[bin];

        while (pair !is null && compare(key, pair.pair[0]) > 0)
        {
            pair = pair.next;
        }

        // Did we actually find anything?
        if (pair is null || compare(key, pair.pair[0]) != 0)
        {
            return null;
        }
        else
        {
            return pair.pair[1];
        }
    }

    /**
     * Insert a key-value pair into a hash table.
     */
    bool insert(K key, V value)
    {
        HashEntry!(K, V)* last;
        auto bin = calculateHash(key);
        auto next = this.table[bin];

        while (next !is null && compare(key, next.pair[0]) > 0)
        {
            last = next;
            next = next.next;
        }

        // There's already a pair.
        if (next !is null && compare(key, next.pair[0]) == 0)
        {
            next.pair[1] = value;
            return false;
        }
        else // Nope, could't find it.  Time to grow a pair.
        {
            auto newpair = new HashEntry!(K, V)(key, value);

            // We're at the start of the linked list in this bin.
            if (next == this.table[bin])
            {
                newpair.next = next;
                this.table[bin] = newpair;
            }
            else if (next is null)
            {
                // We're at the end of the linked list in this bin.
                last.next = newpair;
            }
            else
            {
                // We're in the middle of the list.
                newpair.next = next;
                last.next = newpair;
            }
            return true;
        }
    }

    void opIndexAssign(V value, K key)
    {
        insert(key, value);
    }

    Range!(K, V) opIndex()
    {
        return typeof(return)(this.table);
    }

    @property bool empty() const
    {
        foreach (entry; this.table)
        {
            if (entry !is null)
            {
                return false;
            }
        }
        return true;
    }

    private HashEntry!(K, V)*[] table;

    mixin DefaultAllocator;
}

unittest
{
    auto ht = HashTable!(string, string)(65536);
    assert(ht.empty);

    ht["key1"] = "inky";
    ht["key2"] = "pinky";
    ht["key3"] = "blinky";
    ht["key4"] = "floyd";

    assert(!ht.empty);
    assert("inky" == ht["key1"]);
    assert("pinky" == ht["key2"]);
    assert("blinky" == ht["key3"]);
    assert("floyd" == ht["key4"]);
}