2 * Copyright (C) 1995-2009 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 themselves 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. (usefull 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) (HashSetEntry*) xmalloc((size) * sizeof(HashSetEntry))
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
194 #ifndef hashset_iterator_init
195 #error You have to redefine hashset_iterator_init
197 #ifndef hashset_iterator_next
198 #error You have to redefine hashset_iterator_next
200 #ifndef hashset_remove_iterator
201 #error You have to redefine hashset_remove_iterator
204 /* prototypes to avoid warnings */
205 void hashset_init(HashSet *self);
206 void hashset_destroy(HashSet *self);
207 size_t hashset_size(const HashSet *self);
208 InsertReturnValue hashset_insert(HashSet *self, KeyType key);
209 InsertReturnValue hashset_find(const HashSet *self, ConstKeyType key);
210 void hashset_remove(HashSet *self, ConstKeyType key);
211 void hashset_init_size(HashSet *self, size_t expected_elements);
212 void hashset_iterator_init(HashSetIterator *self, const HashSet *hashset);
213 ValueType hashset_iterator_next(HashSetIterator *self);
214 void hashset_remove_iterator(HashSet *self, const HashSetIterator *iter);
217 * Returns the number of elements in the hashset
219 size_t hashset_size(const HashSet *self)
221 return self->num_elements - self->num_deleted;
225 * Inserts an element into a hashset without growing the set (you have to make
226 * sure there's enough room for that.
227 * @note also see comments for hashset_insert()
231 InsertReturnValue insert_nogrow(HashSet *self, KeyType key)
233 size_t num_probes = 0;
234 size_t num_buckets = self->num_buckets;
235 size_t hashmask = num_buckets - 1;
236 unsigned hash = Hash(self, key);
237 size_t bucknum = hash & hashmask;
238 size_t insert_pos = ILLEGAL_POS;
240 assert((num_buckets & (num_buckets - 1)) == 0);
243 HashSetEntry *entry = & self->entries[bucknum];
245 if(EntryIsEmpty(*entry)) {
247 HashSetEntry *nentry;
249 if(insert_pos != ILLEGAL_POS) {
255 nentry = &self->entries[p];
256 InitData(self, EntryGetValue(*nentry), key);
257 EntrySetHash(*nentry, hash);
258 self->num_elements++;
259 return GetInsertReturnValue(*nentry, 0);
261 if(EntryIsDeleted(*entry)) {
262 if(insert_pos == ILLEGAL_POS)
263 insert_pos = bucknum;
264 } else if(EntryGetHash(self, *entry) == hash) {
265 if(KeysEqual(self, GetKey(EntryGetValue(*entry)), key)) {
266 // Value already in the set, return it
267 return GetInsertReturnValue(*entry, 1);
272 bucknum = (bucknum + JUMP(num_probes)) & hashmask;
273 assert(num_probes < num_buckets);
278 * Inserts an element into a hashset under the assumption that the hashset
279 * contains no deleted entries and the element doesn't exist in the hashset yet.
283 void insert_new(HashSet *self, unsigned hash, ValueType value)
285 size_t num_probes = 0;
286 size_t num_buckets = self->num_buckets;
287 size_t hashmask = num_buckets - 1;
288 size_t bucknum = hash & hashmask;
289 size_t insert_pos = ILLEGAL_POS;
291 //assert(value != NullValue);
294 HashSetEntry *entry = & self->entries[bucknum];
296 if(EntryIsEmpty(*entry)) {
298 HashSetEntry *nentry;
300 if(insert_pos != ILLEGAL_POS) {
305 nentry = &self->entries[p];
307 EntryGetValue(*nentry) = value;
308 EntrySetHash(*nentry, hash);
309 self->num_elements++;
312 assert(!EntryIsDeleted(*entry));
315 bucknum = (bucknum + JUMP(num_probes)) & hashmask;
316 assert(num_probes < num_buckets);
321 * calculate shrink and enlarge limits
325 void reset_thresholds(HashSet *self)
327 self->enlarge_threshold = (size_t) HT_OCCUPANCY_FLT(self->num_buckets);
328 self->shrink_threshold = (size_t) HT_EMPTY_FLT(self->num_buckets);
329 self->consider_shrink = 0;
337 void resize(HashSet *self, size_t new_size)
339 size_t num_buckets = self->num_buckets;
341 HashSetEntry *old_entries = self->entries;
342 HashSetEntry *new_entries;
344 /* allocate a new array with double size */
345 new_entries = Alloc(new_size);
346 SetRangeEmpty(new_entries, new_size);
348 /* use the new array */
349 self->entries = new_entries;
350 self->num_buckets = new_size;
351 self->num_elements = 0;
352 self->num_deleted = 0;
354 self->entries_version++;
356 reset_thresholds(self);
358 /* reinsert all elements */
359 for(i = 0; i < num_buckets; ++i) {
360 HashSetEntry *entry = & old_entries[i];
361 if(EntryIsEmpty(*entry) || EntryIsDeleted(*entry))
364 insert_new(self, EntryGetHash(self, *entry), EntryGetValue(*entry));
367 /* now we can free the old array */
372 * grow the hashset if adding 1 more elements would make it too crowded
376 void maybe_grow(HashSet *self)
380 if(LIKELY(self->num_elements + 1 <= self->enlarge_threshold))
383 /* double table size */
384 resize_to = self->num_buckets * 2;
385 resize(self, resize_to);
389 * shrink the hashset if it is only sparsely filled
393 void maybe_shrink(HashSet *self)
398 if(!self->consider_shrink)
401 self->consider_shrink = 0;
402 size = hashset_size(self);
403 if(size <= HT_MIN_BUCKETS)
406 if(LIKELY(size > self->shrink_threshold))
409 resize_to = ceil_po2(size);
414 resize(self, resize_to);
418 * Insert an element into the hashset. If no element with key key exists yet,
419 * then a new one is created and initialized with the InitData function.
420 * Otherwise the exisiting element is returned (for hashs where key is equal to
421 * value, nothing is returned.)
423 * @param self the hashset
424 * @param key the key that identifies the data
425 * @returns the existing or newly created data element (or nothing in case of hashs where keys are the while value)
427 InsertReturnValue hashset_insert(HashSet *self, KeyType key)
430 self->entries_version++;
435 return insert_nogrow(self, key);
439 * Searchs for an element with key @p key.
441 * @param self the hashset
442 * @param key the key to search for
443 * @returns the found value or NullValue if nothing was found
445 InsertReturnValue hashset_find(const HashSet *self, ConstKeyType key)
447 size_t num_probes = 0;
448 size_t num_buckets = self->num_buckets;
449 size_t hashmask = num_buckets - 1;
450 unsigned hash = Hash(self, key);
451 size_t bucknum = hash & hashmask;
454 HashSetEntry *entry = & self->entries[bucknum];
456 if(EntryIsEmpty(*entry)) {
457 return NullReturnValue;
459 if(EntryIsDeleted(*entry)) {
461 } else if(EntryGetHash(self, *entry) == hash) {
462 if(KeysEqual(self, GetKey(EntryGetValue(*entry)), key)) {
464 return GetInsertReturnValue(*entry, 1);
469 bucknum = (bucknum + JUMP(num_probes)) & hashmask;
470 assert(num_probes < num_buckets);
475 * Removes an element from a hashset. Does nothing if the set doesn't contain
478 * @param self the hashset
479 * @param key key that identifies the data to remove
481 void hashset_remove(HashSet *self, ConstKeyType key)
483 size_t num_probes = 0;
484 size_t num_buckets = self->num_buckets;
485 size_t hashmask = num_buckets - 1;
486 unsigned hash = Hash(self, key);
487 size_t bucknum = hash & hashmask;
490 self->entries_version++;
494 HashSetEntry *entry = & self->entries[bucknum];
496 if(EntryIsEmpty(*entry)) {
499 if(EntryIsDeleted(*entry)) {
501 } else if(EntryGetHash(self, *entry) == hash) {
502 if(KeysEqual(self, GetKey(EntryGetValue(*entry)), key)) {
503 EntrySetDeleted(*entry);
505 self->consider_shrink = 1;
511 bucknum = (bucknum + JUMP(num_probes)) & hashmask;
512 assert(num_probes < num_buckets);
517 * Initializes hashset with a specific size
521 void init_size(HashSet *self, size_t initial_size)
526 self->entries = Alloc(initial_size);
527 SetRangeEmpty(self->entries, initial_size);
528 self->num_buckets = initial_size;
529 self->consider_shrink = 0;
530 self->num_elements = 0;
531 self->num_deleted = 0;
533 self->entries_version = 0;
536 reset_thresholds(self);
540 * Initialializes a hashset with the default size. The memory for the set has to
543 void hashset_init(HashSet *self)
545 init_size(self, HT_MIN_BUCKETS);
549 * Destroys a hashset, freeing all used memory (except the memory for the
550 * HashSet struct itself).
552 void hashset_destroy(HashSet *self)
556 self->entries = NULL;
561 * Initializes a hashset expecting expected_element size
563 void hashset_init_size(HashSet *self, size_t expected_elements)
568 if(expected_elements >= UINT_MAX/2) {
572 needed_size = expected_elements * HT_1_DIV_OCCUPANCY_FLT;
573 po2size = ceil_po2(needed_size);
574 init_size(self, po2size);
578 * Initializes a hashset iterator. The memory for the allocator has to be
580 * @note it is not allowed to remove or insert elements while iterating
582 void hashset_iterator_init(HashSetIterator *self, const HashSet *hashset)
584 self->current_bucket = hashset->entries - 1;
585 self->end = hashset->entries + hashset->num_buckets;
588 self->entries_version = hashset->entries_version;
593 * Returns the next value in the iterator or NULL if no value is left
595 * @note it is not allowed to remove or insert elements while iterating
597 ValueType hashset_iterator_next(HashSetIterator *self)
599 HashSetEntry *current_bucket = self->current_bucket;
600 HashSetEntry *end = self->end;
602 /* using hashset_insert or hashset_remove is not allowed while iterating */
603 assert(self->entries_version == self->set->entries_version);
607 if(current_bucket >= end)
609 } while(EntryIsEmpty(*current_bucket) || EntryIsDeleted(*current_bucket));
611 self->current_bucket = current_bucket;
612 return EntryGetValue(*current_bucket);
616 * Removes the element the iterator points to. Removing an element a second time
619 void hashset_remove_iterator(HashSet *self, const HashSetIterator *iter)
621 HashSetEntry *entry = iter->current_bucket;
623 /* iterator_next needs to have been called at least once */
624 assert(entry >= self->entries);
625 /* needs to be on a valid element */
626 assert(entry < self->entries + self->num_buckets);
628 if(EntryIsDeleted(*entry))
631 EntrySetDeleted(*entry);
633 self->consider_shrink = 1;
637 __attribute__((unused)) static int dummy;