]> git.karo-electronics.de Git - mdnsd.git/blob - sdtxt.c
Applied Simons initial checkin, first slightly modifications
[mdnsd.git] / sdtxt.c
1 #include "sdtxt.h"
2
3 #include <string.h>
4
5 // the universe is bound in equal parts by arrogance and altruism, any attempt to alter this would be suicide
6
7 int _sd2txt_len(const char *key, char *val)
8 {
9     int ret = strlen(key);
10     if(!*val) return ret;
11     ret += strlen(val);
12     ret++;
13     return ret;
14 }
15
16 void _sd2txt_count(xht h, const char *key, void *val, void *arg)
17 {
18     int *count = (int*)arg;
19     *count += _sd2txt_len(key,(char*)val) + 1;
20 }
21
22 void _sd2txt_write(xht h, const char *key, void *val, void *arg)
23 {
24     unsigned char **txtp = (unsigned char **)arg;
25     char *cval = (char*)val;
26     int len;
27
28     // copy in lengths, then strings
29     **txtp = _sd2txt_len(key,(char*)val);
30     (*txtp)++;
31     memcpy(*txtp,key,strlen(key));
32     *txtp += strlen(key);
33     if(!*cval) return;
34     **txtp = '=';
35     (*txtp)++;
36     memcpy(*txtp,cval,strlen(cval));
37     *txtp += strlen(cval);
38 }
39
40 unsigned char *sd2txt(xht h, int *len)
41 {
42     unsigned char *buf, *raw;
43     *len = 0;
44
45     xht_walk(h,_sd2txt_count,(void*)len);
46     if(!*len)
47     {
48         *len = 1;
49         buf = (unsigned char *)malloc(1);
50         *buf = 0;
51         return buf;
52     }
53     raw = buf = (unsigned char *)malloc(*len);
54     xht_walk(h,_sd2txt_write,&buf);
55     return raw;
56 }
57
58 xht txt2sd(unsigned char *txt, int len)
59 {
60     char key[256], *val;
61     xht h = 0;
62
63     if(txt == 0 || len == 0 || *txt == 0) return 0;
64     h = xht_new(23);
65
66     // loop through data breaking out each block, storing into hashtable
67     for(;*txt <= len && len > 0; len -= *txt, txt += *txt + 1)
68     {
69         if(*txt == 0) break;
70         memcpy(key,txt+1,*txt);
71         key[*txt] = 0;
72         if((val = strchr(key,'=')) != 0)
73         {
74             *val = 0;
75             val++;
76         }
77         xht_store(h, key, strlen(key), val, strlen(val));
78     }
79     return h;
80 }