plan9port

fork of plan9port with libvec, libstr and libsdb
Log | Files | Refs | README | LICENSE

ndbgetval.c (1309B)


      1 #include <u.h>
      2 #include <libc.h>
      3 #include <bio.h>
      4 #include "ndb.h"
      5 
      6 /*
      7  *  search for a tuple that has the given 'attr=val' and also 'rattr=x'.
      8  *  copy 'x' into 'buf' and return the whole tuple.
      9  *
     10  *  return 0 if not found.
     11  */
     12 char*
     13 ndbgetvalue(Ndb *db, Ndbs *s, char *attr, char *val, char *rattr, Ndbtuple **pp)
     14 {
     15 	Ndbtuple *t, *nt;
     16 	char *rv;
     17 	Ndbs temps;
     18 
     19 	if(s == nil)
     20 		s = &temps;
     21 	if(pp)
     22 		*pp = nil;
     23 	t = ndbsearch(db, s, attr, val);
     24 	while(t){
     25 		/* first look on same line (closer binding) */
     26 		nt = s->t;
     27 		for(;;){
     28 			if(strcmp(rattr, nt->attr) == 0){
     29 				rv = strdup(nt->val);
     30 				if(pp != nil)
     31 					*pp = t;
     32 				else
     33 					ndbfree(t);
     34 				return rv;
     35 			}
     36 			nt = nt->line;
     37 			if(nt == s->t)
     38 				break;
     39 		}
     40 		/* search whole tuple */
     41 		for(nt = t; nt; nt = nt->entry){
     42 			if(strcmp(rattr, nt->attr) == 0){
     43 				rv = strdup(nt->val);
     44 				if(pp != nil)
     45 					*pp = t;
     46 				else
     47 					ndbfree(t);
     48 				return rv;
     49 			}
     50 		}
     51 		ndbfree(t);
     52 		t = ndbsnext(s, attr, val);
     53 	}
     54 	return nil;
     55 }
     56 
     57 Ndbtuple*
     58 ndbgetval(Ndb *db, Ndbs *s, char *attr, char *val, char *rattr, char *buf)
     59 {
     60 	Ndbtuple *t;
     61 	char *p;
     62 
     63 	p = ndbgetvalue(db, s, attr, val, rattr, &t);
     64 	if(p == nil){
     65 		if(buf != nil)
     66 			*buf = 0;
     67 	} else {
     68 		if(buf != nil){
     69 			strncpy(buf, p, Ndbvlen-1);
     70 			buf[Ndbvlen-1] = 0;
     71 		}
     72 		free(p);
     73 	}
     74 	return t;
     75 }