hash_table.c revision 01e04c3f
1/*
2 * Copyright © 2009,2012 Intel Corporation
3 * Copyright © 1988-2004 Keith Packard and Bart Massey.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a
6 * copy of this software and associated documentation files (the "Software"),
7 * to deal in the Software without restriction, including without limitation
8 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 * and/or sell copies of the Software, and to permit persons to whom the
10 * Software is furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice (including the next
13 * paragraph) shall be included in all copies or substantial portions of the
14 * Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22 * IN THE SOFTWARE.
23 *
24 * Except as contained in this notice, the names of the authors
25 * or their institutions shall not be used in advertising or
26 * otherwise to promote the sale, use or other dealings in this
27 * Software without prior written authorization from the
28 * authors.
29 *
30 * Authors:
31 *    Eric Anholt <eric@anholt.net>
32 *    Keith Packard <keithp@keithp.com>
33 */
34
35/**
36 * Implements an open-addressing, linear-reprobing hash table.
37 *
38 * For more information, see:
39 *
40 * http://cgit.freedesktop.org/~anholt/hash_table/tree/README
41 */
42
43#include <stdlib.h>
44#include <string.h>
45#include <assert.h>
46
47#include "hash_table.h"
48#include "ralloc.h"
49#include "macros.h"
50#include "main/hash.h"
51
52static const uint32_t deleted_key_value;
53
54/**
55 * From Knuth -- a good choice for hash/rehash values is p, p-2 where
56 * p and p-2 are both prime.  These tables are sized to have an extra 10%
57 * free to avoid exponential performance degradation as the hash table fills
58 */
59static const struct {
60   uint32_t max_entries, size, rehash;
61} hash_sizes[] = {
62   { 2,			5,		3	  },
63   { 4,			7,		5	  },
64   { 8,			13,		11	  },
65   { 16,		19,		17	  },
66   { 32,		43,		41        },
67   { 64,		73,		71        },
68   { 128,		151,		149       },
69   { 256,		283,		281       },
70   { 512,		571,		569       },
71   { 1024,		1153,		1151      },
72   { 2048,		2269,		2267      },
73   { 4096,		4519,		4517      },
74   { 8192,		9013,		9011      },
75   { 16384,		18043,		18041     },
76   { 32768,		36109,		36107     },
77   { 65536,		72091,		72089     },
78   { 131072,		144409,		144407    },
79   { 262144,		288361,		288359    },
80   { 524288,		576883,		576881    },
81   { 1048576,		1153459,	1153457   },
82   { 2097152,		2307163,	2307161   },
83   { 4194304,		4613893,	4613891   },
84   { 8388608,		9227641,	9227639   },
85   { 16777216,		18455029,	18455027  },
86   { 33554432,		36911011,	36911009  },
87   { 67108864,		73819861,	73819859  },
88   { 134217728,		147639589,	147639587 },
89   { 268435456,		295279081,	295279079 },
90   { 536870912,		590559793,	590559791 },
91   { 1073741824,	1181116273,	1181116271},
92   { 2147483648ul,	2362232233ul,	2362232231ul}
93};
94
95static int
96entry_is_free(const struct hash_entry *entry)
97{
98   return entry->key == NULL;
99}
100
101static int
102entry_is_deleted(const struct hash_table *ht, struct hash_entry *entry)
103{
104   return entry->key == ht->deleted_key;
105}
106
107static int
108entry_is_present(const struct hash_table *ht, struct hash_entry *entry)
109{
110   return entry->key != NULL && entry->key != ht->deleted_key;
111}
112
113struct hash_table *
114_mesa_hash_table_create(void *mem_ctx,
115                        uint32_t (*key_hash_function)(const void *key),
116                        bool (*key_equals_function)(const void *a,
117                                                    const void *b))
118{
119   struct hash_table *ht;
120
121   ht = ralloc(mem_ctx, struct hash_table);
122   if (ht == NULL)
123      return NULL;
124
125   ht->size_index = 0;
126   ht->size = hash_sizes[ht->size_index].size;
127   ht->rehash = hash_sizes[ht->size_index].rehash;
128   ht->max_entries = hash_sizes[ht->size_index].max_entries;
129   ht->key_hash_function = key_hash_function;
130   ht->key_equals_function = key_equals_function;
131   ht->table = rzalloc_array(ht, struct hash_entry, ht->size);
132   ht->entries = 0;
133   ht->deleted_entries = 0;
134   ht->deleted_key = &deleted_key_value;
135
136   if (ht->table == NULL) {
137      ralloc_free(ht);
138      return NULL;
139   }
140
141   return ht;
142}
143
144struct hash_table *
145_mesa_hash_table_clone(struct hash_table *src, void *dst_mem_ctx)
146{
147   struct hash_table *ht;
148
149   ht = ralloc(dst_mem_ctx, struct hash_table);
150   if (ht == NULL)
151      return NULL;
152
153   memcpy(ht, src, sizeof(struct hash_table));
154
155   ht->table = ralloc_array(ht, struct hash_entry, ht->size);
156   if (ht->table == NULL) {
157      ralloc_free(ht);
158      return NULL;
159   }
160
161   memcpy(ht->table, src->table, ht->size * sizeof(struct hash_entry));
162
163   return ht;
164}
165
166/**
167 * Frees the given hash table.
168 *
169 * If delete_function is passed, it gets called on each entry present before
170 * freeing.
171 */
172void
173_mesa_hash_table_destroy(struct hash_table *ht,
174                         void (*delete_function)(struct hash_entry *entry))
175{
176   if (!ht)
177      return;
178
179   if (delete_function) {
180      hash_table_foreach(ht, entry) {
181         delete_function(entry);
182      }
183   }
184   ralloc_free(ht);
185}
186
187/**
188 * Deletes all entries of the given hash table without deleting the table
189 * itself or changing its structure.
190 *
191 * If delete_function is passed, it gets called on each entry present.
192 */
193void
194_mesa_hash_table_clear(struct hash_table *ht,
195                       void (*delete_function)(struct hash_entry *entry))
196{
197   struct hash_entry *entry;
198
199   for (entry = ht->table; entry != ht->table + ht->size; entry++) {
200      if (entry->key == NULL)
201         continue;
202
203      if (delete_function != NULL && entry->key != ht->deleted_key)
204         delete_function(entry);
205
206      entry->key = NULL;
207   }
208
209   ht->entries = 0;
210   ht->deleted_entries = 0;
211}
212
213/** Sets the value of the key pointer used for deleted entries in the table.
214 *
215 * The assumption is that usually keys are actual pointers, so we use a
216 * default value of a pointer to an arbitrary piece of storage in the library.
217 * But in some cases a consumer wants to store some other sort of value in the
218 * table, like a uint32_t, in which case that pointer may conflict with one of
219 * their valid keys.  This lets that user select a safe value.
220 *
221 * This must be called before any keys are actually deleted from the table.
222 */
223void
224_mesa_hash_table_set_deleted_key(struct hash_table *ht, const void *deleted_key)
225{
226   ht->deleted_key = deleted_key;
227}
228
229static struct hash_entry *
230hash_table_search(struct hash_table *ht, uint32_t hash, const void *key)
231{
232   uint32_t start_hash_address = hash % ht->size;
233   uint32_t hash_address = start_hash_address;
234
235   do {
236      uint32_t double_hash;
237
238      struct hash_entry *entry = ht->table + hash_address;
239
240      if (entry_is_free(entry)) {
241         return NULL;
242      } else if (entry_is_present(ht, entry) && entry->hash == hash) {
243         if (ht->key_equals_function(key, entry->key)) {
244            return entry;
245         }
246      }
247
248      double_hash = 1 + hash % ht->rehash;
249
250      hash_address = (hash_address + double_hash) % ht->size;
251   } while (hash_address != start_hash_address);
252
253   return NULL;
254}
255
256/**
257 * Finds a hash table entry with the given key and hash of that key.
258 *
259 * Returns NULL if no entry is found.  Note that the data pointer may be
260 * modified by the user.
261 */
262struct hash_entry *
263_mesa_hash_table_search(struct hash_table *ht, const void *key)
264{
265   assert(ht->key_hash_function);
266   return hash_table_search(ht, ht->key_hash_function(key), key);
267}
268
269struct hash_entry *
270_mesa_hash_table_search_pre_hashed(struct hash_table *ht, uint32_t hash,
271                                  const void *key)
272{
273   assert(ht->key_hash_function == NULL || hash == ht->key_hash_function(key));
274   return hash_table_search(ht, hash, key);
275}
276
277static struct hash_entry *
278hash_table_insert(struct hash_table *ht, uint32_t hash,
279                  const void *key, void *data);
280
281static void
282_mesa_hash_table_rehash(struct hash_table *ht, unsigned new_size_index)
283{
284   struct hash_table old_ht;
285   struct hash_entry *table;
286
287   if (new_size_index >= ARRAY_SIZE(hash_sizes))
288      return;
289
290   table = rzalloc_array(ht, struct hash_entry,
291                         hash_sizes[new_size_index].size);
292   if (table == NULL)
293      return;
294
295   old_ht = *ht;
296
297   ht->table = table;
298   ht->size_index = new_size_index;
299   ht->size = hash_sizes[ht->size_index].size;
300   ht->rehash = hash_sizes[ht->size_index].rehash;
301   ht->max_entries = hash_sizes[ht->size_index].max_entries;
302   ht->entries = 0;
303   ht->deleted_entries = 0;
304
305   hash_table_foreach(&old_ht, entry) {
306      hash_table_insert(ht, entry->hash, entry->key, entry->data);
307   }
308
309   ralloc_free(old_ht.table);
310}
311
312static struct hash_entry *
313hash_table_insert(struct hash_table *ht, uint32_t hash,
314                  const void *key, void *data)
315{
316   uint32_t start_hash_address, hash_address;
317   struct hash_entry *available_entry = NULL;
318
319   assert(key != NULL);
320
321   if (ht->entries >= ht->max_entries) {
322      _mesa_hash_table_rehash(ht, ht->size_index + 1);
323   } else if (ht->deleted_entries + ht->entries >= ht->max_entries) {
324      _mesa_hash_table_rehash(ht, ht->size_index);
325   }
326
327   start_hash_address = hash % ht->size;
328   hash_address = start_hash_address;
329   do {
330      struct hash_entry *entry = ht->table + hash_address;
331      uint32_t double_hash;
332
333      if (!entry_is_present(ht, entry)) {
334         /* Stash the first available entry we find */
335         if (available_entry == NULL)
336            available_entry = entry;
337         if (entry_is_free(entry))
338            break;
339      }
340
341      /* Implement replacement when another insert happens
342       * with a matching key.  This is a relatively common
343       * feature of hash tables, with the alternative
344       * generally being "insert the new value as well, and
345       * return it first when the key is searched for".
346       *
347       * Note that the hash table doesn't have a delete
348       * callback.  If freeing of old data pointers is
349       * required to avoid memory leaks, perform a search
350       * before inserting.
351       */
352      if (!entry_is_deleted(ht, entry) &&
353          entry->hash == hash &&
354          ht->key_equals_function(key, entry->key)) {
355         entry->key = key;
356         entry->data = data;
357         return entry;
358      }
359
360
361      double_hash = 1 + hash % ht->rehash;
362
363      hash_address = (hash_address + double_hash) % ht->size;
364   } while (hash_address != start_hash_address);
365
366   if (available_entry) {
367      if (entry_is_deleted(ht, available_entry))
368         ht->deleted_entries--;
369      available_entry->hash = hash;
370      available_entry->key = key;
371      available_entry->data = data;
372      ht->entries++;
373      return available_entry;
374   }
375
376   /* We could hit here if a required resize failed. An unchecked-malloc
377    * application could ignore this result.
378    */
379   return NULL;
380}
381
382/**
383 * Inserts the key with the given hash into the table.
384 *
385 * Note that insertion may rearrange the table on a resize or rehash,
386 * so previously found hash_entries are no longer valid after this function.
387 */
388struct hash_entry *
389_mesa_hash_table_insert(struct hash_table *ht, const void *key, void *data)
390{
391   assert(ht->key_hash_function);
392   return hash_table_insert(ht, ht->key_hash_function(key), key, data);
393}
394
395struct hash_entry *
396_mesa_hash_table_insert_pre_hashed(struct hash_table *ht, uint32_t hash,
397                                   const void *key, void *data)
398{
399   assert(ht->key_hash_function == NULL || hash == ht->key_hash_function(key));
400   return hash_table_insert(ht, hash, key, data);
401}
402
403/**
404 * This function deletes the given hash table entry.
405 *
406 * Note that deletion doesn't otherwise modify the table, so an iteration over
407 * the table deleting entries is safe.
408 */
409void
410_mesa_hash_table_remove(struct hash_table *ht,
411                        struct hash_entry *entry)
412{
413   if (!entry)
414      return;
415
416   entry->key = ht->deleted_key;
417   ht->entries--;
418   ht->deleted_entries++;
419}
420
421/**
422 * Removes the entry with the corresponding key, if exists.
423 */
424void _mesa_hash_table_remove_key(struct hash_table *ht,
425                                 const void *key)
426{
427   _mesa_hash_table_remove(ht, _mesa_hash_table_search(ht, key));
428}
429
430/**
431 * This function is an iterator over the hash table.
432 *
433 * Pass in NULL for the first entry, as in the start of a for loop.  Note that
434 * an iteration over the table is O(table_size) not O(entries).
435 */
436struct hash_entry *
437_mesa_hash_table_next_entry(struct hash_table *ht,
438                            struct hash_entry *entry)
439{
440   if (entry == NULL)
441      entry = ht->table;
442   else
443      entry = entry + 1;
444
445   for (; entry != ht->table + ht->size; entry++) {
446      if (entry_is_present(ht, entry)) {
447         return entry;
448      }
449   }
450
451   return NULL;
452}
453
454/**
455 * Returns a random entry from the hash table.
456 *
457 * This may be useful in implementing random replacement (as opposed
458 * to just removing everything) in caches based on this hash table
459 * implementation.  @predicate may be used to filter entries, or may
460 * be set to NULL for no filtering.
461 */
462struct hash_entry *
463_mesa_hash_table_random_entry(struct hash_table *ht,
464                              bool (*predicate)(struct hash_entry *entry))
465{
466   struct hash_entry *entry;
467   uint32_t i = rand() % ht->size;
468
469   if (ht->entries == 0)
470      return NULL;
471
472   for (entry = ht->table + i; entry != ht->table + ht->size; entry++) {
473      if (entry_is_present(ht, entry) &&
474          (!predicate || predicate(entry))) {
475         return entry;
476      }
477   }
478
479   for (entry = ht->table; entry != ht->table + i; entry++) {
480      if (entry_is_present(ht, entry) &&
481          (!predicate || predicate(entry))) {
482         return entry;
483      }
484   }
485
486   return NULL;
487}
488
489
490/**
491 * Quick FNV-1a hash implementation based on:
492 * http://www.isthe.com/chongo/tech/comp/fnv/
493 *
494 * FNV-1a is not be the best hash out there -- Jenkins's lookup3 is supposed
495 * to be quite good, and it probably beats FNV.  But FNV has the advantage
496 * that it involves almost no code.  For an improvement on both, see Paul
497 * Hsieh's http://www.azillionmonkeys.com/qed/hash.html
498 */
499uint32_t
500_mesa_hash_data(const void *data, size_t size)
501{
502   return _mesa_fnv32_1a_accumulate_block(_mesa_fnv32_1a_offset_bias,
503                                          data, size);
504}
505
506/** FNV-1a string hash implementation */
507uint32_t
508_mesa_hash_string(const void *_key)
509{
510   uint32_t hash = _mesa_fnv32_1a_offset_bias;
511   const char *key = _key;
512
513   while (*key != 0) {
514      hash = _mesa_fnv32_1a_accumulate(hash, *key);
515      key++;
516   }
517
518   return hash;
519}
520
521/**
522 * String compare function for use as the comparison callback in
523 * _mesa_hash_table_create().
524 */
525bool
526_mesa_key_string_equal(const void *a, const void *b)
527{
528   return strcmp(a, b) == 0;
529}
530
531bool
532_mesa_key_pointer_equal(const void *a, const void *b)
533{
534   return a == b;
535}
536
537/**
538 * Hash table wrapper which supports 64-bit keys.
539 *
540 * TODO: unify all hash table implementations.
541 */
542
543struct hash_key_u64 {
544   uint64_t value;
545};
546
547static uint32_t
548key_u64_hash(const void *key)
549{
550   return _mesa_hash_data(key, sizeof(struct hash_key_u64));
551}
552
553static bool
554key_u64_equals(const void *a, const void *b)
555{
556   const struct hash_key_u64 *aa = a;
557   const struct hash_key_u64 *bb = b;
558
559   return aa->value == bb->value;
560}
561
562struct hash_table_u64 *
563_mesa_hash_table_u64_create(void *mem_ctx)
564{
565   struct hash_table_u64 *ht;
566
567   ht = CALLOC_STRUCT(hash_table_u64);
568   if (!ht)
569      return NULL;
570
571   if (sizeof(void *) == 8) {
572      ht->table = _mesa_hash_table_create(mem_ctx, _mesa_hash_pointer,
573                                          _mesa_key_pointer_equal);
574   } else {
575      ht->table = _mesa_hash_table_create(mem_ctx, key_u64_hash,
576                                          key_u64_equals);
577   }
578
579   if (ht->table)
580      _mesa_hash_table_set_deleted_key(ht->table, uint_key(DELETED_KEY_VALUE));
581
582   return ht;
583}
584
585void
586_mesa_hash_table_u64_destroy(struct hash_table_u64 *ht,
587                             void (*delete_function)(struct hash_entry *entry))
588{
589   if (!ht)
590      return;
591
592   if (ht->deleted_key_data) {
593      if (delete_function) {
594         struct hash_table *table = ht->table;
595         struct hash_entry deleted_entry;
596
597         /* Create a fake entry for the delete function. */
598         deleted_entry.hash = table->key_hash_function(table->deleted_key);
599         deleted_entry.key = table->deleted_key;
600         deleted_entry.data = ht->deleted_key_data;
601
602         delete_function(&deleted_entry);
603      }
604      ht->deleted_key_data = NULL;
605   }
606
607   _mesa_hash_table_destroy(ht->table, delete_function);
608   free(ht);
609}
610
611void
612_mesa_hash_table_u64_insert(struct hash_table_u64 *ht, uint64_t key,
613                            void *data)
614{
615   if (key == DELETED_KEY_VALUE) {
616      ht->deleted_key_data = data;
617      return;
618   }
619
620   if (sizeof(void *) == 8) {
621      _mesa_hash_table_insert(ht->table, (void *)(uintptr_t)key, data);
622   } else {
623      struct hash_key_u64 *_key = CALLOC_STRUCT(hash_key_u64);
624
625      if (!_key)
626         return;
627      _key->value = key;
628
629      _mesa_hash_table_insert(ht->table, _key, data);
630   }
631}
632
633static struct hash_entry *
634hash_table_u64_search(struct hash_table_u64 *ht, uint64_t key)
635{
636   if (sizeof(void *) == 8) {
637      return _mesa_hash_table_search(ht->table, (void *)(uintptr_t)key);
638   } else {
639      struct hash_key_u64 _key = { .value = key };
640      return _mesa_hash_table_search(ht->table, &_key);
641   }
642}
643
644void *
645_mesa_hash_table_u64_search(struct hash_table_u64 *ht, uint64_t key)
646{
647   struct hash_entry *entry;
648
649   if (key == DELETED_KEY_VALUE)
650      return ht->deleted_key_data;
651
652   entry = hash_table_u64_search(ht, key);
653   if (!entry)
654      return NULL;
655
656   return entry->data;
657}
658
659void
660_mesa_hash_table_u64_remove(struct hash_table_u64 *ht, uint64_t key)
661{
662   struct hash_entry *entry;
663
664   if (key == DELETED_KEY_VALUE) {
665      ht->deleted_key_data = NULL;
666      return;
667   }
668
669   entry = hash_table_u64_search(ht, key);
670   if (!entry)
671      return;
672
673   if (sizeof(void *) == 8) {
674      _mesa_hash_table_remove(ht->table, entry);
675   } else {
676      struct hash_key *_key = (struct hash_key *)entry->key;
677
678      _mesa_hash_table_remove(ht->table, entry);
679      free(_key);
680   }
681}
682