hash_table.c revision 848b8605
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
46#include "hash_table.h"
47#include "ralloc.h"
48#include "macros.h"
49
50static const uint32_t deleted_key_value;
51
52/**
53 * From Knuth -- a good choice for hash/rehash values is p, p-2 where
54 * p and p-2 are both prime.  These tables are sized to have an extra 10%
55 * free to avoid exponential performance degradation as the hash table fills
56 */
57static const struct {
58   uint32_t max_entries, size, rehash;
59} hash_sizes[] = {
60   { 2,			5,		3	  },
61   { 4,			7,		5	  },
62   { 8,			13,		11	  },
63   { 16,		19,		17	  },
64   { 32,		43,		41        },
65   { 64,		73,		71        },
66   { 128,		151,		149       },
67   { 256,		283,		281       },
68   { 512,		571,		569       },
69   { 1024,		1153,		1151      },
70   { 2048,		2269,		2267      },
71   { 4096,		4519,		4517      },
72   { 8192,		9013,		9011      },
73   { 16384,		18043,		18041     },
74   { 32768,		36109,		36107     },
75   { 65536,		72091,		72089     },
76   { 131072,		144409,		144407    },
77   { 262144,		288361,		288359    },
78   { 524288,		576883,		576881    },
79   { 1048576,		1153459,	1153457   },
80   { 2097152,		2307163,	2307161   },
81   { 4194304,		4613893,	4613891   },
82   { 8388608,		9227641,	9227639   },
83   { 16777216,		18455029,	18455027  },
84   { 33554432,		36911011,	36911009  },
85   { 67108864,		73819861,	73819859  },
86   { 134217728,		147639589,	147639587 },
87   { 268435456,		295279081,	295279079 },
88   { 536870912,		590559793,	590559791 },
89   { 1073741824,	1181116273,	1181116271},
90   { 2147483648ul,	2362232233ul,	2362232231ul}
91};
92
93static int
94entry_is_free(const struct hash_entry *entry)
95{
96   return entry->key == NULL;
97}
98
99static int
100entry_is_deleted(const struct hash_table *ht, struct hash_entry *entry)
101{
102   return entry->key == ht->deleted_key;
103}
104
105static int
106entry_is_present(const struct hash_table *ht, struct hash_entry *entry)
107{
108   return entry->key != NULL && entry->key != ht->deleted_key;
109}
110
111struct hash_table *
112_mesa_hash_table_create(void *mem_ctx,
113                        bool (*key_equals_function)(const void *a,
114                                                    const void *b))
115{
116   struct hash_table *ht;
117
118   ht = ralloc(mem_ctx, struct hash_table);
119   if (ht == NULL)
120      return NULL;
121
122   ht->size_index = 0;
123   ht->size = hash_sizes[ht->size_index].size;
124   ht->rehash = hash_sizes[ht->size_index].rehash;
125   ht->max_entries = hash_sizes[ht->size_index].max_entries;
126   ht->key_equals_function = key_equals_function;
127   ht->table = rzalloc_array(ht, struct hash_entry, ht->size);
128   ht->entries = 0;
129   ht->deleted_entries = 0;
130   ht->deleted_key = &deleted_key_value;
131
132   if (ht->table == NULL) {
133      ralloc_free(ht);
134      return NULL;
135   }
136
137   return ht;
138}
139
140/**
141 * Frees the given hash table.
142 *
143 * If delete_function is passed, it gets called on each entry present before
144 * freeing.
145 */
146void
147_mesa_hash_table_destroy(struct hash_table *ht,
148                         void (*delete_function)(struct hash_entry *entry))
149{
150   if (!ht)
151      return;
152
153   if (delete_function) {
154      struct hash_entry *entry;
155
156      hash_table_foreach(ht, entry) {
157         delete_function(entry);
158      }
159   }
160   ralloc_free(ht);
161}
162
163/** Sets the value of the key pointer used for deleted entries in the table.
164 *
165 * The assumption is that usually keys are actual pointers, so we use a
166 * default value of a pointer to an arbitrary piece of storage in the library.
167 * But in some cases a consumer wants to store some other sort of value in the
168 * table, like a uint32_t, in which case that pointer may conflict with one of
169 * their valid keys.  This lets that user select a safe value.
170 *
171 * This must be called before any keys are actually deleted from the table.
172 */
173void
174_mesa_hash_table_set_deleted_key(struct hash_table *ht, const void *deleted_key)
175{
176   ht->deleted_key = deleted_key;
177}
178
179/**
180 * Finds a hash table entry with the given key and hash of that key.
181 *
182 * Returns NULL if no entry is found.  Note that the data pointer may be
183 * modified by the user.
184 */
185struct hash_entry *
186_mesa_hash_table_search(struct hash_table *ht, uint32_t hash,
187                        const void *key)
188{
189   uint32_t start_hash_address = hash % ht->size;
190   uint32_t hash_address = start_hash_address;
191
192   do {
193      uint32_t double_hash;
194
195      struct hash_entry *entry = ht->table + hash_address;
196
197      if (entry_is_free(entry)) {
198         return NULL;
199      } else if (entry_is_present(ht, entry) && entry->hash == hash) {
200         if (ht->key_equals_function(key, entry->key)) {
201            return entry;
202         }
203      }
204
205      double_hash = 1 + hash % ht->rehash;
206
207      hash_address = (hash_address + double_hash) % ht->size;
208   } while (hash_address != start_hash_address);
209
210   return NULL;
211}
212
213static void
214_mesa_hash_table_rehash(struct hash_table *ht, int new_size_index)
215{
216   struct hash_table old_ht;
217   struct hash_entry *table, *entry;
218
219   if (new_size_index >= ARRAY_SIZE(hash_sizes))
220      return;
221
222   table = rzalloc_array(ht, struct hash_entry,
223                         hash_sizes[new_size_index].size);
224   if (table == NULL)
225      return;
226
227   old_ht = *ht;
228
229   ht->table = table;
230   ht->size_index = new_size_index;
231   ht->size = hash_sizes[ht->size_index].size;
232   ht->rehash = hash_sizes[ht->size_index].rehash;
233   ht->max_entries = hash_sizes[ht->size_index].max_entries;
234   ht->entries = 0;
235   ht->deleted_entries = 0;
236
237   hash_table_foreach(&old_ht, entry) {
238      _mesa_hash_table_insert(ht, entry->hash,
239                              entry->key, entry->data);
240   }
241
242   ralloc_free(old_ht.table);
243}
244
245/**
246 * Inserts the key with the given hash into the table.
247 *
248 * Note that insertion may rearrange the table on a resize or rehash,
249 * so previously found hash_entries are no longer valid after this function.
250 */
251struct hash_entry *
252_mesa_hash_table_insert(struct hash_table *ht, uint32_t hash,
253                        const void *key, void *data)
254{
255   uint32_t start_hash_address, hash_address;
256
257   if (ht->entries >= ht->max_entries) {
258      _mesa_hash_table_rehash(ht, ht->size_index + 1);
259   } else if (ht->deleted_entries + ht->entries >= ht->max_entries) {
260      _mesa_hash_table_rehash(ht, ht->size_index);
261   }
262
263   start_hash_address = hash % ht->size;
264   hash_address = start_hash_address;
265   do {
266      struct hash_entry *entry = ht->table + hash_address;
267      uint32_t double_hash;
268
269      if (!entry_is_present(ht, entry)) {
270         if (entry_is_deleted(ht, entry))
271            ht->deleted_entries--;
272         entry->hash = hash;
273         entry->key = key;
274         entry->data = data;
275         ht->entries++;
276         return entry;
277      }
278
279      /* Implement replacement when another insert happens
280       * with a matching key.  This is a relatively common
281       * feature of hash tables, with the alternative
282       * generally being "insert the new value as well, and
283       * return it first when the key is searched for".
284       *
285       * Note that the hash table doesn't have a delete
286       * callback.  If freeing of old data pointers is
287       * required to avoid memory leaks, perform a search
288       * before inserting.
289       */
290      if (entry->hash == hash &&
291          ht->key_equals_function(key, entry->key)) {
292         entry->key = key;
293         entry->data = data;
294         return entry;
295      }
296
297
298      double_hash = 1 + hash % ht->rehash;
299
300      hash_address = (hash_address + double_hash) % ht->size;
301   } while (hash_address != start_hash_address);
302
303   /* We could hit here if a required resize failed. An unchecked-malloc
304    * application could ignore this result.
305    */
306   return NULL;
307}
308
309/**
310 * This function deletes the given hash table entry.
311 *
312 * Note that deletion doesn't otherwise modify the table, so an iteration over
313 * the table deleting entries is safe.
314 */
315void
316_mesa_hash_table_remove(struct hash_table *ht,
317                        struct hash_entry *entry)
318{
319   if (!entry)
320      return;
321
322   entry->key = ht->deleted_key;
323   ht->entries--;
324   ht->deleted_entries++;
325}
326
327/**
328 * This function is an iterator over the hash table.
329 *
330 * Pass in NULL for the first entry, as in the start of a for loop.  Note that
331 * an iteration over the table is O(table_size) not O(entries).
332 */
333struct hash_entry *
334_mesa_hash_table_next_entry(struct hash_table *ht,
335                            struct hash_entry *entry)
336{
337   if (entry == NULL)
338      entry = ht->table;
339   else
340      entry = entry + 1;
341
342   for (; entry != ht->table + ht->size; entry++) {
343      if (entry_is_present(ht, entry)) {
344         return entry;
345      }
346   }
347
348   return NULL;
349}
350
351/**
352 * Returns a random entry from the hash table.
353 *
354 * This may be useful in implementing random replacement (as opposed
355 * to just removing everything) in caches based on this hash table
356 * implementation.  @predicate may be used to filter entries, or may
357 * be set to NULL for no filtering.
358 */
359struct hash_entry *
360_mesa_hash_table_random_entry(struct hash_table *ht,
361                              bool (*predicate)(struct hash_entry *entry))
362{
363   struct hash_entry *entry;
364   uint32_t i = rand() % ht->size;
365
366   if (ht->entries == 0)
367      return NULL;
368
369   for (entry = ht->table + i; entry != ht->table + ht->size; entry++) {
370      if (entry_is_present(ht, entry) &&
371          (!predicate || predicate(entry))) {
372         return entry;
373      }
374   }
375
376   for (entry = ht->table; entry != ht->table + i; entry++) {
377      if (entry_is_present(ht, entry) &&
378          (!predicate || predicate(entry))) {
379         return entry;
380      }
381   }
382
383   return NULL;
384}
385
386
387/**
388 * Quick FNV-1 hash implementation based on:
389 * http://www.isthe.com/chongo/tech/comp/fnv/
390 *
391 * FNV-1 is not be the best hash out there -- Jenkins's lookup3 is supposed to
392 * be quite good, and it probably beats FNV.  But FNV has the advantage that
393 * it involves almost no code.  For an improvement on both, see Paul
394 * Hsieh's http://www.azillionmonkeys.com/qed/hash.html
395 */
396uint32_t
397_mesa_hash_data(const void *data, size_t size)
398{
399   uint32_t hash = 2166136261ul;
400   const uint8_t *bytes = data;
401
402   while (size-- != 0) {
403      hash ^= *bytes;
404      hash = hash * 0x01000193;
405      bytes++;
406   }
407
408   return hash;
409}
410
411/** FNV-1 string hash implementation */
412uint32_t
413_mesa_hash_string(const char *key)
414{
415   uint32_t hash = 2166136261ul;
416
417   while (*key != 0) {
418      hash ^= *key;
419      hash = hash * 0x01000193;
420      key++;
421   }
422
423   return hash;
424}
425
426/**
427 * String compare function for use as the comparison callback in
428 * _mesa_hash_table_create().
429 */
430bool
431_mesa_key_string_equal(const void *a, const void *b)
432{
433   return strcmp(a, b) == 0;
434}
435
436bool
437_mesa_key_pointer_equal(const void *a, const void *b)
438{
439   return a == b;
440}
441