-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhashmap.c
118 lines (109 loc) · 2.31 KB
/
hashmap.c
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
#include "hashmap.h"
#include "utilities.h"
#include <stdlib.h>
Hash hash(HashMap * map, Key key)
{
if (key < 0) {
return -(key % map->array_size);
}
return key % map->array_size;
}
void init_HashMap(HashMap * map)
{
map->array_size = 32;
map->data = calloc(sizeof(void *), map->array_size);
map->size = 0;
}
void resize_HashMap(HashMap * map, int newSize)
{
INFO("Resizing hashmap to size %d", newSize);
HashMapNode **oldNodes = map->data;
int oldSize = map->size;
map->data = malloc(sizeof(HashMapNode *) * newSize);
map->size = 0;
map->array_size = newSize;
for (int i = 0; i < oldSize; ++i) {
HashMapNode *tmp = oldNodes[i];
while (tmp) {
insert_into_HashMap(map, tmp->key, tmp->value);
tmp = tmp->next;
}
}
free(oldNodes);
}
void insert_into_HashMap(HashMap * map, Key key, void *value)
{
/* Keep the load factor under 0.75 (3/4) */
if (3 * map->array_size < 4 * map->size) {
resize_HashMap(map, map->array_size * 2);
}
Hash h = hash(map, key);
HashMapNode *list = map->data[h];
HashMapNode *node = calloc(sizeof(HashMapNode), 1);
HashMapNode *tmp = list;
while (tmp) {
if (tmp->key == key) {
tmp->value = value;
return;
}
tmp = tmp->next;
}
node->key = key;
node->value = value;
node->next = list;
map->data[h] = node;
}
void *get_from_HashMap(HashMap * map, Key key)
{
Hash h = hash(map, key);
HashMapNode *list = map->data[h];
HashMapNode *tmp = list;
while (tmp) {
if (tmp->key == key) {
return tmp->value;
}
tmp = tmp->next;
}
return NULL;
}
void delete_from_HashMap(HashMap * map, Key key)
{
Hash h = hash(map, key);
HashMapNode *list = map->data[h];
HashMapNode *previous = NULL;
HashMapNode *tmp = list;
while (tmp) {
if (tmp->key == key) {
if (previous) {
previous->next = tmp->next;
}
free(tmp);
}
previous = tmp;
tmp = tmp->next;
}
}
void delete_HashMap(HashMap * map)
{
for (int i = 0; i < map->array_size; ++i) {
HashMapNode *list = map->data[i];
while (list) {
HashMapNode *next = list->next;
free(list);
list = next;
}
}
free(map->data);
}
void for_each_in_HashMap(HashMap * map,
void (*fn)(Key key, void *value, void *extra),
void *extra)
{
for (int i = 0; i < map->array_size; ++i) {
HashMapNode *list = map->data[i];
while (list) {
fn(list->key, list->value, extra);
list = list->next;
}
}
}