[go: up one dir, main page]

File: hashmap.c

package info (click to toggle)
uftrace 0.18.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,356 kB
  • sloc: ansic: 49,770; python: 11,181; asm: 837; makefile: 769; sh: 637; cpp: 627; javascript: 191
file content (427 lines) | stat: -rw-r--r-- 8,966 bytes parent folder | download | duplicates (3)
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
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
/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <errno.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>

#include "hashmap.h"
#include "utils.h"

typedef pthread_mutex_t mutex_t;
typedef struct Entry Entry;

struct Entry {
	void *key;
	hash_t hash;
	void *value;
	Entry *next;
};

struct Hashmap {
	Entry **buckets;
	size_t bucket_count;
	hash_t (*hash)(void *key);
	bool (*equals)(void *keyA, void *keyB);
	mutex_t lock;
	size_t size;
};

Hashmap *hashmap_create(size_t initial_capacity, hash_t (*hash)(void *key),
			bool (*equals)(void *keyA, void *keyB))
{
	Hashmap *map;
	size_t minimum_bucket_count;

	ASSERT(hash != NULL);
	ASSERT(equals != NULL);

	map = malloc(sizeof(Hashmap));
	if (map == NULL) {
		return NULL;
	}

	// 0.75 load factor.
	minimum_bucket_count = initial_capacity * 4 / 3;
	map->bucket_count = 1;
	while (map->bucket_count <= minimum_bucket_count) {
		// Bucket count must be power of 2.
		map->bucket_count <<= 1;
	}

	map->buckets = calloc(map->bucket_count, sizeof(Entry *));
	if (map->buckets == NULL) {
		free(map);
		return NULL;
	}

	map->size = 0;
	map->hash = hash;
	map->equals = equals;

	pthread_mutex_init(&map->lock, NULL);

	return map;
}

/**
 * Hashes the given key.
 */
static hash_t hash_key(Hashmap *map, void *key)
{
	hash_t h = map->hash(key);
	return h;
}

size_t hashmap_size(Hashmap *map)
{
	return map->size;
}

static inline size_t calculate_index(size_t bucket_count, int hash)
{
	return ((size_t)hash) & (bucket_count - 1);
}

static void expand_if_necessary(Hashmap *map)
{
	// If the load factor exceeds 0.75...
	if (map->size > (map->bucket_count * 3 / 4)) {
		// Start off with a 0.33 load factor.
		size_t new_bucket_count = map->bucket_count << 1;
		Entry **new_buckets;
		size_t i;

		new_buckets = calloc(new_bucket_count, sizeof(Entry *));
		if (new_buckets == NULL) {
			// Abort expansion.
			return;
		}

		// Move over existing entries.
		for (i = 0; i < map->bucket_count; i++) {
			Entry *entry = map->buckets[i];
			while (entry != NULL) {
				Entry *next = entry->next;
				size_t index = calculate_index(new_bucket_count, entry->hash);
				entry->next = new_buckets[index];
				new_buckets[index] = entry;
				entry = next;
			}
		}

		// Copy over internals.
		free(map->buckets);
		map->buckets = new_buckets;
		map->bucket_count = new_bucket_count;
	}
}

void hashmap_lock(Hashmap *map)
{
	pthread_mutex_lock(&map->lock);
}

void hashmap_unlock(Hashmap *map)
{
	pthread_mutex_unlock(&map->lock);
}

void hashmap_free(Hashmap *map)
{
	size_t i;

	for (i = 0; i < map->bucket_count; i++) {
		Entry *entry = map->buckets[i];
		while (entry != NULL) {
			Entry *next = entry->next;
			free(entry);
			entry = next;
		}
	}
	free(map->buckets);
	pthread_mutex_destroy(&map->lock);
	free(map);
}

hash_t hashmap_hash(void *key, size_t key_size)
{
	hash_t h = key_size;
	char *data = (char *)key;
	size_t i;

	for (i = 0; i < key_size; i++) {
		h = h * 31 + *data;
		data++;
	}
	return h;
}

static Entry *create_entry(void *key, int hash, void *value)
{
	Entry *entry = malloc(sizeof(Entry));

	if (entry == NULL) {
		return NULL;
	}
	entry->key = key;
	entry->hash = hash;
	entry->value = value;
	entry->next = NULL;
	return entry;
}

static inline bool equal_keys(void *keyA, int hashA, void *keyB, int hashB,
			      bool (*equals)(void *, void *))
{
	if (keyA == keyB) {
		return true;
	}
	if (hashA != hashB) {
		return false;
	}
	return equals(keyA, keyB);
}

void *hashmap_put(Hashmap *map, void *key, void *value)
{
	hash_t hash = hash_key(map, key);
	size_t index = calculate_index(map->bucket_count, hash);

	Entry **p = &(map->buckets[index]);
	while (true) {
		Entry *current = *p;

		// Add a new entry.
		if (current == NULL) {
			*p = create_entry(key, hash, value);
			if (*p == NULL) {
				errno = ENOMEM;
				return NULL;
			}
			map->size++;
			expand_if_necessary(map);
			return value;
		}

		// Replace existing entry.
		if (equal_keys(current->key, current->hash, key, hash, map->equals)) {
			void *oldValue = current->value;
			current->value = value;
			return oldValue;
		}

		// Move to next entry.
		p = &current->next;
	}
}

