hashset.c 15.1 KB
Newer Older
Matthias Braun's avatar
Matthias Braun committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
 * @file
 * @date    17.03.2007
 * @brief   Geberic hashset implementation
 * @author  Matthias Braun, inspiration from densehash from google sparsehash
 *          package
 * @version $Id$
 *
 *
 * You have to specialize this file by defining:
 *
 * <ul>
 *  <li><b>HashSet</b>         The name of the hashset type</li>
 *  <li><b>HashSetIterator</b> The name of the hashset iterator type</li>
 *  <li><b>ValueType</b>       The type of the stored data values</li>
 *  <li><b>NullValue</b>       A special value representing no values</li>
 *  <li><b>DeletedValue</b>    A special value representing deleted entries</li>
 *  <li><b>Hash(hashset,key)</b> calculates the hash value for a given key</li>
 * </ul>
 *
 * Note that by default it is assumed that the data values themselfes are used
 * as keys. However you can change that with additional defines:
 *
 * <ul>
 *  <li><b>KeyType</b>         The type of the keys identifying data values.
 *                             Defining this implies, that a data value contains
 *                             more than just the key.</li>
 *  <li><b>GetKey(value)</b>   Extracts the key from a data value</li>
 *  <li><b>KeysEqual(hashset,key1,key2)</b>  Tests wether 2 keys are equal</li>
 *  <li><b>DO_REHASH</b>       Instead of storing the hash-values, recalculate
 *                             them on demand from the datavalues. (usefull if
 *                             calculating the hash-values takes less time than
 *                             a memory access)</li>
 * </ul>
 *
 * You can further fine tune your hashset by defining the following:
 *
 * <ul>
 *  <li><b>JUMP(num_probes)</b> The probing method</li>
 *  <li><b>Alloc(count)</b>     Allocates count hashset entries (NOT bytes)</li>
 *  <li><b>Free(ptr)</b>        Frees a block of memory allocated by Alloc</li>
 *  <li><b>SetRangeEmpty(ptr,count)</b> Efficiently sets a range of elements to
 *                                      the Null value</li>
 *  <li><b>ADDITIONAL_DATA<b>   Additional fields appended to the hashset struct</li>
 * </ul>
 */
#ifdef HashSet

#include <stdlib.h>
#include <string.h>
#include <assert.h>

#include "bitfiddle.h"
#include "util.h"

/* quadratic probing */
#ifndef JUMP
#define JUMP(num_probes)      (num_probes)
Christian Würdig's avatar
Christian Würdig committed
59
#endif /* JUMP */
Matthias Braun's avatar
Matthias Braun committed
60
61
62
63

#ifndef Hash
#define ID_HASH
#define Hash(this,value)      ((unsigned)(value))
Christian Würdig's avatar
Christian Würdig committed
64
#endif /* Hash */
Matthias Braun's avatar
Matthias Braun committed
65
66
67
68
69
70

#ifdef DO_REHASH
#define HashSetEntry                   ValueType
#define EntrySetHash(entry,new_hash)
#define EntryGetHash(this,entry)       Hash(this,entry)
#define EntryGetValue(entry)           (entry)
Christian Würdig's avatar
Christian Würdig committed
71
#else /* ! DO_REHASH */
Matthias Braun's avatar
Matthias Braun committed
72
73
74
#define EntryGetHash(this,entry)       (entry).hash
#define EntrySetHash(entry,new_hash)   (entry).hash = (new_hash)
#define EntryGetValue(entry)           (entry).data
Christian Würdig's avatar
Christian Würdig committed
75
#endif /* DO_REHASH */
Matthias Braun's avatar
Matthias Braun committed
76
77
78
79
80

#ifndef Alloc
#include "xmalloc.h"
#define Alloc(size)    (HashSetEntry*) xmalloc((size) * sizeof(HashSetEntry))
#define Free(ptr)      free(ptr)
Christian Würdig's avatar
Christian Würdig committed
81
#endif /* Alloc */
Matthias Braun's avatar
Matthias Braun committed
82
83
84
85

