chiark / gitweb /
Release 2.3.1.
[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 "sym.h"
7
8 typedef struct word {
9   sym_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;
17   return (strcmp(SYM_NAME(*w), SYM_NAME(*v)));
18 }
19
20 int main(void)
21 {
22   char buf[256];
23   char *p;
24   sym_table t;
25   size_t n = 0, j;
26
27   sym_create(&t);
28
29   while (fgets(buf, sizeof(buf), stdin)) {
30 /*     printf("+++ %s", buf); */
31     buf[strlen(buf) - 1] = 0;
32     p = strtok(buf, " ");
33
34     if (strcmp(p, "set") == 0) {
35       char *k = strtok(0, " ");
36       int i = atoi(strtok(0, " "));
37       unsigned f;
38       word *w = sym_find(&t, k, -1, sizeof(word), &f);
39       w->i = i;
40       if (!f)
41         n++;
42     } else if (strcmp(p, "get") == 0) {
43       char *k = strtok(0, " ");
44       word *w = sym_find(&t, k, -1, 0, 0);
45       if (w)
46         printf("%i\n", w->i);
47       else
48         puts("*MISSING*");
49     } else if (strcmp(p, "del") == 0) {
50       char *k = strtok(0, " ");
51       word *w = sym_find(&t, k, -1, 0, 0);
52       if (w) {
53         sym_remove(&t, w);
54         n--;
55       } else
56         puts("*MISSING*");
57     } else if (strcmp(p, "count") == 0) {
58       printf("%lu\n", (unsigned long)n);
59     } else if (strcmp(p, "show") == 0) {
60       sym_iter i;
61       word *w;
62       word **v, **vv;
63
64       if (!n)
65         puts("*EMPTY*");
66       else {
67         v = malloc(n * sizeof(*v));
68         if (!v) {
69           puts("*NOMEM*");
70           continue;
71         }
72         for (vv = v, sym_mkiter(&i, &t), j = 0;
73              (w = sym_next(&i)) != 0;
74              vv++, j++) {
75           assert(j < n);
76           *vv = w;
77         }
78         assert(j == n);
79         qsort(v, n, sizeof(*v), cmp);
80         printf("%s:%i", SYM_NAME(*v), (*v)->i);
81         for (vv = v + 1; --j; vv++)
82           printf(" %s:%i", SYM_NAME(*vv), (*vv)->i);
83         free(v);
84         putchar('\n');
85       }
86     } else
87       puts("*BAD*");
88 /*     printf("--- %d\n", n); */
89   }
90
91   sym_destroy(&t);
92   return (0);
93 }