utils/macros.h: Add <ctype.h> and `foocmp' helper macros.
[mLib] / struct / t / sym-test.c
1 #include <assert.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5
6 #include "macros.h"
7 #include "sym.h"
8
9 typedef struct word {
10 sym_base _b;
11 int i;
12 } word;
13
14 static int cmp(const void *a, const void *b)
15 {
16 const word *const *v = b;
17 const word *const *w = a;
18 return (strcmp(SYM_NAME(*w), SYM_NAME(*v)));
19 }
20
21 int main(void)
22 {
23 char buf[256];
24 char *p;
25 sym_table t;
26 size_t n = 0, j;
27
28 sym_create(&t);
29
30 while (fgets(buf, sizeof(buf), stdin)) {
31 /* printf("+++ %s", buf); */
32 buf[strlen(buf) - 1] = 0;
33 p = strtok(buf, " ");
34
35 if (STRCMP(p, ==, "set")) {
36 char *k = strtok(0, " ");
37 int i = atoi(strtok(0, " "));
38 unsigned f;
39 word *w = sym_find(&t, k, -1, sizeof(word), &f);
40 w->i = i;
41 if (!f)
42 n++;
43 } else if (STRCMP(p, ==, "get")) {
44 char *k = strtok(0, " ");
45 word *w = sym_find(&t, k, -1, 0, 0);
46 if (w)
47 printf("%i\n", w->i);
48 else
49 puts("*MISSING*");
50 } else if (STRCMP(p, ==, "del")) {
51 char *k = strtok(0, " ");
52 word *w = sym_find(&t, k, -1, 0, 0);
53 if (w) {
54 sym_remove(&t, w);
55 n--;
56 } else
57 puts("*MISSING*");
58 } else if (STRCMP(p, ==, "count")) {
59 printf("%lu\n", (unsigned long)n);
60 } else if (STRCMP(p, ==, "show")) {
61 sym_iter i;
62 word *w;
63 word **v, **vv;
64
65 if (!n)
66 puts("*EMPTY*");
67 else {
68 v = malloc(n * sizeof(*v));
69 if (!v) {
70 puts("*NOMEM*");
71 continue;
72 }
73 for (vv = v, sym_mkiter(&i, &t), j = 0;
74 (w = sym_next(&i)) != 0;
75 vv++, j++) {
76 assert(j < n);
77 *vv = w;
78 }
79 assert(j == n);
80 qsort(v, n, sizeof(*v), cmp);
81 printf("%s:%i", SYM_NAME(*v), (*v)->i);
82 for (vv = v + 1; --j; vv++)
83 printf(" %s:%i", SYM_NAME(*vv), (*vv)->i);
84 free(v);
85 putchar('\n');
86 }
87 } else
88 puts("*BAD*");
89 /* printf("--- %d\n", n); */
90 }
91
92 sym_destroy(&t);
93 return (0);
94 }