xref: /plan9/sys/src/libndb/ndbaux.c (revision 1a4050f5b2ddf426a278e3233ccd7b6bcb0639b8)
1 #include <u.h>
2 #include <libc.h>
3 #include <bio.h>
4 #include <ctype.h>
5 #include <ndb.h>
6 #include "ndbhf.h"
7 
8 
9 /*
10  *  parse a single tuple
11  */
12 char*
_ndbparsetuple(char * cp,Ndbtuple ** tp)13 _ndbparsetuple(char *cp, Ndbtuple **tp)
14 {
15 	char *p;
16 	int len;
17 	Ndbtuple *t;
18 
19 	/* a '#' starts a comment lasting till new line */
20 	EATWHITE(cp);
21 	if(*cp == '#' || *cp == '\n')
22 		return 0;
23 
24 	t = ndbnew(nil, nil);
25 	setmalloctag(t, getcallerpc(&cp));
26 	*tp = t;
27 
28 	/* parse attribute */
29 	p = cp;
30 	while(*cp != '=' && !ISWHITE(*cp) && *cp != '\n')
31 		cp++;
32 	len = cp - p;
33 	if(len >= Ndbalen)
34 		len = Ndbalen-1;
35 	strncpy(t->attr, p, len);
36 
37 	/* parse value */
38 	EATWHITE(cp);
39 	if(*cp == '='){
40 		cp++;
41 		if(*cp == '"'){
42 			p = ++cp;
43 			while(*cp != '\n' && *cp != '"')
44 				cp++;
45 			len = cp - p;
46 			if(*cp == '"')
47 				cp++;
48 		} else if(*cp == '#'){
49 			len = 0;
50 		} else {
51 			p = cp;
52 			while(!ISWHITE(*cp) && *cp != '\n')
53 				cp++;
54 			len = cp - p;
55 		}
56 		ndbsetval(t, p, len);
57 	}
58 
59 	return cp;
60 }
61 
62 /*
63  *  parse all tuples in a line.  we assume that the
64  *  line ends in a '\n'.
65  *
66  *  the tuples are linked as a list using ->entry and
67  *  as a ring using ->line.
68  */
69 Ndbtuple*
_ndbparseline(char * cp)70 _ndbparseline(char *cp)
71 {
72 	Ndbtuple *t;
73 	Ndbtuple *first, *last;
74 
75 	first = last = 0;
76 	while(*cp != '#' && *cp != '\n'){
77 		t = 0;
78 		cp = _ndbparsetuple(cp, &t);
79 		if(cp == 0)
80 			break;
81 		if(first){
82 			last->line = t;
83 			last->entry = t;
84 		} else
85 			first = t;
86 		last = t;
87 		t->line = 0;
88 		t->entry = 0;
89 		setmalloctag(t, getcallerpc(&cp));
90 	}
91 	if(first)
92 		last->line = first;
93 	ndbsetmalloctag(first, getcallerpc(&cp));
94 	return first;
95 }
96