source: mainline/common/adt/hash_table.c@ cad7b7e

topic/simplify-dev-export
Last change on this file since cad7b7e was ad9178bf, checked in by Jiří Zárevúcky <zarevucky.jiri@…>, 20 months ago

Deduplicate ADT

  • Property mode set to 100644
File size: 12.5 KB
Line 
1/*
2 * Copyright (c) 2008 Jakub Jermar
3 * Copyright (c) 2012 Adam Hraska
4 *
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 *
11 * - Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * - Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * - The name of the author may not be used to endorse or promote products
17 * derived from this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31/** @addtogroup libc
32 * @{
33 */
34/** @file
35 */
36
37/*
38 * This is an implementation of a generic resizable chained hash table.
39 *
40 * The table grows to 2*n+1 buckets each time, starting at n == 89,
41 * per Thomas Wang's recommendation:
42 * http://www.concentric.net/~Ttwang/tech/hashsize.htm
43 *
44 * This policy produces prime table sizes for the first five resizes
45 * and generally produces table sizes which are either prime or
46 * have fairly large (prime/odd) divisors. Having a prime table size
47 * mitigates the use of suboptimal hash functions and distributes
48 * items over the whole table.
49 */
50
51#include <adt/hash_table.h>
52#include <adt/list.h>
53#include <assert.h>
54#include <stdlib.h>
55#include <str.h>
56
57/* Optimal initial bucket count. See comment above. */
58#define HT_MIN_BUCKETS 89
59/* The table is resized when the average load per bucket exceeds this number. */
60#define HT_MAX_LOAD 2
61
62static size_t round_up_size(size_t);
63static bool alloc_table(size_t, list_t **);
64static void clear_items(hash_table_t *);
65static void resize(hash_table_t *, size_t);
66static void grow_if_needed(hash_table_t *);
67static void shrink_if_needed(hash_table_t *);
68
69/* Dummy do nothing callback to invoke in place of remove_callback == NULL. */
70static void nop_remove_callback(ht_link_t *item)
71{
72 /* no-op */
73}
74
75/** Create chained hash table.
76 *
77 * @param h Hash table structure. Will be initialized by this call.
78 * @param init_size Initial desired number of hash table buckets. Pass zero
79 * if you want the default initial size.
80 * @param max_load The table is resized when the average load per bucket
81 * exceeds this number. Pass zero if you want the default.
82 * @param op Hash table operations structure. remove_callback()
83 * is optional and can be NULL if no action is to be taken
84 * upon removal. equal() is optional if and only if
85 * hash_table_insert_unique() will never be invoked.
86 * All other operations are mandatory.
87 *
88 * @return True on success
89 *
90 */
91bool hash_table_create(hash_table_t *h, size_t init_size, size_t max_load,
92 const hash_table_ops_t *op)
93{
94 assert(h);
95 assert(op && op->hash && op->key_hash && op->key_equal);
96
97 /* Check for compulsory ops. */
98 if (!op || !op->hash || !op->key_hash || !op->key_equal)
99 return false;
100
101 h->bucket_cnt = round_up_size(init_size);
102
103 if (!alloc_table(h->bucket_cnt, &h->bucket))
104 return false;
105
106 h->max_load = (max_load == 0) ? HT_MAX_LOAD : max_load;
107 h->item_cnt = 0;
108 h->op = op;
109 h->full_item_cnt = h->max_load * h->bucket_cnt;
110 h->apply_ongoing = false;
111
112 return true;
113}
114
115/** Destroy a hash table instance.
116 *
117 * @param h Hash table to be destroyed.
118 *
119 */
120void hash_table_destroy(hash_table_t *h)
121{
122 assert(h && h->bucket);
123 assert(!h->apply_ongoing);
124
125 clear_items(h);
126
127 free(h->bucket);
128
129 h->bucket = NULL;
130 h->bucket_cnt = 0;
131}
132
133/** Returns true if there are no items in the table. */
134bool hash_table_empty(hash_table_t *h)
135{
136 assert(h && h->bucket);
137 return h->item_cnt == 0;
138}
139
140/** Returns the number of items in the table. */
141size_t hash_table_size(hash_table_t *h)
142{
143 assert(h && h->bucket);
144 return h->item_cnt;
145}
146
147/** Remove all elements from the hash table
148 *
149 * @param h Hash table to be cleared
150 */
151void hash_table_clear(hash_table_t *h)
152{
153 assert(h && h->bucket);
154 assert(!h->apply_ongoing);
155
156 clear_items(h);
157
158 /* Shrink the table to its minimum size if possible. */
159 if (HT_MIN_BUCKETS < h->bucket_cnt) {
160 resize(h, HT_MIN_BUCKETS);
161 }
162}
163
164/** Unlinks and removes all items but does not resize. */
165static void clear_items(hash_table_t *h)
166{
167 if (h->item_cnt == 0)
168 return;
169
170 void (*remove_cb)(ht_link_t *) = h->op->remove_callback ? h->op->remove_callback : nop_remove_callback;
171
172 for (size_t idx = 0; idx < h->bucket_cnt; ++idx) {
173 list_foreach_safe(h->bucket[idx], cur, next) {
174 assert(cur);
175 ht_link_t *cur_link = member_to_inst(cur, ht_link_t, link);
176
177 list_remove(cur);
178 remove_cb(cur_link);
179 }
180 }
181
182 h->item_cnt = 0;
183}
184
185/** Insert item into a hash table.
186 *
187 * @param h Hash table.
188 * @param item Item to be inserted into the hash table.
189 */
190void hash_table_insert(hash_table_t *h, ht_link_t *item)
191{
192 assert(item);
193 assert(h && h->bucket);
194 assert(!h->apply_ongoing);
195
196 size_t idx = h->op->hash(item) % h->bucket_cnt;
197
198 list_append(&item->link, &h->bucket[idx]);
199 ++h->item_cnt;
200 grow_if_needed(h);
201}
202
203/** Insert item into a hash table if not already present.
204 *
205 * @param h Hash table.
206 * @param item Item to be inserted into the hash table.
207 *
208 * @return False if such an item had already been inserted.
209 * @return True if the inserted item was the only item with such a lookup key.
210 */
211bool hash_table_insert_unique(hash_table_t *h, ht_link_t *item)
212{
213 assert(item);
214 assert(h && h->bucket && h->bucket_cnt);
215 assert(h->op && h->op->hash && h->op->equal);
216 assert(!h->apply_ongoing);
217
218 size_t idx = h->op->hash(item) % h->bucket_cnt;
219
220 /* Check for duplicates. */
221 list_foreach(h->bucket[idx], link, ht_link_t, cur_link) {
222 /*
223 * We could filter out items using their hashes first, but
224 * calling equal() might very well be just as fast.
225 */
226 if (h->op->equal(cur_link, item))
227 return false;
228 }
229
230 list_append(&item->link, &h->bucket[idx]);
231 ++h->item_cnt;
232 grow_if_needed(h);
233
234 return true;
235}
236
237/** Search hash table for an item matching keys.
238 *
239 * @param h Hash table.
240 * @param key Array of all keys needed to compute hash index.
241 *
242 * @return Matching item on success, NULL if there is no such item.
243 *
244 */
245ht_link_t *hash_table_find(const hash_table_t *h, const void *key)
246{
247 assert(h && h->bucket);
248
249 size_t idx = h->op->key_hash(key) % h->bucket_cnt;
250
251 list_foreach(h->bucket[idx], link, ht_link_t, cur_link) {
252 /*
253 * Is this is the item we are looking for? We could have first
254 * checked if the hashes match but op->key_equal() may very well be
255 * just as fast as op->hash().
256 */
257 if (h->op->key_equal(key, cur_link)) {
258 return cur_link;
259 }
260 }
261
262 return NULL;
263}
264
265/** Find the next item equal to item. */
266ht_link_t *
267hash_table_find_next(const hash_table_t *h, ht_link_t *first, ht_link_t *item)
268{
269 assert(item);
270 assert(h && h->bucket);
271
272 size_t idx = h->op->hash(item) % h->bucket_cnt;
273
274 /* Traverse the circular list until we reach the starting item again. */
275 for (link_t *cur = item->link.next; cur != &first->link;
276 cur = cur->next) {
277 assert(cur);
278
279 if (cur == &h->bucket[idx].head)
280 continue;
281
282 ht_link_t *cur_link = member_to_inst(cur, ht_link_t, link);
283 /*
284 * Is this is the item we are looking for? We could have first
285 * checked if the hashes match but op->equal() may very well be
286 * just as fast as op->hash().
287 */
288 if (h->op->equal(cur_link, item)) {
289 return cur_link;
290 }
291 }
292
293 return NULL;
294}
295
296/** Remove all matching items from hash table.
297 *
298 * For each removed item, h->remove_callback() is called.
299 *
300 * @param h Hash table.
301 * @param key Array of keys that will be compared against items of
302 * the hash table.
303 *
304 * @return Returns the number of removed items.
305 */
306size_t hash_table_remove(hash_table_t *h, const void *key)
307{
308 assert(h && h->bucket);
309 assert(!h->apply_ongoing);
310
311 size_t idx = h->op->key_hash(key) % h->bucket_cnt;
312
313 size_t removed = 0;
314
315 list_foreach_safe(h->bucket[idx], cur, next) {
316 ht_link_t *cur_link = member_to_inst(cur, ht_link_t, link);
317
318 if (h->op->key_equal(key, cur_link)) {
319 ++removed;
320 list_remove(cur);
321
322 if (h->op->remove_callback)
323 h->op->remove_callback(cur_link);
324 }
325 }
326
327 h->item_cnt -= removed;
328 shrink_if_needed(h);
329
330 return removed;
331}
332
333/** Removes an item already present in the table. The item must be in the table. */
334void hash_table_remove_item(hash_table_t *h, ht_link_t *item)
335{
336 assert(item);
337 assert(h && h->bucket);
338 assert(link_in_use(&item->link));
339
340 list_remove(&item->link);
341 --h->item_cnt;
342
343 if (h->op->remove_callback)
344 h->op->remove_callback(item);
345 shrink_if_needed(h);
346}
347
348/** Apply function to all items in hash table.
349 *
350 * @param h Hash table.
351 * @param f Function to be applied. Return false if no more items
352 * should be visited. The functor may only delete the supplied
353 * item. It must not delete the successor of the item passed
354 * in the first argument.
355 * @param arg Argument to be passed to the function.
356 */
357void hash_table_apply(hash_table_t *h, bool (*f)(ht_link_t *, void *), void *arg)
358{
359 assert(f);
360 assert(h && h->bucket);
361
362 if (h->item_cnt == 0)
363 return;
364
365 h->apply_ongoing = true;
366
367 for (size_t idx = 0; idx < h->bucket_cnt; ++idx) {
368 list_foreach_safe(h->bucket[idx], cur, next) {
369 ht_link_t *cur_link = member_to_inst(cur, ht_link_t, link);
370 /*
371 * The next pointer had already been saved. f() may safely
372 * delete cur (but not next!).
373 */
374 if (!f(cur_link, arg))
375 goto out;
376 }
377 }
378out:
379 h->apply_ongoing = false;
380
381 shrink_if_needed(h);
382 grow_if_needed(h);
383}
384
385/** Rounds up size to the nearest suitable table size. */
386static size_t round_up_size(size_t size)
387{
388 size_t rounded_size = HT_MIN_BUCKETS;
389
390 while (rounded_size < size) {
391 rounded_size = 2 * rounded_size + 1;
392 }
393
394 return rounded_size;
395}
396
397/** Allocates and initializes the desired number of buckets. True if successful. */
398static bool alloc_table(size_t bucket_cnt, list_t **pbuckets)
399{
400 assert(pbuckets && HT_MIN_BUCKETS <= bucket_cnt);
401
402 list_t *buckets = malloc(bucket_cnt * sizeof(list_t));
403 if (!buckets)
404 return false;
405
406 for (size_t i = 0; i < bucket_cnt; i++)
407 list_initialize(&buckets[i]);
408
409 *pbuckets = buckets;
410 return true;
411}
412
413/** Shrinks the table if the table is only sparely populated. */
414static inline void shrink_if_needed(hash_table_t *h)
415{
416 if (h->item_cnt <= h->full_item_cnt / 4 && HT_MIN_BUCKETS < h->bucket_cnt) {
417 /*
418 * Keep the bucket_cnt odd (possibly also prime).
419 * Shrink from 2n + 1 to n. Integer division discards the +1.
420 */
421 size_t new_bucket_cnt = h->bucket_cnt / 2;
422 resize(h, new_bucket_cnt);
423 }
424}
425
426/** Grows the table if table load exceeds the maximum allowed. */
427static inline void grow_if_needed(hash_table_t *h)
428{
429 /* Grow the table if the average bucket load exceeds the maximum. */
430 if (h->full_item_cnt < h->item_cnt) {
431 /* Keep the bucket_cnt odd (possibly also prime). */
432 size_t new_bucket_cnt = 2 * h->bucket_cnt + 1;
433 resize(h, new_bucket_cnt);
434 }
435}
436
437/** Allocates and rehashes items to a new table. Frees the old table. */
438static void resize(hash_table_t *h, size_t new_bucket_cnt)
439{
440 assert(h && h->bucket);
441 assert(HT_MIN_BUCKETS <= new_bucket_cnt);
442
443 /* We are traversing the table and resizing would mess up the buckets. */
444 if (h->apply_ongoing)
445 return;
446
447 list_t *new_buckets;
448
449 /* Leave the table as is if we cannot resize. */
450 if (!alloc_table(new_bucket_cnt, &new_buckets))
451 return;
452
453 if (0 < h->item_cnt) {
454 /* Rehash all the items to the new table. */
455 for (size_t old_idx = 0; old_idx < h->bucket_cnt; ++old_idx) {
456 list_foreach_safe(h->bucket[old_idx], cur, next) {
457 ht_link_t *cur_link = member_to_inst(cur, ht_link_t, link);
458
459 size_t new_idx = h->op->hash(cur_link) % new_bucket_cnt;
460 list_remove(cur);
461 list_append(cur, &new_buckets[new_idx]);
462 }
463 }
464 }
465
466 free(h->bucket);
467 h->bucket = new_buckets;
468 h->bucket_cnt = new_bucket_cnt;
469 h->full_item_cnt = h->max_load * h->bucket_cnt;
470}
471
472/** @}
473 */
Note: See TracBrowser for help on using the repository browser.