#ifdef ID_HASH
#define InsertReturnValue               int
#define GetInsertReturnValue(entry,new) (new)
Christian Würdig's avatar
Christian Würdig committed
86
#else /* ! ID_HASH */
Matthias Braun's avatar
Matthias Braun committed
87
88
#define InsertReturnValue               ValueType
#define GetInsertReturnValue(entry,new) EntryGetValue(entry)
Christian Würdig's avatar
Christian Würdig committed
89
#endif /* ID_HASH */
Matthias Braun's avatar
Matthias Braun committed
90
91
92
93
94

#ifndef KeyType
#define KeyType                  ValueType
#define GetKey(value)            (value)
#define InitData(this,value,key) (value) = (key)
Christian Würdig's avatar
Christian Würdig committed
95
#endif /* KeyType */
Matthias Braun's avatar
Matthias Braun committed
96
97
98

#ifndef ConstKeyType
#define ConstKeyType             const KeyType
Christian Würdig's avatar
Christian Würdig committed
99
#endif /* ConstKeyType */
Matthias Braun's avatar
Matthias Braun committed
100
101
102

#ifndef EntrySetEmpty
#define EntrySetEmpty(entry)    EntryGetValue(entry) = NullValue
Christian Würdig's avatar
Christian Würdig committed
103
#endif /* EntrySetEmpty */
Matthias Braun's avatar
Matthias Braun committed
104
105
#ifndef EntrySetDeleted
#define EntrySetDeleted(entry)  EntryGetValue(entry) = DeletedValue
Christian Würdig's avatar
Christian Würdig committed
106
#endif /* EntrySetDeleted */
Matthias Braun's avatar
Matthias Braun committed
107
108
#ifndef EntryIsEmpty
#define EntryIsEmpty(entry)     (EntryGetValue(entry) == NullValue)
Christian Würdig's avatar
Christian Würdig committed
109
#endif /* EntryIsEmpty */
Matthias Braun's avatar
Matthias Braun committed
110
111
#ifndef EntryIsDeleted
#define EntryIsDeleted(entry)   (EntryGetValue(entry) == DeletedValue)
Christian Würdig's avatar
Christian Würdig committed
112
#endif /* EntryIsDeleted */
Matthias Braun's avatar
Matthias Braun committed
113
114
115
116
117
118
119
120
121
122
123
#ifndef SetRangeEmpty
#define SetRangeEmpty(ptr,size)                \
{                                              \
	size_t _i;                                 \
	size_t _size = (size);                     \
	HashSetEntry *entries = (ptr);             \
	for(_i = 0; _i < _size; ++_i) {            \
		HashSetEntry *entry = & entries[_i];   \
		EntrySetEmpty(*entry);                 \
	}                                          \
}
Christian Würdig's avatar
Christian Würdig committed
124
#endif /* SetRangeEmpty */
Matthias Braun's avatar
Matthias Braun committed
125
126
127
128

#ifndef HT_OCCUPANCY_FLT
/** how full before we double size */
#define HT_OCCUPANCY_FLT  0.5f
Christian Würdig's avatar
Christian Würdig committed
129
#endif /* HT_OCCUPANCY_FLT */
Matthias Braun's avatar
Matthias Braun committed
130
131
132
133

#ifndef HT_EMPTY_FLT
/** how empty before we half size */
#define HT_EMPTY_FLT      (0.4f * (HT_OCCUPANCY_FLT))
Christian Würdig's avatar
Christian Würdig committed
134
#endif /* HT_EMPTY_FLT */
Matthias Braun's avatar
Matthias Braun committed
135
136
137
138

#ifndef HT_MIN_BUCKETS
/** default smallest bucket size */
#define HT_MIN_BUCKETS    32
Christian Würdig's avatar
Christian Würdig committed
139
#endif /* HT_MIN_BUCKETS */
Matthias Braun's avatar
Matthias Braun committed
140
141
142

#define ILLEGAL_POS       ((size_t)-1)

