2 * Copyright (C) 1995-2008 University of Karlsruhe. All right reserved.
4 * This file is part of libFirm.
6 * This file may be distributed and/or modified under the terms of the
7 * GNU General Public License version 2 as published by the Free Software
8 * Foundation and appearing in the file LICENSE.GPL included in the
9 * packaging of this file.
11 * Licensees holding valid libFirm Professional Edition licenses may use
12 * this file in accordance with the libFirm Commercial License.
13 * Agreement provided with the Software.
15 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16 * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * @brief Generic hashset implementation
23 * @author Matthias Braun, inspiration from densehash from google sparsehash
28 * You have to specialize this file by defining:
31 * <li><b>HashSet</b> The name of the hashset type</li>
32 * <li><b>HashSetIterator</b> The name of the hashset iterator type</li>
33 * <li><b>ValueType</b> The type of the stored data values</li>
34 * <li><b>NullValue</b> A special value representing no values</li>
35 * <li><b>DeletedValue</b> A special value representing deleted entries</li>
36 * <li><b>Hash(hashset,key)</b> calculates the hash value for a given key</li>
39 * Note that by default it is assumed that the data values themselfes are used
40 * as keys. However you can change that with additional defines:
43 * <li><b>KeyType</b> The type of the keys identifying data values.
44 * Defining this implies, that a data value contains
45 * more than just the key.</li>
46 * <li><b>GetKey(value)</b> Extracts the key from a data value</li>
47 * <li><b>KeysEqual(hashset,key1,key2)</b> Tests wether 2 keys are equal</li>
48 * <li><b>DO_REHASH</b> Instead of storing the hash-values, recalculate
49 * them on demand from the datavalues. (useful if
50 * calculating the hash-values takes less time than
51 * a memory access)</li>
54 * You can further fine tune your hashset by defining the following:
57 * <li><b>JUMP(num_probes)</b> The probing method</li>
58 * <li><b>Alloc(count)</b> Allocates count hashset entries (NOT bytes)</li>
59 * <li><b>Free(ptr)</b> Frees a block of memory allocated by Alloc</li>
60 * <li><b>SetRangeEmpty(ptr,count)</b> Efficiently sets a range of elements to
62 * <li><b>ADDITIONAL_DATA<b> Additional fields appended to the hashset struct</li>
71 #include "bitfiddle.h"
74 /* quadratic probing */
76 #define JUMP(num_probes) (num_probes)
81 #define Hash(self,key) ((unsigned)(((char *)key) - (char *)0))
85 #define HashSetEntry ValueType
86 #define EntrySetHash(entry,new_hash) (void)0
87 #define EntryGetHash(self,entry) Hash(self, GetKey(entry))
88 #define EntryGetValue(entry) (entry)
89 #else /* ! DO_REHASH */
90 #define EntryGetHash(self,entry) (entry).hash
91 #define EntrySetHash(entry,new_hash) (entry).hash = (new_hash)
92 #define EntryGetValue(entry) (entry).data
93 #endif /* DO_REHASH */
97 #define Alloc(size) XMALLOCN(HashSetEntry, (size))
98 #define Free(ptr) free(ptr)
102 #define InsertReturnValue int
103 #define GetInsertReturnValue(entry,found) (found)
104 #define NullReturnValue 0
105 #else /* ! ID_HASH */
107 #define InsertReturnValue ValueType
108 #define GetInsertReturnValue(entry,found) EntryGetValue(entry)
109 #define NullReturnValue NullValue
111 #define InsertReturnValue ValueType*
112 #define GetInsertReturnValue(entry,found) & EntryGetValue(entry)
113 #define NullReturnValue & NullValue
118 #define KeyType ValueType
119 #define GetKey(value) (value)
120 #define InitData(self,value,key) (value) = (key)
124 #define ConstKeyType const KeyType
125 #endif /* ConstKeyType */
127 #ifndef EntrySetEmpty
128 #define EntrySetEmpty(entry) EntryGetValue(entry) = NullValue
129 #endif /* EntrySetEmpty */
130 #ifndef EntrySetDeleted
131 #define EntrySetDeleted(entry) EntryGetValue(entry) = DeletedValue
132 #endif /* EntrySetDeleted */
134 #define EntryIsEmpty(entry) (EntryGetValue(entry) == NullValue)
135 #endif /* EntryIsEmpty */
136 #ifndef EntryIsDeleted
137 #define EntryIsDeleted(entry) (EntryGetValue(entry) == DeletedValue)
138 #endif /* EntryIsDeleted */
139 #ifndef SetRangeEmpty
140 #define SetRangeEmpty(ptr,size) \
143 size_t _size = (size); \
144 HashSetEntry *entries = (ptr); \
145 for (_i = 0; _i < _size; ++_i) { \
146 HashSetEntry *entry = & entries[_i]; \
147 EntrySetEmpty(*entry); \
150 #endif /* SetRangeEmpty */
152 #ifndef HT_OCCUPANCY_FLT
153 /** how full before we double size */
154 #define HT_OCCUPANCY_FLT(x) ((x)/2)
155 #endif /* HT_OCCUPANCY_FLT */
156 #ifndef HT_1_DIV_OCCUPANCY_FLT
157 #define HT_1_DIV_OCCUPANCY_FLT 2
161 /** how empty before we half size */
162 #define HT_EMPTY_FLT(x) ((x)/5)
163 #endif /* HT_EMPTY_FLT */
165 #ifndef HT_MIN_BUCKETS
166 /** default smallest bucket size */
167 #define HT_MIN_BUCKETS 32
168 #endif /* HT_MIN_BUCKETS */
170 #define ILLEGAL_POS ((size_t)-1)
172 /* check that all needed functions are defined */
174 #error You have to redefine hashset_init
176 #ifndef hashset_init_size
177 #error You have to redefine hashset_init_size
179 #ifndef hashset_destroy
180 #error You have to redefine hashset_destroy
182 #ifndef hashset_insert
183 #error You have to redefine hashset_insert
185 #ifndef hashset_remove
186 #error You have to redefine hashset_remove
189 #error You have to redefine hashset_find
192 #error You have to redefine hashset_size
196 #ifndef hashset_iterator_init
197 #error You have to redefine hashset_iterator_init
199 #ifndef hashset_iterator_next
200 #error You have to redefine hashset_iterator_next
202 #ifndef hashset_remove_iterator
203 #error You have to redefine hashset_remove_iterator
208 * Returns the number of elements in the hashset
210 size_t hashset_size(const HashSet *self)
212 return self->num_elements - self->num_deleted;
216 * Inserts an element into a hashset without growing the set (you have to make
217 * sure there's enough room for that.
218 * @note also see comments for hashset_insert()
221 static inline InsertReturnValue insert_nogrow(HashSet *self, KeyType key)
223 size_t num_probes = 0;
224 size_t num_buckets = self->num_buckets;
225 size_t hashmask = num_buckets - 1;
226 unsigned hash = Hash(self, key);
227 size_t bucknum = hash & hashmask;
228 size_t insert_pos = ILLEGAL_POS;
230 assert((num_buckets & (num_buckets - 1)) == 0);
233 HashSetEntry *entry = & self->entries[bucknum];
235 if (EntryIsEmpty(*entry)) {
237 HashSetEntry *nentry;
239 if (insert_pos != ILLEGAL_POS) {
245 nentry = &self->entries[p];
246 InitData(self, EntryGetValue(*nentry), key);
247 EntrySetHash(*nentry, hash);
248 self->num_elements++;
249 return GetInsertReturnValue(*nentry, 0);
251 if (EntryIsDeleted(*entry)) {
252 if (insert_pos == ILLEGAL_POS)
253 insert_pos = bucknum;
254 } else if (EntryGetHash(self, *entry) == hash) {
255 if (KeysEqual(self, GetKey(EntryGetValue(*entry)), key)) {
256 // Value already in the set, return it
257 return GetInsertReturnValue(*entry, 1);
262 bucknum = (bucknum + JUMP(num_probes)) & hashmask;
263 assert(num_probes < num_buckets);
268 * calculate shrink and enlarge limits
271 static inline void reset_thresholds(HashSet *self)
273 self->enlarge_threshold = (size_t) HT_OCCUPANCY_FLT(self->num_buckets);
274 self->shrink_threshold = (size_t) HT_EMPTY_FLT(self->num_buckets);
275 self->consider_shrink = 0;
278 #ifndef HAVE_OWN_RESIZE
280 * Inserts an element into a hashset under the assumption that the hashset
281 * contains no deleted entries and the element doesn't exist in the hashset yet.
284 static void insert_new(HashSet *self, unsigned hash, ValueType value)
286 size_t num_probes = 0;
287 size_t num_buckets = self->num_buckets;
288 size_t hashmask = num_buckets - 1;
289 size_t bucknum = hash & hashmask;
290 size_t insert_pos = ILLEGAL_POS;
292 //assert(value != NullValue);
295 HashSetEntry *entry = & self->entries[bucknum];
297 if (EntryIsEmpty(*entry)) {
299 HashSetEntry *nentry;
301 if (insert_pos != ILLEGAL_POS) {
306 nentry = &self->entries[p];
308 EntryGetValue(*nentry) = value;
309 EntrySetHash(*nentry, hash);
310 self->num_elements++;
313 assert(!EntryIsDeleted(*entry));
316 bucknum = (bucknum + JUMP(num_probes)) & hashmask;
317 assert(num_probes < num_buckets);
325 static inline void resize(HashSet *self, size_t new_size)
327 size_t num_buckets = self->num_buckets;
329 HashSetEntry *old_entries = self->entries;
330 HashSetEntry *new_entries;
332 /* allocate a new array with double size */
333 new_entries = Alloc(new_size);
334 SetRangeEmpty(new_entries, new_size);
336 /* use the new array */
337 self->entries = new_entries;
338 self->num_buckets = new_size;
339 self->num_elements = 0;
340 self->num_deleted = 0;
342 self->entries_version++;
344 reset_thresholds(self);
346 /* reinsert all elements */
347 for (i = 0; i < num_buckets; ++i) {
348 HashSetEntry *entry = & old_entries[i];
349 if (EntryIsEmpty(*entry) || EntryIsDeleted(*entry))
352 insert_new(self, EntryGetHash(self, *entry), EntryGetValue(*entry));
355 /* now we can free the old array */
360 /* resize must be defined outside */
361 static inline void resize(HashSet *self, size_t new_size);
366 * grow the hashset if adding 1 more elements would make it too crowded
369 static inline void maybe_grow(HashSet *self)
373 if (LIKELY(self->num_elements + 1 <= self->enlarge_threshold))
376 /* double table size */
377 resize_to = self->num_buckets * 2;
378 resize(self, resize_to);
382 * shrink the hashset if it is only sparsely filled
385 static inline void maybe_shrink(HashSet *self)
390 if (!self->consider_shrink)
393 self->consider_shrink = 0;
394 size = hashset_size(self);
395 if (size <= HT_MIN_BUCKETS)
398 if (LIKELY(size > self->shrink_threshold))
401 resize_to = ceil_po2(size);
406 resize(self, resize_to);
410 * Insert an element into the hashset. If no element with the given key exists yet,
411 * then a new one is created and initialized with the InitData function.
412 * Otherwise the existing element is returned (for hashs where key is equal to
413 * value, nothing is returned.)
415 * @param self the hashset
416 * @param key the key that identifies the data
417 * @returns the existing or newly created data element (or nothing in case of hashs where keys are the while value)
419 InsertReturnValue hashset_insert(HashSet *self, KeyType key)
422 self->entries_version++;
427 return insert_nogrow(self, key);
431 * Searches for an element with key @p key.
433 * @param self the hashset
434 * @param key the key to search for
435 * @returns the found value or NullValue if nothing was found
437 InsertReturnValue hashset_find(const HashSet *self, ConstKeyType key)
439 size_t num_probes = 0;
440 size_t num_buckets = self->num_buckets;
441 size_t hashmask = num_buckets - 1;
442 unsigned hash = Hash(self, key);
443 size_t bucknum = hash & hashmask;
446 HashSetEntry *entry = & self->entries[bucknum];
448 if (EntryIsEmpty(*entry)) {
449 return NullReturnValue;
451 if (EntryIsDeleted(*entry)) {
453 } else if (EntryGetHash(self, *entry) == hash) {
454 if (KeysEqual(self, GetKey(EntryGetValue(*entry)), key)) {
456 return GetInsertReturnValue(*entry, 1);
461 bucknum = (bucknum + JUMP(num_probes)) & hashmask;
462 assert(num_probes < num_buckets);
467 * Removes an element from a hashset. Does nothing if the set doesn't contain
470 * @param self the hashset
471 * @param key key that identifies the data to remove
473 void hashset_remove(HashSet *self, ConstKeyType key)
475 size_t num_probes = 0;
476 size_t num_buckets = self->num_buckets;
477 size_t hashmask = num_buckets - 1;
478 unsigned hash = Hash(self, key);
479 size_t bucknum = hash & hashmask;
482 self->entries_version++;
486 HashSetEntry *entry = & self->entries[bucknum];
488 if (EntryIsEmpty(*entry)) {
491 if (EntryIsDeleted(*entry)) {
493 } else if (EntryGetHash(self, *entry) == hash) {
494 if (KeysEqual(self, GetKey(EntryGetValue(*entry)), key)) {
495 EntrySetDeleted(*entry);
497 self->consider_shrink = 1;
503 bucknum = (bucknum + JUMP(num_probes)) & hashmask;
504 assert(num_probes < num_buckets);
509 * Initializes hashset with a specific size
512 static inline void init_size(HashSet *self, size_t initial_size)
514 if (initial_size < 4)
517 self->entries = Alloc(initial_size);
518 SetRangeEmpty(self->entries, initial_size);
519 self->num_buckets = initial_size;
520 self->consider_shrink = 0;
521 self->num_elements = 0;
522 self->num_deleted = 0;
524 self->entries_version = 0;
526 #ifdef ADDITIONAL_INIT
530 reset_thresholds(self);
534 * Initializes a hashset with the default size. The memory for the set has to
537 void hashset_init(HashSet *self)
539 init_size(self, HT_MIN_BUCKETS);
543 * Destroys a hashset, freeing all used memory (except the memory for the
544 * HashSet struct itself).
546 void hashset_destroy(HashSet *self)
548 #ifdef ADDITIONAL_TERM
553 self->entries = NULL;
558 * Initializes a hashset expecting expected_element size.
560 void hashset_init_size(HashSet *self, size_t expected_elements)
565 if (expected_elements >= UINT_MAX/2) {
569 needed_size = expected_elements * HT_1_DIV_OCCUPANCY_FLT;
570 po2size = ceil_po2(needed_size);
571 init_size(self, po2size);
576 * Initializes a hashset iterator. The memory for the allocator has to be
578 * @note it is not allowed to remove or insert elements while iterating
580 void hashset_iterator_init(HashSetIterator *self, const HashSet *hashset)
582 self->current_bucket = hashset->entries - 1;
583 self->end = hashset->entries + hashset->num_buckets;
586 self->entries_version = hashset->entries_version;
591 * Returns the next value in the iterator or NULL if no value is left
593 * @note it is not allowed to remove or insert elements while iterating
595 ValueType hashset_iterator_next(HashSetIterator *self)
597 HashSetEntry *current_bucket = self->current_bucket;
598 HashSetEntry *end = self->end;
600 /* using hashset_insert or hashset_remove is not allowed while iterating */
601 assert(self->entries_version == self->set->entries_version);
605 if (current_bucket >= end)
607 } while (EntryIsEmpty(*current_bucket) || EntryIsDeleted(*current_bucket));
609 self->current_bucket = current_bucket;
610 return EntryGetValue(*current_bucket);
614 * Removes the element the iterator points to. Removing an element a second time
617 void hashset_remove_iterator(HashSet *self, const HashSetIterator *iter)
619 HashSetEntry *entry = iter->current_bucket;
621 /* iterator_next needs to have been called at least once */
622 assert(entry >= self->entries);
623 /* needs to be on a valid element */
624 assert(entry < self->entries + self->num_buckets);
626 if (EntryIsDeleted(*entry))
629 EntrySetDeleted(*entry);
631 self->consider_shrink = 1;
633 #endif /* NO_ITERATOR */