aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

tree.c (2018B)


      1 #include <assert.h>
      2 #include <stdbool.h>
      3 #include <stddef.h>
      4 #include "util.h"
      5 
      6 #define MAXH (sizeof(void *) * 8 * 3 / 2)
      7 
      8 static inline int
      9 height(struct treenode *n)
     10 {
     11   return n ? n->height : 0;
     12 }
     13 
     14 static int
     15 rot(void **p, struct treenode *x, int dir /* deeper side */)
     16 {
     17   struct treenode *y  = x->child[dir];
     18   struct treenode *z  = y->child[!dir];
     19   int              hx = x->height;
     20   int              hz = height(z);
     21   if (hz > height(y->child[dir])) {
     22     /*
     23      * x
     24      * / \ dir z
     25      * a y / \
     26      * / \ --> x y
     27      * z d /| |\
     28      * / \ a b c d
     29      * b c
     30      */
     31     x->child[dir]  = z->child[!dir];
     32     y->child[!dir] = z->child[dir];
     33     z->child[!dir] = x;
     34     z->child[dir]  = y;
     35     x->height      = hz;
     36     y->height      = hz;
     37     z->height      = hz + 1;
     38   } else {
     39     /*
     40      * x y
     41      * / \ / \
     42      * a y --> x d
     43      * / \ / \
     44      * z d a z
     45      */
     46     x->child[dir]  = z;
     47     y->child[!dir] = x;
     48     x->height      = hz + 1;
     49     y->height      = hz + 2;
     50     z              = y;
     51   }
     52   *p = z;
     53   return z->height - hx;
     54 }
     55 
     56 /* balance *p, return 0 if height is unchanged */
     57 static int
     58 balance(void **p)
     59 {
     60   struct treenode *n  = *p;
     61   int              h0 = height(n->child[0]);
     62   int              h1 = height(n->child[1]);
     63   if (h0 - h1 + 1u < 3u) {
     64     int old   = n->height;
     65     n->height = h0 < h1 ? h1 + 1 : h0 + 1;
     66     return n->height - old;
     67   }
     68   return rot(p, n, h0 < h1);
     69 }
     70 
     71 void *
     72 treeinsert(void **root, unsigned long long key, size_t sz)
     73 {
     74   void           **a[MAXH];
     75   struct treenode *n = *root;
     76   int              i = 0;
     77 
     78   a[i++] = root;
     79   while (n) {
     80     if (key == n->key) {
     81       n->new = false;
     82       return n;
     83     }
     84     a[i++] = &n->child[key > n->key];
     85     n      = n->child[key > n->key];
     86   }
     87   assert(sz > sizeof(*n));
     88   n           = xmalloc(sz);
     89   n->key      = key;
     90   n->child[0] = n->child[1] = 0;
     91   n->height                 = 1;
     92   /* insert new node, rebalance ancestors */
     93   *a[--i] = n;
     94   while (i && balance(a[--i]))
     95     ;
     96   n->new = true;
     97   return n;
     98 }