Christian Würdig's avatar
Christian Würdig committed
143
/* check that all needed functions are defined */
Matthias Braun's avatar
Matthias Braun committed
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
#ifndef hashset_init
#error You have to redefine hashset_init
#endif
#ifndef hashset_init_size
#error You have to redefine hashset_init_size
#endif
#ifndef hashset_destroy
#error You have to redefine hashset_destroy
#endif
#ifndef hashset_insert
#error You have to redefine hashset_insert
#endif
#ifndef hashset_remove
#error You have to redefine hashset_remove
#endif
#ifndef hashset_find
#error You have to redefine hashset_find
#endif
#ifndef hashset_size
#error You have to redefine hashset_size
#endif
#ifndef hashset_iterator_init
#error You have to redefine hashset_iterator_init
#endif
#ifndef hashset_iterator_next
#error You have to redefine hashset_iterator_next
#endif
#ifndef hashset_remove_iterator
#error You have to redefine hashset_remove_iterator
#endif

/**
 * Returns the number of elements in the hashset
 */
size_t hashset_size(const HashSet *this)
{
	return this->num_elements - this->num_deleted;
}

/**
 * Inserts an element into a hashset without growing the set (you have to make
 * sure there's enough room for that.
 * @note also see comments for hashset_insert()
 * @internal
 */
static inline
InsertReturnValue insert_nogrow(HashSet *this, KeyType key)
{
	size_t num_probes = 0;
	size_t num_buckets = this->num_buckets;
	size_t hashmask = num_buckets - 1;
	unsigned hash = Hash(this, key);
	size_t bucknum = hash & hashmask;
	size_t insert_pos = ILLEGAL_POS;

	assert((num_buckets & (num_buckets - 1)) == 0);

	while(1) {
		HashSetEntry *entry = & this->entries[bucknum];

		if(EntryIsEmpty(*entry)) {
			size_t p;
			HashSetEntry *nentry;

			if(insert_pos != ILLEGAL_POS) {
				p = insert_pos;
			} else {
				p = bucknum;
			}

			nentry = &this->entries[p];
			InitData(this, EntryGetValue(*nentry), key);
			EntrySetHash(*nentry, hash);
			this->num_elements++;
			return GetInsertReturnValue(*nentry, 1);
		}
		if(EntryIsDeleted(*entry)) {
			if(insert_pos == ILLEGAL_POS)
				insert_pos = bucknum;
		} else if(EntryGetHash(this, *entry) == hash) {
			if(KeysEqual(this, GetKey(EntryGetValue(*entry)), key)) {
				// Value already in the set, return it
				return GetInsertReturnValue(*entry, 0);
			}
		}

		++num_probes;
		bucknum = (bucknum + JUMP(num_probes)) & hashmask;
		assert(num_probes < num_buckets);
	}
}

/**
 * Inserts an element into a hashset under the assumption that the hashset
 * contains no deleted entries and the element doesn't exist in the hashset yet.
 * @internal
 */
static
void insert_new(HashSet *this, unsigned hash, ValueType value)
{
	size_t num_probes = 0;
	size_t num_buckets = this->num_buckets;
	size_t hashmask = num_buckets - 1;
	size_t bucknum = hash & hashmask;
	size_t insert_pos = ILLEGAL_POS;

	assert(value != NullValue);

	while(1) {
		HashSetEntry *entry = & this->entries[bucknum];

		if(EntryIsEmpty(*entry)) {
			size_t p;
			HashSetEntry *nentry;

			if(insert_pos != ILLEGAL_POS) {
				p = insert_pos;
			} else {
				p = bucknum;
			}
			nentry = &this->entries[p];

			EntryGetValue(*nentry) = value;
			EntrySetHash(*nentry, hash);
			this->num_elements++;
			return;
		}
		assert(!EntryIsDeleted(*entry));

		++num_probes;
		bucknum = (bucknum + JUMP(num_probes)) & hashmask;
		assert(num_probes < num_buckets);
	}
}

/**
 * calculate shrink and enlarge limits
 * @internal
 */
static inline
void reset_thresholds(HashSet *this)
{
	this->enlarge_threshold = (size_t) (this->num_buckets * HT_OCCUPANCY_FLT);
	this->shrink_threshold = (size_t) (this->num_buckets * HT_EMPTY_FLT);
	this->consider_shrink = 0;
}

