-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmap.c
More file actions
62 lines (47 loc) · 1.12 KB
/
map.c
File metadata and controls
62 lines (47 loc) · 1.12 KB
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
#include "map.h"
map *create_map() {
map *m = malloc(sizeof(map));
pair *hash_table = m->hash_table;
for (int i = 0; i < TABLE_SIZE; ++i) {
pair *p = &hash_table[i];
p->key = NULL;
p->value = NULL;
}
return m;
}
unsigned int hash(char *input) {
unsigned long hash = 5381;
int c;
while ((c = *input++))
hash = ((hash << 5) + hash) + c;
return hash % TABLE_SIZE;
}
int map_contains(map *map, char *input) {
unsigned long h = hash(input);
pair *hash_table = map->hash_table;
return hash_table[h].key != NULL;
}
char *map_get(map *map, char *input) {
unsigned long h = hash(input);
pair *hash_table = map->hash_table;
return hash_table[h].value;
}
void map_delete(map *map) {
pair *hash_table = map->hash_table;
for (int i = 0; i < TABLE_SIZE; ++i) {
pair *p = &hash_table[i];
if (p->key) {
free(p->key);
free(p->value);
}
}
free(map);
map = NULL;
}
void map_insert(map *map, char *key, char *value) {
unsigned long h = hash(key);
pair *hash_table = map->hash_table;
pair *p = &hash_table[h];
p->key = strdup(key);
p->value = strdup(value);
}