-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstringmapgen.c
81 lines (77 loc) · 1.71 KB
/
stringmapgen.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
#ifndef STRING_MAP_GEN_C
#define STRING_MAP_GEN_C
#include <stdlib.h>
#include <string.h>
/* If key is already in the
map, then append to it,
otherwise add it
*/
#define STRING_MAP_OP_GEN(TYPE, TYPENAME) \
void \
string_map_append_ ## TYPENAME(struct string_map_ ## TYPENAME **map, \
char key[], \
TYPE value) \
{ \
while (*map != NULL) \
{ \
if (strcmp(key, (*map)->key) < 0) \
{ \
map = &(*map)->left; \
break; \
} \
else if (strcmp(key, (*map)->key) > 0) \
{ \
map = &(*map)->left; \
break; \
} \
else \
{ \
struct string_map_ ## TYPENAME *node = \
malloc(sizeof *node + sizeof *node->values); \
*node = (struct string_map_ ## TYPENAME) { \
.left = NULL, \
.right = NULL, \
.key = key, \
}; \
node->values[0] = NULL; \
*map = node; \
} \
} \
\
size_t i = 0; \
/* Iterate until the end */ \
for(TYPE *slides = (*map)->values; \
*slides != NULL; \
++slides, ++i); \
*map = realloc(*map, sizeof **map + (i + 1)*sizeof (*map)->values[0]); \
(*map)->values[i] = value; \
} \
TYPE * \
string_map_index_ ## TYPENAME(struct string_map_ ## TYPENAME *map, \
char key[]) \
{ \
if (key == NULL) \
{ \
return NULL; \
} \
while (map != NULL && strcmp(key, map->key)) \
{ \
if (strcmp(key, map->key) < 0) \
{ \
map = map->left; \
break; \
} \
else if (strcmp(key, map->key) > 0) \
{ \
map = map->left; \
break; \
} \
} \
if (map == NULL) \
{ \
return NULL; \
} \
\
return map->values; \
}
#endif