/**
 * Resize the hashset
 * @internal
 */
static inline
void resize(HashSet *this, size_t new_size)
{
	size_t num_buckets = this->num_buckets;
	size_t i;
	HashSetEntry *old_entries = this->entries;
	HashSetEntry *new_entries;

	/* allocate a new array with double size */
	new_entries = Alloc(new_size);
	SetRangeEmpty(new_entries, new_size);

	/* use the new array */
	this->entries = new_entries;
	this->num_buckets = new_size;
	this->num_elements = 0;
	this->num_deleted = 0;
#ifndef NDEBUG
	this->entries_version++;
#endif
	reset_thresholds(this);

	/* reinsert all elements */
	for(i = 0; i < num_buckets; ++i) {
		HashSetEntry *entry = & old_entries[i];
		if(EntryIsEmpty(*entry) || EntryIsDeleted(*entry))
			continue;

		insert_new(this, EntryGetHash(this, *entry), EntryGetValue(*entry));
	}

	/* now we can free the old array */
	Free(old_entries);
}

/**
 * grow the hashset if adding 1 more elements would make it too crowded
 * @internal
 */
static inline
void maybe_grow(HashSet *this)
{
	size_t resize_to;

	if(LIKELY(this->num_elements + 1 <= this->enlarge_threshold))
		return;

	/* double table size */
	resize_to = this->num_buckets * 2;
	resize(this, resize_to);
}

/**
 * shrink the hashset if it is only sparsely filled
 * @internal
 */
static inline
void maybe_shrink(HashSet *this)
{
	size_t size;
	size_t resize_to;

	if(!this->consider_shrink)
		return;

	this->consider_shrink = 0;
	size = hashset_size(this);
	if(LIKELY(size > this->shrink_threshold))
		return;

	resize_to = ceil_po2(size);

	if(resize_to < 4)
		resize_to = 4;

	resize(this, resize_to);
}

/**
 * Insert an element into the hashset. If no element with key key exists yet,
 * then a new one is created and initialized with the InitData function.
 * Otherwise the exisiting element is returned (for hashs where key is equal to
 * value, nothing is returned.)
 *
 * @param this   the hashset
 * @param key    the key that identifies the data
 * @returns      the existing or newly created data element (or nothing in case of hashs where keys are the while value)
 */
InsertReturnValue hashset_insert(HashSet *this, KeyType key)
{
#ifndef NDEBUG
	this->entries_version++;
#endif

	maybe_shrink(this);
	maybe_grow(this);
	return insert_nogrow(this, key);
}

/**
 * Searchs for an element with key @p key.
 *
 * @param this      the hashset
 * @param key       the key to search for
 * @returns         the found value or NullValue if nothing was found
 */
ValueType hashset_find(const HashSet *this, ConstKeyType key)
{
	size_t num_probes = 0;
	size_t num_buckets = this->num_buckets;
	size_t hashmask = num_buckets - 1;
	unsigned hash = Hash(this, key);
	size_t bucknum = hash & hashmask;

	while(1) {
		HashSetEntry *entry = & this->entries[bucknum];

		if(EntryIsEmpty(*entry)) {
			return NullValue;
		}
		if(EntryIsDeleted(*entry)) {
			// value is deleted
		} else if(EntryGetHash(this, *entry) == hash) {
			if(KeysEqual(this, GetKey(EntryGetValue(*entry)), key)) {
				// found the value
				return EntryGetValue(*entry);
			}
		}

		++num_probes;
		bucknum = (bucknum + JUMP(num_probes)) & hashmask;
		assert(num_probes < num_buckets);
	}
}

/**
 * Removes an element from a hashset. Does nothing if the set doesn't contain
 * the element.
 *
 * @param this    the hashset
 * @param key     key that identifies the data to remove
 */
