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