void *hashmap_get(Hashmap *map, void *key)
{
	hash_t hash = hash_key(map, key);
	size_t index = calculate_index(map->bucket_count, hash);

	Entry *entry = map->buckets[index];
	while (entry != NULL) {
		if (equal_keys(entry->key, entry->hash, key, hash, map->equals)) {
			return entry->value;
		}
		entry = entry->next;
	}

	return NULL;
}

bool hashmap_contains_key(Hashmap *map, void *key)
{
	hash_t hash = hash_key(map, key);
	size_t index = calculate_index(map->bucket_count, hash);

	Entry *entry = map->buckets[index];
	while (entry != NULL) {
		if (equal_keys(entry->key, entry->hash, key, hash, map->equals)) {
			return true;
		}
		entry = entry->next;
	}

	return false;
}

void *hashmap_memoize(Hashmap *map, void *key, void *(*initial_value)(void *key, void *context),
		      void *context)
{
	hash_t hash = hash_key(map, key);
	size_t index = calculate_index(map->bucket_count, hash);

	Entry **p = &(map->buckets[index]);
	while (true) {
		Entry *current = *p;

		// Add a new entry.
		if (current == NULL) {
			void *value;

			*p = create_entry(key, hash, NULL);
			if (*p == NULL) {
				errno = ENOMEM;
				return NULL;
			}

			value = initial_value(key, context);
			(*p)->value = value;
			map->size++;
			expand_if_necessary(map);
			return value;
		}

		// Return existing value.
		if (equal_keys(current->key, current->hash, key, hash, map->equals)) {
			return current->value;
		}

		// Move to next entry.
		p = &current->next;
	}
}

void *hashmap_remove(Hashmap *map, void *key)
{
	hash_t hash = hash_key(map, key);
	size_t index = calculate_index(map->bucket_count, hash);

	// Pointer to the current entry.
	Entry **p = &(map->buckets[index]);
	Entry *current;
	while ((current = *p) != NULL) {
		if (equal_keys(current->key, current->hash, key, hash, map->equals)) {
			void *value = current->value;
			*p = current->next;
			free(current);
			map->size--;
			return value;
		}

		p = &current->next;
	}

	return NULL;
}

void hashmap_for_each(Hashmap *map, bool (*callback)(void *key, void *value, void *context),
		      void *context)
{
	size_t i;
	for (i = 0; i < map->bucket_count; i++) {
		Entry *entry = map->buckets[i];
		while (entry != NULL) {
			Entry *next = entry->next;
			if (!callback(entry->key, entry->value, context)) {
				return;
			}
			entry = next;
		}
	}
}

size_t hashmap_current_capacity(Hashmap *map)
{
	size_t bucket_count = map->bucket_count;
	return bucket_count * 3 / 4;
}

size_t hashmap_count_collisions(Hashmap *map)
{
	size_t collisions = 0;
	size_t i;
	for (i = 0; i < map->bucket_count; i++) {
		Entry *entry = map->buckets[i];
		while (entry != NULL) {
			if (entry->next != NULL) {
				collisions++;
			}
			entry = entry->next;
		}
	}
	return collisions;
}

hash_t hashmap_default_hash(void *key)
{
	return *((hash_t *)key);
}

bool hashmap_default_equals(void *keyA, void *keyB)
{
	hash_t a = *((hash_t *)keyA);
	hash_t b = *((hash_t *)keyB);
	return a == b;
}

hash_t hashmap_ptr_hash(void *key)
{
	return (uintptr_t)key;
}

bool hashmap_ptr_equals(void *keyA, void *keyB)
{
	hash_t a = (uintptr_t)keyA;
	hash_t b = (uintptr_t)keyB;
	return a == b;
}

#ifdef UNIT_TEST
#include "utils/utils.h"

TEST_CASE(hashmap_expand)
{
	int orig_size = 3;
	Hashmap *hmap = hashmap_create(orig_size, hashmap_default_hash, hashmap_default_equals);
	size_t count = hmap->bucket_count;
	hash_t keys[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	char str_value[] = "string value longer than the keys";
	int i;

	pr_dbg("add entries not to expand yet\n");
	for (i = 0; i < orig_size; i++) {
		hashmap_put(hmap, &keys[i], &str_value[i]);
	}
	TEST_EQ(hmap->bucket_count, count);

	pr_dbg("add more entries to expand\n");
	for (i = 0; i < ARRAY_SIZE(keys); i++) {
		if (i < orig_size) {
			TEST_EQ(hashmap_contains_key(hmap, &keys[i]), true);
			continue;
		}
		hashmap_put(hmap, &keys[i], &str_value[i]);
	}
	pr_dbg("now hmap should be expanded\n");
	TEST_GT(hmap->bucket_count, count);

	pr_dbg("check keys return correct values\n");
	for (i = 0; i < ARRAY_SIZE(keys); i++) {
		void *val = hashmap_get(hmap, &keys[i]);
		TEST_NE(val, NULL);
		TEST_EQ(val, &str_value[i]);
	}
	hashmap_free(hmap);
	return TEST_OK;
}
#endif /* UNIT_TEST */