ece42f68 |
1 | #include <stdio.h> |
2 | #include <stdlib.h> |
3 | #include <string.h> |
4 | |
5 | #include "assoc.h" |
6 | #include "atom.h" |
7 | |
8 | typedef struct word { |
9 | assoc_base _b; |
10 | int i; |
11 | } word; |
12 | |
13 | static int cmp(const void *a, const void *b) |
14 | { |
15 | const word *const *v = b; |
16 | const word *const *w = a; |
90407c44 |
17 | return (strcmp(ATOM_NAME(ASSOC_ATOM(*w)), ATOM_NAME(ASSOC_ATOM(*v)))); |
ece42f68 |
18 | } |
19 | |
20 | int main(void) |
21 | { |
22 | char buf[256]; |
23 | char *p; |
24 | atom_table at; |
25 | assoc_table t; |
26 | size_t n = 0; |
27 | |
28 | atom_createtable(&at); |
29 | assoc_create(&t); |
30 | |
31 | while (fgets(buf, sizeof(buf), stdin)) { |
32 | buf[strlen(buf) - 1] = 0; |
33 | /* printf("# %s\n", buf); */ |
34 | p = strtok(buf, " "); |
35 | |
36 | if (strcmp(p, "set") == 0) { |
37 | char *k = strtok(0, " "); |
38 | int i = atoi(strtok(0, " ")); |
39 | unsigned f; |
40 | word *w = assoc_find(&t, atom_intern(&at, k), sizeof(word), &f); |
41 | w->i = i; |
42 | if (!f) |
43 | n++; |
44 | } else if (strcmp(p, "get") == 0) { |
45 | char *k = strtok(0, " "); |
46 | word *w = assoc_find(&t, atom_intern(&at, k), 0, 0); |
47 | if (w) |
48 | printf("%i\n", w->i); |
49 | else |
50 | puts("*MISSING*"); |
51 | } else if (strcmp(p, "del") == 0) { |
52 | char *k = strtok(0, " "); |
53 | word *w = assoc_find(&t, atom_intern(&at, k), 0, 0); |
54 | if (w) { |
55 | assoc_remove(&t, w); |
56 | n--; |
57 | } else |
58 | puts("*MISSING*"); |
59 | } else if (strcmp(p, "count") == 0) { |
60 | printf("%i\n", n); |
61 | } else if (strcmp(p, "show") == 0) { |
62 | assoc_iter i; |
63 | word *w; |
64 | word **v, **vv; |
65 | |
66 | if (!n) |
67 | puts("*EMPTY*"); |
68 | else { |
69 | v = malloc(n * sizeof(*v)); |
70 | if (!v) { |
71 | puts("*NOMEM*"); |
72 | continue; |
73 | } |
74 | for (vv = v, assoc_mkiter(&i, &t); (w = assoc_next(&i)) != 0; vv++) |
75 | *vv = w; |
76 | qsort(v, n, sizeof(*v), cmp); |
90407c44 |
77 | printf("%s:%i", ATOM_NAME(ASSOC_ATOM(*v)), (*v)->i); |
ece42f68 |
78 | for (vv = v + 1; --n; vv++) |
90407c44 |
79 | printf(" %s:%i", ATOM_NAME(ASSOC_ATOM(*vv)), (*vv)->i); |
ece42f68 |
80 | free(v); |
81 | putchar('\n'); |
82 | } |
83 | } else |
84 | puts("*BAD*"); |
85 | } |
86 | |
87 | assoc_destroy(&t); |
90407c44 |
88 | atom_destroytable(&at); |
ece42f68 |
89 | return (0); |
90 | } |