chiark / gitweb /
Infrastructure: Switch testing over to Autotest.
[mLib] / struct / t / assoc-test.c
CommitLineData
7cf5c72a 1#include <assert.h>
ece42f68 2#include <stdio.h>
3#include <stdlib.h>
4#include <string.h>
5
6#include "assoc.h"
7#include "atom.h"
8
9typedef struct word {
10 assoc_base _b;
11 int i;
12} word;
13
14static int cmp(const void *a, const void *b)
15{
16 const word *const *v = b;
17 const word *const *w = a;
90407c44 18 return (strcmp(ATOM_NAME(ASSOC_ATOM(*w)), ATOM_NAME(ASSOC_ATOM(*v))));
ece42f68 19}
20
21int main(void)
22{
23 char buf[256];
24 char *p;
25 atom_table at;
26 assoc_table t;
7cf5c72a 27 size_t n = 0, j;
ece42f68 28
29 atom_createtable(&at);
30 assoc_create(&t);
31
32 while (fgets(buf, sizeof(buf), stdin)) {
7cf5c72a 33/* printf("+++ %s", buf); */
ece42f68 34 buf[strlen(buf) - 1] = 0;
ece42f68 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 }
7cf5c72a
MW
75 for (vv = v, assoc_mkiter(&i, &t), j = 0;
76 (w = assoc_next(&i)) != 0;
77 vv++, j++) {
78 assert(j < n);
ece42f68 79 *vv = w;
7cf5c72a
MW
80 }
81 assert(j == n);
ece42f68 82 qsort(v, n, sizeof(*v), cmp);
90407c44 83 printf("%s:%i", ATOM_NAME(ASSOC_ATOM(*v)), (*v)->i);
7cf5c72a 84 for (vv = v + 1; --j; vv++)
90407c44 85 printf(" %s:%i", ATOM_NAME(ASSOC_ATOM(*vv)), (*vv)->i);
ece42f68 86 free(v);
87 putchar('\n');
88 }
89 } else
90 puts("*BAD*");
7cf5c72a 91/* printf("--- %d\n", n); */
ece42f68 92 }
93
94 assoc_destroy(&t);
90407c44 95 atom_destroytable(&at);
ece42f68 96 return (0);
97}