hashset.c 15.8 KB
Newer Older
1
/*
2
 * Copyright (C) 1995-2007 University of Karlsruhe.  All right reserved.
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 *
 * This file is part of libFirm.
 *
 * This file may be distributed and/or modified under the terms of the
 * GNU General Public License version 2 as published by the Free Software
 * Foundation and appearing in the file LICENSE.GPL included in the
 * packaging of this file.
 *
 * Licensees holding valid libFirm Professional Edition licenses may use
 * this file in accordance with the libFirm Commercial License.
 * Agreement provided with the Software.
 *
 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
 * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE.
 */

Matthias Braun's avatar
Matthias Braun committed
20
21
/**
 * @file
22
 * @brief   Generic hashset implementation
Matthias Braun's avatar
Matthias Braun committed
23
24
 * @author  Matthias Braun, inspiration from densehash from google sparsehash
 *          package
25
 * @date    17.03.2007
Matthias Braun's avatar
Matthias Braun committed
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
 * @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
78
#endif /* JUMP */
Matthias Braun's avatar
Matthias Braun committed
79
80
81

#ifndef Hash
#define ID_HASH
82
#define Hash(self,value)      ((unsigned)(value))
Christian Würdig's avatar
Christian Würdig committed
83
#endif /* Hash */
Matthias Braun's avatar
Matthias Braun committed
84
85
86
87

#ifdef DO_REHASH
#define HashSetEntry                   ValueType
#define EntrySetHash(entry,new_hash)
88
#define EntryGetHash(self,entry)       Hash(self,entry)
Matthias Braun's avatar
Matthias Braun committed
89
#define EntryGetValue(entry)           (entry)
Christian Würdig's avatar
Christian Würdig committed
90
#else /* ! DO_REHASH */
91
#define EntryGetHash(self,entry)       (entry).hash
Matthias Braun's avatar
Matthias Braun committed
92
93
#define EntrySetHash(entry,new_hash)   (entry).hash = (new_hash)
#define EntryGetValue(entry)           (entry).data
Christian Würdig's avatar
Christian Würdig committed
94
#endif /* DO_REHASH */
Matthias Braun's avatar
Matthias Braun committed
95
96
97
98
99

#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
100
#endif /* Alloc */
Matthias Braun's avatar
Matthias Braun committed
101
102
103
104

#ifdef ID_HASH
#define InsertReturnValue               int
#define GetInsertReturnValue(entry,new) (new)
Christian Würdig's avatar
Christian Würdig committed
105
#else /* ! ID_HASH */
Matthias Braun's avatar
Matthias Braun committed
106
107
#define InsertReturnValue               ValueType
#define GetInsertReturnValue(entry,new) EntryGetValue(entry)
Christian Würdig's avatar
Christian Würdig committed
108
#endif /* ID_HASH */
Matthias Braun's avatar
Matthias Braun committed
109
110
111
112

#ifndef KeyType
#define KeyType                  ValueType
#define GetKey(value)            (value)
113
#define InitData(self,value,key) (value) = (key)
Christian Würdig's avatar
Christian Würdig committed
114
#endif /* KeyType */
Matthias Braun's avatar
Matthias Braun committed
115
116
117

#ifndef ConstKeyType
#define ConstKeyType             const KeyType
Christian Würdig's avatar
Christian Würdig committed
118
#endif /* ConstKeyType */
Matthias Braun's avatar
Matthias Braun committed
119
120
121

#ifndef EntrySetEmpty
#define EntrySetEmpty(entry)    EntryGetValue(entry) = NullValue
Christian Würdig's avatar
Christian Würdig committed
122
#endif /* EntrySetEmpty */
Matthias Braun's avatar
Matthias Braun committed
123
124
#ifndef EntrySetDeleted
#define EntrySetDeleted(entry)  EntryGetValue(entry) = DeletedValue
Christian Würdig's avatar
Christian Würdig committed
125
#endif /* EntrySetDeleted */
Matthias Braun's avatar
Matthias Braun committed
126
127
#ifndef EntryIsEmpty
#define EntryIsEmpty(entry)     (EntryGetValue(entry) == NullValue)
Christian Würdig's avatar
Christian Würdig committed
128
#endif /* EntryIsEmpty */
Matthias Braun's avatar
Matthias Braun committed
129
130
#ifndef EntryIsDeleted
#define EntryIsDeleted(entry)   (EntryGetValue(entry) == DeletedValue)
Christian Würdig's avatar
Christian Würdig committed
131
#endif /* EntryIsDeleted */
Matthias Braun's avatar
Matthias Braun committed
132
133
134
135
136
137
138
139
140
141
142
#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
143
#endif /* SetRangeEmpty */
Matthias Braun's avatar
Matthias Braun committed
144
145
146
147

