chiark / gitweb /
New test structure for symbol tables.
[mLib] / sym-test.c
diff --git a/sym-test.c b/sym-test.c
new file mode 100644 (file)
index 0000000..dea3e60
--- /dev/null
@@ -0,0 +1,88 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "sub.h"
+#include "sym.h"
+
+typedef struct word {
+  sym_base _b;
+  int i;
+} word;
+
+static int cmp(const void *a, const void *b)
+{
+  const word *const *v = b;
+  const word *const *w = a;
+  return (strcmp(SYM_NAME(*w), SYM_NAME(*v)));
+}
+
+int main(void)
+{
+  char buf[256];
+  char *p;
+  sym_table t;
+  size_t n = 0;
+
+  sub_init();
+  sym_create(&t);
+
+  while (fgets(buf, sizeof(buf), stdin)) {
+    buf[strlen(buf) - 1] = 0;
+/*     printf("# %s\n", buf); */
+    p = strtok(buf, " ");
+
+    if (strcmp(p, "set") == 0) {
+      char *k = strtok(0, " ");
+      int i = atoi(strtok(0, " "));
+      unsigned f;
+      word *w = sym_find(&t, k, -1, sizeof(word), &f);
+      w->i = i;
+      if (!f)
+       n++;
+    } else if (strcmp(p, "get") == 0) {
+      char *k = strtok(0, " ");
+      word *w = sym_find(&t, k, -1, 0, 0);
+      if (w)
+       printf("%i\n", w->i);
+      else
+       puts("*MISSING*");
+    } else if (strcmp(p, "del") == 0) {
+      char *k = strtok(0, " ");
+      word *w = sym_find(&t, k, -1, 0, 0);
+      if (w) {
+       sym_remove(&t, w);
+       n--;
+      } else
+       puts("*MISSING*");
+    } else if (strcmp(p, "count") == 0) {
+      printf("%i\n", n);
+    } else if (strcmp(p, "show") == 0) {
+      sym_iter i;
+      word *w;
+      word **v, **vv;
+
+      if (!n)
+       puts("*EMPTY*");
+      else {
+       v = malloc(n * sizeof(*v));
+       if (!v) {
+         puts("*NOMEM*");
+         continue;
+       }
+       for (vv = v, sym_mkiter(&i, &t); (w = sym_next(&i)) != 0; vv++)
+         *vv = w;
+       qsort(v, n, sizeof(*v), cmp);
+       printf("%s:%i", SYM_NAME(*v), (*v)->i);
+       for (vv = v + 1; --n; vv++)
+         printf(" %s:%i", SYM_NAME(*vv), (*vv)->i);
+       free(v);
+       putchar('\n');
+      }
+    } else
+      puts("*BAD*");
+  }
+
+  sym_destroy(&t);
+  return (0);
+}