After incrementing an unsigned char value, don't cast it back to
[sgt/agedu] / trie.c
diff --git a/trie.c b/trie.c
index 1344bdf..48302db 100644 (file)
--- a/trie.c
+++ b/trie.c
@@ -2,17 +2,8 @@
  * trie.c: implementation of trie.h.
  */
 
-#include <assert.h>
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <errno.h>
-
-#include <sys/types.h>
-#include <unistd.h>
-
 #include "agedu.h"
-#include "malloc.h"
+#include "alloc.h"
 #include "trie.h"
 
 #define alignof(typ) ( offsetof(struct { char c; typ t; }, t) )
@@ -24,9 +15,9 @@
  */
 static int trieccmp(unsigned char a, unsigned char b)
 {
-    a = (a == '\0' ? '\0' : a == pathsep ? '\1' : a+1);
-    b = (b == '\0' ? '\0' : b == pathsep ? '\1' : b+1);
-    return (int)a - (int)b;
+    int ia = (a == '\0' ? '\0' : a == pathsep ? '\1' : a+1);
+    int ib = (b == '\0' ? '\0' : b == pathsep ? '\1' : b+1);
+    return ia - ib;
 }
 
 static int triencmp(const char *a, size_t alen,
@@ -227,7 +218,8 @@ static off_t triebuild_unwind(triebuild *tb, int targetdepth, int *outcount)
     while (depth > targetdepth) {
        int odepth = depth;
        while (depth > targetdepth &&
-              (depth-1 > tb->switchsize || tb->switches[depth-1].len == 0))
+              (depth-1 > tb->switchsize || !tb->switches ||
+               tb->switches[depth-1].len == 0))
            depth--;
        if (odepth > depth) {
            /*
@@ -637,6 +629,19 @@ triewalk *triewalk_new(const void *vt)
 
     return tw;
 }
+
+void triewalk_rebase(triewalk *tw, const void *t)
+{
+    ptrdiff_t diff = ((const unsigned char *)t - (const unsigned char *)(tw->t));
+    int i;
+
+    tw->t = t;
+
+    for (i = 0; i < tw->nswitches; i++)
+       tw->switches[i].sw = (const struct trie_switch *)
+           ((const unsigned char *)(tw->switches[i].sw) + diff);
+}
+
 const struct trie_file *triewalk_next(triewalk *tw, char *buf)
 {
     off_t off;