#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
148
#endif /* HT_OCCUPANCY_FLT */
Matthias Braun's avatar
Matthias Braun committed
149
150
151
152

#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
153
#endif /* HT_EMPTY_FLT */
Matthias Braun's avatar
Matthias Braun committed
154
155
156
157

#ifndef HT_MIN_BUCKETS
/** default smallest bucket size */
#define HT_MIN_BUCKETS    32
Christian Würdig's avatar
Christian Würdig committed
158
#endif /* HT_MIN_BUCKETS */
Matthias Braun's avatar
Matthias Braun committed
159
160
161

#define ILLEGAL_POS       ((size_t)-1)

Christian Würdig's avatar
Christian Würdig committed
162
/* check that all needed functions are defined */
Matthias Braun's avatar
Matthias Braun committed
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
#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
 */
197
size_t hashset_size(const HashSet *self)
Matthias Braun's avatar
Matthias Braun committed
198
{
199
	return self->num_elements - self->num_deleted;
Matthias Braun's avatar
Matthias Braun committed
200
201
202
203
204
205
206
207
}

/**
 * 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
 */
Andreas Schösser's avatar
Andreas Schösser committed
208
static INLINE
209
InsertReturnValue insert_nogrow(HashSet *self, KeyType key)
Matthias Braun's avatar
Matthias Braun committed
210
211
{
	size_t num_probes = 0;
212
	size_t num_buckets = self->num_buckets;
Matthias Braun's avatar
Matthias Braun committed
213
	size_t hashmask = num_buckets - 1;
214
	unsigned hash = Hash(self, key);
Matthias Braun's avatar
Matthias Braun committed
215
216
217
218
219
220
	size_t bucknum = hash & hashmask;
	size_t insert_pos = ILLEGAL_POS;

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

	while(1) {
221
		HashSetEntry *entry = & self->entries[bucknum];
Matthias Braun's avatar
Matthias Braun committed
222
223
224
225
226
227
228
229
230
231
232

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

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

233
234
			nentry = &self->entries[p];
			InitData(self, EntryGetValue(*nentry), key);
Matthias Braun's avatar
Matthias Braun committed
235
			EntrySetHash(*nentry, hash);
236
			self->num_elements++;
Matthias Braun's avatar
Matthias Braun committed
237
238
239
240
241
			return GetInsertReturnValue(*nentry, 1);
		}
		if(EntryIsDeleted(*entry)) {
			if(insert_pos == ILLEGAL_POS)
				insert_pos = bucknum;
242
243
		} else if(EntryGetHash(self, *entry) == hash) {
			if(KeysEqual(self, GetKey(EntryGetValue(*entry)), key)) {
Matthias Braun's avatar
Matthias Braun committed
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
				// 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
261
void insert_new(HashSet *self, unsigned hash, ValueType value)
Matthias Braun's avatar
Matthias Braun committed
262
263
{
	size_t num_probes = 0;
264
	size_t num_buckets = self->num_buckets;
Matthias Braun's avatar
Matthias Braun committed
265
266
267
268
269
270
271
	size_t hashmask = num_buckets - 1;
	size_t bucknum = hash & hashmask;
	size_t insert_pos = ILLEGAL_POS;

	assert(value != NullValue);

	while(1) {
272
		HashSetEntry *entry = & self->entries[bucknum];
Matthias Braun's avatar
Matthias Braun committed
273
274
275
276
277
278
279
280
281
282

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

			if(insert_pos != ILLEGAL_POS) {
				p = insert_pos;
			} else {
				p = bucknum;
			}
283
			nentry = &self->entries[p];
Matthias Braun's avatar
Matthias Braun committed
284
285
286

			EntryGetValue(*nentry) = value;
			EntrySetHash(*nentry, hash);
287
			self->num_elements++;
Matthias Braun's avatar
Matthias Braun committed
288
289
290
291
292
293
294
295
296
297
298
299
300
301
			return;
		}
		assert(!EntryIsDeleted(*entry));

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

/**
 * calculate shrink and enlarge limits
 * @internal
 */
Andreas Schösser's avatar
Andreas Schösser committed
302
static INLINE
303
void reset_thresholds(HashSet *self)
Matthias Braun's avatar
Matthias Braun committed
304
{
305
306
307
	self->enlarge_threshold = (size_t) (self->num_buckets * HT_OCCUPANCY_FLT);
	self->shrink_threshold = (size_t) (self->num_buckets * HT_EMPTY_FLT);
	self->consider_shrink = 0;
Matthias Braun's avatar
Matthias Braun committed
308
309
310
311
312
313
}

/**
 * Resize the hashset
 * @internal
 */
Andreas Schösser's avatar
Andreas Schösser committed
314
static INLINE
315
void resize(HashSet *self, size_t new_size)
Matthias Braun's avatar
Matthias Braun committed
316
{
317
	size_t num_buckets = self->num_buckets;
Matthias Braun's avatar
Matthias Braun committed
318
	size_t i;
319
	HashSetEntry *old_entries = self->entries;
Matthias Braun's avatar
Matthias Braun committed
320
321
322
323
324
325
326
	HashSetEntry *new_entries;

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

	/* use the new array */
327
328
329
330
	self->entries = new_entries;
	self->num_buckets = new_size;
	self->num_elements = 0;
	self->num_deleted = 0;
Matthias Braun's avatar
Matthias Braun committed
331
#ifndef NDEBUG
332
	self->entries_version++;
Matthias Braun's avatar
Matthias Braun committed
333
#endif
334
	reset_thresholds(self);
Matthias Braun's avatar
Matthias Braun committed
335
336
337
338
339
340
341

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

342
		insert_new(self, EntryGetHash(self, *entry), EntryGetValue(*entry));
Matthias Braun's avatar
Matthias Braun committed
343
344
345
346
347
348
349
350
351
352
	}

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

/**
 * grow the hashset if adding 1 more elements would make it too crowded
 * @internal
 */
Andreas Schösser's avatar
Andreas Schösser committed
353
static INLINE
354
void maybe_grow(HashSet *self)
Matthias Braun's avatar
Matthias Braun committed
355
356
357
{
	size_t resize_to;

358
	if(LIKELY(self->num_elements + 1 <= self->enlarge_threshold))
Matthias Braun's avatar
Matthias Braun committed
359
360
361
		return;

	/* double table size */
362
363
	resize_to = self->num_buckets * 2;
	resize(self, resize_to);
Matthias Braun's avatar
Matthias Braun committed
364
365
366
367
368
369
}

/**
 * shrink the hashset if it is only sparsely filled
 * @internal
 */
Andreas Schösser's avatar
Andreas Schösser committed
370
static INLINE
371
void maybe_shrink(HashSet *self)
Matthias Braun's avatar
Matthias Braun committed
372
373
374
375
{
	size_t size;
	size_t resize_to;

376
	if(!self->consider_shrink)
Matthias Braun's avatar
Matthias Braun committed
377
378
		return;

379
380
381
	self->consider_shrink = 0;
	size = hashset_size(self);
	if(LIKELY(size > self->shrink_threshold))
Matthias Braun's avatar
Matthias Braun committed
382
383
384
385
386
387
388
		return;

	resize_to = ceil_po2(size);

	if(resize_to < 4)
		resize_to = 4;

389
	resize(self, resize_to);
Matthias Braun's avatar
Matthias Braun committed
390
391
392
393
394
395
396
397
}

/**
 * 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.)
 *
398
 * @param self   the hashset
Matthias Braun's avatar
Matthias Braun committed
399
400
401
 * @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)
 */
402
InsertReturnValue hashset_insert(HashSet *self, KeyType key)
Matthias Braun's avatar
Matthias Braun committed
403
404
{
#ifndef NDEBUG
405
	self->entries_version++;
Matthias Braun's avatar
Matthias Braun committed
406
407
#endif

408
409
410
	maybe_shrink(self);
	maybe_grow(self);
	return insert_nogrow(self, key);
Matthias Braun's avatar
Matthias Braun committed
411
412
413
414
415
}

/**
 * Searchs for an element with key @p key.
 *
416
 * @param self      the hashset
Matthias Braun's avatar
Matthias Braun committed
417
418
419
 * @param key       the key to search for
 * @returns         the found value or NullValue if nothing was found
 */
420
ValueType hashset_find(const HashSet *self, ConstKeyType key)
Matthias Braun's avatar
Matthias Braun committed
421
422
{
	size_t num_probes = 0;
423
	size_t num_buckets = self->num_buckets;
Matthias Braun's avatar
Matthias Braun committed
424
	size_t hashmask = num_buckets - 1;
425
	unsigned hash = Hash(self, key);
Matthias Braun's avatar
Matthias Braun committed
426
427
428
	size_t bucknum = hash & hashmask;

	while(1) {
429
		HashSetEntry *entry = & self->entries[bucknum];
Matthias Braun's avatar
Matthias Braun committed
430
431
432
433
434
435

		if(EntryIsEmpty(*entry)) {
			return NullValue;
		}
		if(EntryIsDeleted(*entry)) {
			// value is deleted
436
437
		} else if(EntryGetHash(self, *entry) == hash) {
			if(KeysEqual(self, GetKey(EntryGetValue(*entry)), key)) {
Matthias Braun's avatar
Matthias Braun committed
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
				// 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.
 *
453
 * @param self    the hashset
Matthias Braun's avatar
Matthias Braun committed
454
455
 * @param key     key that identifies the data to remove
 */
456
void hashset_remove(HashSet *self, ConstKeyType key)
Matthias Braun's avatar
Matthias Braun committed
457
458
{
	size_t num_probes = 0;
459
	size_t num_buckets = self->num_buckets;
Matthias Braun's avatar
Matthias Braun committed
460
	size_t hashmask = num_buckets - 1;
461
	unsigned hash = Hash(self, key);
Matthias Braun's avatar
Matthias Braun committed
462
463
464
	size_t bucknum = hash & hashmask;

#ifndef NDEBUG
465
	self->entries_version++;
Matthias Braun's avatar
Matthias Braun committed
466
467
468
#endif

	while(1) {
469
		HashSetEntry *entry = & self->entries[bucknum];
Matthias Braun's avatar
Matthias Braun committed
470
471
472
473
474
475

		if(EntryIsEmpty(*entry)) {
			return;
		}
		if(EntryIsDeleted(*entry)) {
			// entry is deleted
476
477
		} else if(EntryGetHash(self, *entry) == hash) {
			if(KeysEqual(self, GetKey(EntryGetValue(*entry)), key)) {
Matthias Braun's avatar
Matthias Braun committed
478
				EntrySetDeleted(*entry);
479
480
				self->num_deleted++;
				self->consider_shrink = 1;
Matthias Braun's avatar
Matthias Braun committed
481
482
483
484
485
486
487
488
489
490
491
492
493
494
				return;
			}
		}

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

/**
 * Initializes hashset with a specific size
 * @internal
 */
Andreas Schösser's avatar
Andreas Schösser committed
495
static INLINE
496
void init_size(HashSet *self, size_t initial_size)
Matthias Braun's avatar
Matthias Braun committed
497
498
499
500
{
	if(initial_size < 4)
		initial_size = 4;

501
502
503
504
505
506
	self->entries = Alloc(initial_size);
	SetRangeEmpty(self->entries, initial_size);
	self->num_buckets = initial_size;
	self->consider_shrink = 0;
	self->num_elements = 0;
	self->num_deleted = 0;
Matthias Braun's avatar
Matthias Braun committed
507
#ifndef NDEBUG
508
	self->entries_version = 0;
Matthias Braun's avatar
Matthias Braun committed
509
510
#endif

511
	reset_thresholds(self);
Matthias Braun's avatar
Matthias Braun committed
512
513
514
515
516
517
}

/**
 * Initialializes a hashset with the default size. The memory for the set has to
 * already allocated.
 */
518
void hashset_init(HashSet *self)
Matthias Braun's avatar
Matthias Braun committed
519
{
520
	init_size(self, HT_MIN_BUCKETS);
Matthias Braun's avatar
Matthias Braun committed
521
522
523
524
525
526
}

/**
 * Destroys a hashset, freeing all used memory (except the memory for the
 * HashSet struct itself).
 */
527
void hashset_destroy(HashSet *self)
Matthias Braun's avatar
Matthias Braun committed
528
{
529
	Free(self->entries);
Matthias Braun's avatar
Matthias Braun committed
530
#ifndef NDEBUG
531
	self->entries = NULL;
Matthias Braun's avatar
Matthias Braun committed
532
533
534
535
536
537
#endif
}

/**
 * Initializes a hashset expecting expected_element size
 */
538
void hashset_init_size(HashSet *self, size_t expected_elements)
Matthias Braun's avatar
Matthias Braun committed
539
540
541
542
543
544
545
546
{
	size_t needed_size;
	size_t po2size;

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

547
	needed_size = expected_elements * (int)(1.0 / HT_OCCUPANCY_FLT);
Matthias Braun's avatar
Matthias Braun committed
548
	po2size = ceil_po2(needed_size);
549
	init_size(self, po2size);
Matthias Braun's avatar
Matthias Braun committed
550
551
552
553
554
555
556
}

/**
 * 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
 */
557
void hashset_iterator_init(HashSetIterator *self, const HashSet *hashset)
Matthias Braun's avatar
Matthias Braun committed
558
{
559
560
	self->current_bucket = hashset->entries - 1;
	self->end = hashset->entries + hashset->num_buckets;
Matthias Braun's avatar
Matthias Braun committed
561
#ifndef NDEBUG
562
563
	self->set = hashset;
	self->entries_version = hashset->entries_version;
Matthias Braun's avatar
Matthias Braun committed
564
565
566
567
568
569
570
571
#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
 */
572
ValueType hashset_iterator_next(HashSetIterator *self)
Matthias Braun's avatar
Matthias Braun committed
573
{
574
575
	HashSetEntry *current_bucket = self->current_bucket;
	HashSetEntry *end = self->end;
Matthias Braun's avatar
Matthias Braun committed
576
577
578
579
580

	if(current_bucket >= end)
		return NullValue;

	/* using hashset_insert or hashset_remove is not allowed while iterating */
581
	assert(self->entries_version == self->set->entries_version);
Matthias Braun's avatar
Matthias Braun committed
582
583
584
585
586
587
588
589
590

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

	if(current_bucket >= end)
		return NullValue;

591
	self->current_bucket = current_bucket;
Matthias Braun's avatar
Matthias Braun committed
592
593
594
595
596
597
598
	return EntryGetValue(*current_bucket);
}

/**
 * Removes the element the iterator points to. Removing an element a second time
 * has no result.
 */
599
void hashset_remove_iterator(HashSet *self, const HashSetIterator *iter)
Matthias Braun's avatar
Matthias Braun committed
600
601
602
603
{
	HashSetEntry *entry = iter->current_bucket;

	/* iterator_next needs to have been called at least once */
604
	assert(entry >= self->entries);
Matthias Braun's avatar
Matthias Braun committed
605
	/* needs to be on a valid element */
606
	assert(entry < self->entries + self->num_buckets);
Matthias Braun's avatar
Matthias Braun committed
607
608
609
610
611

	if(EntryIsDeleted(*entry))
		return;

	EntrySetDeleted(*entry);
612
613
	self->num_deleted++;
	self->consider_shrink = 1;
Matthias Braun's avatar
Matthias Braun committed
614
615
616
}

#endif