-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmap.c
More file actions
85 lines (76 loc) · 1.76 KB
/
map.c
File metadata and controls
85 lines (76 loc) · 1.76 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include "map.h"
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
Map *new_map() {
Map *m = (Map *)malloc(sizeof(Map));
m->root = NULL;
m->count = 0;
return m;
}
MapPair *new_map_pair(const char *key, void *value) {
MapPair *pair = (MapPair *)malloc(sizeof(MapPair));
pair->left = NULL;
pair->right = NULL;
pair->key = key;
pair->value = value;
return pair;
}
// TODO:free memory, do nothing now.
void free_map(Map *map) {}
void map_insert(Map *map, const char *key, void *value) {
map->count += 1;
if (map->root == NULL) {
map->root = new_map_pair(key, value);
return;
}
MapPair *pair = map->root;
while (1) {
int r = strcmp(pair->key, key);
if (r < 0) {
if (pair->right == NULL) {
MapPair *np = new_map_pair(key, value);
pair->right = np;
return;
} else {
pair = pair->right;
}
} else if (r > 0) {
if (pair->left == NULL) {
MapPair *np = new_map_pair(key, value);
pair->left = np;
return;
} else {
pair = pair->left;
}
} else {
pair->value = value;
return;
}
}
}
MapPair *map_get(Map *map, const char *key) {
MapPair *start = map->root;
while (start != NULL) {
int r = strcmp(start->key, key);
if (r < 0) {
start = start->right;
} else if (r > 0) {
start = start->left;
} else {
return start;
}
}
return start;
}
void _map_foreach_kernel(MapPair *pair, map_handler handler, void *data) {
if (pair == NULL) {
return;
}
handler(pair, data);
_map_foreach_kernel(pair->left, handler, data);
_map_foreach_kernel(pair->right, handler, data);
}
void map_foreach(Map *map, map_handler handler, void *data) {
_map_foreach_kernel(map->root, handler, data);
}