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