gopherfs

A FUSE gopher file system.
git clone git://r-36.net/gopherfs
Log | Files | Refs | README | LICENSE

sdb.c (1618B)


      1 /*
      2  * Copy me if you can.
      3  * by 20h
      4  */
      5 
      6 #include <unistd.h>
      7 #include <stdio.h>
      8 #include <stdlib.h>
      9 #include <string.h>
     10 #include "ind.h"
     11 #include "sdb.h"
     12 
     13 void
     14 freeelem(sdbe *e)
     15 {
     16 
     17 	if(e != nil) {
     18 		free(e->v);
     19 		free(e->k);
     20 		free(e);
     21 	}
     22 
     23 	return;
     24 }
     25 
     26 sdbe *
     27 mkelem(char *k, char *v, int l, sdbe *p, sdbe *n)
     28 {
     29 	sdbe *ret;
     30 
     31 	ret = greallocz(nil, sizeof(sdbe), 2);
     32 	ret->v = gmemdup(v, l);
     33 	ret->k = gmemdup(k, strlen(k) + 1);
     34 	ret->n = n;
     35 	ret->p = p;
     36 
     37 	return ret;
     38 }
     39 
     40 sdb *
     41 createdb(void)
     42 {
     43 
     44 	return greallocz(nil, sizeof(sdb), 2);
     45 }
     46 
     47 void
     48 destroydb(sdb *d)
     49 {
     50 
     51 	for(; d->n > 0; d->l = d->l->p, d->n--)
     52 		freeelem(d->l->n);
     53 	freeelem(d->b);
     54 	free(d);
     55 
     56 	return;
     57 }
     58 
     59 int
     60 addelem(sdb *d, char *k, char *v, int l)
     61 {
     62 	sdbe *ret;
     63 
     64 	ret = mkelem(k, v, l, d->l,
     65 			(d->l != nil) ? d->l->n : nil);
     66 
     67 	if(d->l != nil)
     68 		d->l->n = ret;
     69 	if(d->b == nil)
     70 		d->b = ret;
     71 
     72 	d->l = ret;
     73 	d->n++;
     74 
     75 	return 0;
     76 }
     77 
     78 sdbe *
     79 getelem(sdb *d, char *k, sdbe *e)
     80 {
     81 	sdbe *cur;
     82 
     83 	if(e != nil)
     84 		cur = e->n;
     85 	else
     86 		cur = d->b;
     87 
     88 	for(; cur != nil; cur = cur->n)
     89 		if(!strncmp(cur->k, k, strlen(k)))
     90 			return cur;
     91 
     92 	return nil;
     93 }
     94 
     95 int
     96 delelem(sdb *d, char *k)
     97 {
     98 	sdbe *e;
     99 
    100 	e = getelem(d, k, nil);
    101 	if(e == nil)
    102 		return 1;
    103 
    104 	if(d->b == e)
    105 		d->b = e->n;
    106 	if(d->l == e)
    107 		d->l = e->p;
    108 
    109 	if(e->p != nil)
    110 		e->p->n = e->n;
    111 	if(e->n != nil)
    112 		e->n->p = e->p;
    113 
    114 	freeelem(e);
    115 
    116 	d->n--;
    117 
    118 	return 0;
    119 }
    120 
    121 void
    122 printdb(sdb *d)
    123 {
    124         sdbe *cur;
    125 	int i;
    126 
    127 	fprintf(stdout, "d->n == %d\n", d->n);
    128         for(cur = d->b, i = 0; i < d->n; cur = cur->n, i++)
    129 		fprintf(stdout, "%p \"%s\" -%p-> \"%s\" %p\n", cur->p,
    130 			cur->k, cur, cur->v, cur->n);
    131 
    132 	return;
    133 }
    134