void hashset_remove(HashSet *this, ConstKeyType key)
{
	size_t num_probes = 0;
	size_t num_buckets = this->num_buckets;
	size_t hashmask = num_buckets - 1;
	unsigned hash = Hash(this, key);
	size_t bucknum = hash & hashmask;

#ifndef NDEBUG
	this->entries_version++;
#endif

	while(1) {
		HashSetEntry *entry = & this->entries[bucknum];

		if(EntryIsEmpty(*entry)) {
			return;
		}
		if(EntryIsDeleted(*entry)) {
			// entry is deleted
		} else if(EntryGetHash(this, *entry) == hash) {
			if(KeysEqual(this, GetKey(EntryGetValue(*entry)), key)) {
				EntrySetDeleted(*entry);
				this->num_deleted++;
				this->consider_shrink = 1;
				return;
			}
		}

		++num_probes;
		bucknum = (bucknum + JUMP(num_probes)) & hashmask;
		assert(num_probes < num_buckets);
	}
}

/**
 * Initializes hashset with a specific size
 * @internal
 */
static inline
void init_size(HashSet *this, size_t initial_size)
{
	if(initial_size < 4)
		initial_size = 4;

	this->entries = Alloc(initial_size);
	SetRangeEmpty(this->entries, initial_size);
	this->num_buckets = initial_size;
	this->consider_shrink = 0;
	this->num_elements = 0;
	this->num_deleted = 0;
#ifndef NDEBUG
	this->entries_version = 0;
#endif

	reset_thresholds(this);
}

/**
 * Initialializes a hashset with the default size. The memory for the set has to
 * already allocated.
 */
void hashset_init(HashSet *this)
{
	init_size(this, HT_MIN_BUCKETS);
}

/**
 * Destroys a hashset, freeing all used memory (except the memory for the
 * HashSet struct itself).
 */
void hashset_destroy(HashSet *this)
{
	Free(this->entries);
#ifndef NDEBUG
	this->entries = NULL;
#endif
}

/**
 * Initializes a hashset expecting expected_element size
 */
void hashset_init_size(HashSet *this, size_t expected_elements)
{
	size_t needed_size;
	size_t po2size;

	if(expected_elements >= UINT_MAX/2) {
		abort();
	}

	needed_size = expected_elements * (1.0 / HT_OCCUPANCY_FLT);
	po2size = ceil_po2(needed_size);
	init_size(this, po2size);
}

/**
 * Initializes a hashset iterator. The memory for the allocator has to be
 * already allocated.
 * @note it is not allowed to remove or insert elements while iterating
 */
void hashset_iterator_init(HashSetIterator *this, const HashSet *hashset)
{
	this->current_bucket = hashset->entries - 1;
	this->end = hashset->entries + hashset->num_buckets;
#ifndef NDEBUG
	this->set = hashset;
	this->entries_version = hashset->entries_version;
#endif
}

/**
 * Returns the next value in the iterator or NULL if no value is left
 * in the hashset.
 * @note it is not allowed to remove or insert elements while iterating
 */
ValueType hashset_iterator_next(HashSetIterator *this)
{
	HashSetEntry *current_bucket = this->current_bucket;
	HashSetEntry *end = this->end;

	if(current_bucket >= end)
		return NullValue;

	/* using hashset_insert or hashset_remove is not allowed while iterating */
	assert(this->entries_version == this->set->entries_version);

	do {
		current_bucket++;
	} while(current_bucket < end &&
			(EntryIsEmpty(*current_bucket) || EntryIsDeleted(*current_bucket)));

	if(current_bucket >= end)
		return NullValue;

	this->current_bucket = current_bucket;
	return EntryGetValue(*current_bucket);
}

/**
 * Removes the element the iterator points to. Removing an element a second time
 * has no result.
 */
void hashset_remove_iterator(HashSet *this, const HashSetIterator *iter)
{
	HashSetEntry *entry = iter->current_bucket;

	/* iterator_next needs to have been called at least once */
	assert(entry >= this->entries);
	/* needs to be on a valid element */
	assert(entry < this->entries + this->num_buckets);

	if(EntryIsDeleted(*entry))
		return;

	EntrySetDeleted(*entry);
	this->num_deleted++;
	this->consider_shrink = 1;
}

#endif