2 * Copyright (C) 1995-2007 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
29 * You have to specialize this file by defining:
32 * <li><b>HashSet</b> The name of the hashset type</li>
33 * <li><b>HashSetIterator</b> The name of the hashset iterator type</li>
34 * <li><b>ValueType</b> The type of the stored data values</li>
35 * <li><b>NullValue</b> A special value representing no values</li>
36 * <li><b>DeletedValue</b> A special value representing deleted entries</li>
37 * <li><b>Hash(hashset,key)</b> calculates the hash value for a given key</li>
40 * Note that by default it is assumed that the data values themselfes are used
41 * as keys. However you can change that with additional defines:
44 * <li><b>KeyType</b> The type of the keys identifying data values.
45 * Defining this implies, that a data value contains
46 * more than just the key.</li>
47 * <li><b>GetKey(value)</b> Extracts the key from a data value</li>
48 * <li><b>KeysEqual(hashset,key1,key2)</b> Tests wether 2 keys are equal</li>
49 * <li><b>DO_REHASH</b> Instead of storing the hash-values, recalculate
50 * them on demand from the datavalues. (usefull if
51 * calculating the hash-values takes less time than
52 * a memory access)</li>
55 * You can further fine tune your hashset by defining the following:
58 * <li><b>JUMP(num_probes)</b> The probing method</li>
59 * <li><b>Alloc(count)</b> Allocates count hashset entries (NOT bytes)</li>
60 * <li><b>Free(ptr)</b> Frees a block of memory allocated by Alloc</li>
61 * <li><b>SetRangeEmpty(ptr,count)</b> Efficiently sets a range of elements to
63 * <li><b>ADDITIONAL_DATA<b> Additional fields appended to the hashset struct</li>
72 #include "bitfiddle.h"
75 /* quadratic probing */
77 #define JUMP(num_probes) (num_probes)
82 #define Hash(self,key) ((unsigned)(key))
86 #define HashSetEntry ValueType
87 #define EntrySetHash(entry,new_hash)
88 #define EntryGetHash(self,entry) Hash(self, GetKey(entry))
89 #define EntryGetValue(entry) (entry)
90 #else /* ! DO_REHASH */
91 #define EntryGetHash(self,entry) (entry).hash
92 #define EntrySetHash(entry,new_hash) (entry).hash = (new_hash)
93 #define EntryGetValue(entry) (entry).data
94 #endif /* DO_REHASH */
98 #define Alloc(size) (HashSetEntry*) xmalloc((size) * sizeof(HashSetEntry))
99 #define Free(ptr) free(ptr)
103 #define InsertReturnValue int
104 #define GetInsertReturnValue(entry,found) (found)
105 #define NullReturnValue 0
106 #else /* ! ID_HASH */
108 #define InsertReturnValue ValueType
109 #define GetInsertReturnValue(entry,found) EntryGetValue(entry)
110 #define NullReturnValue NullValue
112 #define InsertReturnValue ValueType*
113 #define GetInsertReturnValue(entry,found) & EntryGetValue(entry)
114 #define NullReturnValue & NullValue
119 #define KeyType ValueType
120 #define GetKey(value) (value)
121 #define InitData(self,value,key) (value) = (key)
125 #define ConstKeyType const KeyType
126 #endif /* ConstKeyType */
128 #ifndef EntrySetEmpty
129 #define EntrySetEmpty(entry) EntryGetValue(entry) = NullValue
130 #endif /* EntrySetEmpty */
131 #ifndef EntrySetDeleted
132 #define EntrySetDeleted(entry) EntryGetValue(entry) = DeletedValue
133 #endif /* EntrySetDeleted */
135 #define EntryIsEmpty(entry) (EntryGetValue(entry) == NullValue)
136 #endif /* EntryIsEmpty */
137 #ifndef EntryIsDeleted
138 #define EntryIsDeleted(entry) (EntryGetValue(entry) == DeletedValue)
139 #endif /* EntryIsDeleted */
140 #ifndef SetRangeEmpty
141 #define SetRangeEmpty(ptr,size) \
144 size_t _size = (size); \
145 HashSetEntry *entries = (ptr); \
146 for(_i = 0; _i < _size; ++_i) { \
147 HashSetEntry *entry = & entries[_i]; \
148 EntrySetEmpty(*entry); \
151 #endif /* SetRangeEmpty */
153 #ifndef HT_OCCUPANCY_FLT
154 /** how full before we double size */
155 #define HT_OCCUPANCY_FLT(x) ((x)/2)
156 #endif /* HT_OCCUPANCY_FLT */
157 #ifndef HT_1_DIV_OCCUPANCY_FLT
158 #define HT_1_DIV_OCCUPANCY_FLT 2
162 /** how empty before we half size */
163 #define HT_EMPTY_FLT(x) ((x)/5)
164 #endif /* HT_EMPTY_FLT */
166 #ifndef HT_MIN_BUCKETS
167 /** default smallest bucket size */
168 #define HT_MIN_BUCKETS 32
169 #endif /* HT_MIN_BUCKETS */
171 #define ILLEGAL_POS ((size_t)-1)
173 /* check that all needed functions are defined */
175 #error You have to redefine hashset_init
177 #ifndef hashset_init_size
178 #error You have to redefine hashset_init_size
180 #ifndef hashset_destroy
181 #error You have to redefine hashset_destroy
183 #ifndef hashset_insert
184 #error You have to redefine hashset_insert
186 #ifndef hashset_remove
187 #error You have to redefine hashset_remove
190 #error You have to redefine hashset_find
193 #error You have to redefine hashset_size
195 #ifndef hashset_iterator_init
196 #error You have to redefine hashset_iterator_init
198 #ifndef hashset_iterator_next
199 #error You have to redefine hashset_iterator_next
201 #ifndef hashset_remove_iterator
202 #error You have to redefine hashset_remove_iterator
206 * Returns the number of elements in the hashset
208 size_t hashset_size(const HashSet *self)
210 return self->num_elements - self->num_deleted;
214 * Inserts an element into a hashset without growing the set (you have to make
215 * sure there's enough room for that.
216 * @note also see comments for hashset_insert()
220 InsertReturnValue insert_nogrow(HashSet *self, KeyType key)
222 size_t num_probes = 0;
223 size_t num_buckets = self->num_buckets;
224 size_t hashmask = num_buckets - 1;
225 unsigned hash = Hash(self, key);
226 size_t bucknum = hash & hashmask;
227 size_t insert_pos = ILLEGAL_POS;
229 assert((num_buckets & (num_buckets - 1)) == 0);
232 HashSetEntry *entry = & self->entries[bucknum];
234 if(EntryIsEmpty(*entry)) {
236 HashSetEntry *nentry;
238 if(insert_pos != ILLEGAL_POS) {
244 nentry = &self->entries[p];
245 InitData(self, EntryGetValue(*nentry), key);
246 EntrySetHash(*nentry, hash);
247 self->num_elements++;
248 return GetInsertReturnValue(*nentry, 0);
250 if(EntryIsDeleted(*entry)) {
251 if(insert_pos == ILLEGAL_POS)
252 insert_pos = bucknum;
253 } else if(EntryGetHash(self, *entry) == hash) {
254 if(KeysEqual(self, GetKey(EntryGetValue(*entry)), key)) {
255 // Value already in the set, return it
256 return GetInsertReturnValue(*entry, 1);
261 bucknum = (bucknum + JUMP(num_probes)) & hashmask;
262 assert(num_probes < num_buckets);
267 * Inserts an element into a hashset under the assumption that the hashset
268 * contains no deleted entries and the element doesn't exist in the hashset yet.
272 void insert_new(HashSet *self, unsigned hash, ValueType value)
274 size_t num_probes = 0;
275 size_t num_buckets = self->num_buckets;
276 size_t hashmask = num_buckets - 1;
277 size_t bucknum = hash & hashmask;
278 size_t insert_pos = ILLEGAL_POS;
280 //assert(value != NullValue);
283 HashSetEntry *entry = & self->entries[bucknum];
285 if(EntryIsEmpty(*entry)) {
287 HashSetEntry *nentry;
289 if(insert_pos != ILLEGAL_POS) {
294 nentry = &self->entries[p];
296 EntryGetValue(*nentry) = value;
297 EntrySetHash(*nentry, hash);
298 self->num_elements++;
301 assert(!EntryIsDeleted(*entry));
304 bucknum = (bucknum + JUMP(num_probes)) & hashmask;
305 assert(num_probes < num_buckets);
310 * calculate shrink and enlarge limits
314 void reset_thresholds(HashSet *self)
316 self->enlarge_threshold = (size_t) HT_OCCUPANCY_FLT(self->num_buckets);
317 self->shrink_threshold = (size_t) HT_EMPTY_FLT(self->num_buckets);
318 self->consider_shrink = 0;
326 void resize(HashSet *self, size_t new_size)
328 size_t num_buckets = self->num_buckets;
330 HashSetEntry *old_entries = self->entries;
331 HashSetEntry *new_entries;
333 /* allocate a new array with double size */
334 new_entries = Alloc(new_size);
335 SetRangeEmpty(new_entries, new_size);
337 /* use the new array */
338 self->entries = new_entries;
339 self->num_buckets = new_size;
340 self->num_elements = 0;
341 self->num_deleted = 0;
343 self->entries_version++;
345 reset_thresholds(self);
347 /* reinsert all elements */
348 for(i = 0; i < num_buckets; ++i) {
349 HashSetEntry *entry = & old_entries[i];
350 if(EntryIsEmpty(*entry) || EntryIsDeleted(*entry))
353 insert_new(self, EntryGetHash(self, *entry), EntryGetValue(*entry));
356 /* now we can free the old array */
361 * grow the hashset if adding 1 more elements would make it too crowded
365 void maybe_grow(HashSet *self)
369 if(LIKELY(self->num_elements + 1 <= self->enlarge_threshold))
372 /* double table size */
373 resize_to = self->num_buckets * 2;
374 resize(self, resize_to);
378 * shrink the hashset if it is only sparsely filled
382 void maybe_shrink(HashSet *self)
387 if(!self->consider_shrink)
390 self->consider_shrink = 0;
391 size = hashset_size(self);
392 if(size <= HT_MIN_BUCKETS)
395 if(LIKELY(size > self->shrink_threshold))
398 resize_to = ceil_po2(size);
403 resize(self, resize_to);
407 * Insert an element into the hashset. If no element with key key exists yet,
408 * then a new one is created and initialized with the InitData function.
409 * Otherwise the exisiting element is returned (for hashs where key is equal to
410 * value, nothing is returned.)
412 * @param self the hashset
413 * @param key the key that identifies the data
414 * @returns the existing or newly created data element (or nothing in case of hashs where keys are the while value)
416 InsertReturnValue hashset_insert(HashSet *self, KeyType key)
419 self->entries_version++;
424 return insert_nogrow(self, key);
428 * Searchs for an element with key @p key.
430 * @param self the hashset
431 * @param key the key to search for
432 * @returns the found value or NullValue if nothing was found
434 InsertReturnValue hashset_find(const HashSet *self, ConstKeyType key)
436 size_t num_probes = 0;
437 size_t num_buckets = self->num_buckets;
438 size_t hashmask = num_buckets - 1;
439 unsigned hash = Hash(self, key);
440 size_t bucknum = hash & hashmask;
443 HashSetEntry *entry = & self->entries[bucknum];
445 if(EntryIsEmpty(*entry)) {
446 return NullReturnValue;
448 if(EntryIsDeleted(*entry)) {
450 } else if(EntryGetHash(self, *entry) == hash) {
451 if(KeysEqual(self, GetKey(EntryGetValue(*entry)), key)) {
453 return GetInsertReturnValue(*entry, 1);
458 bucknum = (bucknum + JUMP(num_probes)) & hashmask;
459 assert(num_probes < num_buckets);
464 * Removes an element from a hashset. Does nothing if the set doesn't contain
467 * @param self the hashset
468 * @param key key that identifies the data to remove
470 void hashset_remove(HashSet *self, ConstKeyType key)
472 size_t num_probes = 0;
473 size_t num_buckets = self->num_buckets;
474 size_t hashmask = num_buckets - 1;
475 unsigned hash = Hash(self, key);
476 size_t bucknum = hash & hashmask;
479 self->entries_version++;
483 HashSetEntry *entry = & self->entries[bucknum];
485 if(EntryIsEmpty(*entry)) {
488 if(EntryIsDeleted(*entry)) {
490 } else if(EntryGetHash(self, *entry) == hash) {
491 if(KeysEqual(self, GetKey(EntryGetValue(*entry)), key)) {
492 EntrySetDeleted(*entry);
494 self->consider_shrink = 1;
500 bucknum = (bucknum + JUMP(num_probes)) & hashmask;
501 assert(num_probes < num_buckets);
506 * Initializes hashset with a specific size
510 void init_size(HashSet *self, size_t initial_size)
515 self->entries = Alloc(initial_size);
516 SetRangeEmpty(self->entries, initial_size);
517 self->num_buckets = initial_size;
518 self->consider_shrink = 0;
519 self->num_elements = 0;
520 self->num_deleted = 0;
522 self->entries_version = 0;
525 reset_thresholds(self);
529 * Initialializes a hashset with the default size. The memory for the set has to
532 void hashset_init(HashSet *self)
534 init_size(self, HT_MIN_BUCKETS);
538 * Destroys a hashset, freeing all used memory (except the memory for the
539 * HashSet struct itself).
541 void hashset_destroy(HashSet *self)
545 self->entries = NULL;
550 * Initializes a hashset expecting expected_element size
552 void hashset_init_size(HashSet *self, size_t expected_elements)
557 if(expected_elements >= UINT_MAX/2) {
561 needed_size = expected_elements * HT_1_DIV_OCCUPANCY_FLT;
562 po2size = ceil_po2(needed_size);
563 init_size(self, po2size);
567 * Initializes a hashset iterator. The memory for the allocator has to be
569 * @note it is not allowed to remove or insert elements while iterating
571 void hashset_iterator_init(HashSetIterator *self, const HashSet *hashset)
573 self->current_bucket = hashset->entries - 1;
574 self->end = hashset->entries + hashset->num_buckets;
577 self->entries_version = hashset->entries_version;
582 * Returns the next value in the iterator or NULL if no value is left
584 * @note it is not allowed to remove or insert elements while iterating
586 ValueType hashset_iterator_next(HashSetIterator *self)
588 HashSetEntry *current_bucket = self->current_bucket;
589 HashSetEntry *end = self->end;
591 /* using hashset_insert or hashset_remove is not allowed while iterating */
592 assert(self->entries_version == self->set->entries_version);
596 if(current_bucket >= end)
598 } while(EntryIsEmpty(*current_bucket) || EntryIsDeleted(*current_bucket));
600 self->current_bucket = current_bucket;
601 return EntryGetValue(*current_bucket);
605 * Removes the element the iterator points to. Removing an element a second time
608 void hashset_remove_iterator(HashSet *self, const HashSetIterator *iter)
610 HashSetEntry *entry = iter->current_bucket;
612 /* iterator_next needs to have been called at least once */
613 assert(entry >= self->entries);
614 /* needs to be on a valid element */
615 assert(entry < self->entries + self->num_buckets);
617 if(EntryIsDeleted(*entry))
620 EntrySetDeleted(*entry);
622 self->consider_shrink = 1;