-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhashmap.c
78 lines (74 loc) · 1.83 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
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdio.h>
#include "hashmap.h"
hashmap* create_hashmap(const char* key, const char* value)
{
hashmap* tmp = malloc(sizeof(hashmap));
tmp->value = malloc(strlen(value)+1);
assert(tmp->value != NULL);
strcpy(tmp->value, value);
tmp->key = malloc(strlen(key)+1);
assert(tmp->key != NULL);
strcpy(tmp->key, key);
tmp->next = NULL;
return tmp;
}
const char* get_value(hashmap* container, const char* key)
{
if(container) {
hashmap* current = container;
while(current) {
if(strcmp(key, current->key) == 0) {
return current->value;
}
current = current->next;
}
}
return NULL;
}
int key_exists(hashmap* container, const char* key)
{
if(container) {
hashmap* current = container;
while(current) {
if(strcmp(key, current->key) == 0) {
return 1;
}
}
}
return 0;
}
void set_value(hashmap* container, const char* key, const char* value)
{
hashmap* current = container;
hashmap* previous = NULL;
while(current && strcmp(current->key, key) != 0) {
previous = current;
current = current->next;
}
if(current) {
free(current->value);
current->value = malloc(strlen(value)+1);
assert(current->value != NULL);
strcpy(current->value, value);
}
else {
previous->next = create_hashmap(key, value);
}
}
void destroy_hashmap(hashmap* container)
{
if(container) {
hashmap* current = container;
hashmap* next = NULL;
while(current) {
next = current->next;
free(current->key);
free(current->value);
free(current);
current = next;
}
}
}