WvStreams
wvattrs.cc
1 #include "wvattrs.h"
2 
3 WvAttrs::WvAttrs() : attrlist(NULL), attrlen(0)
4 {
5 }
6 
7 WvAttrs::WvAttrs(const WvAttrs &copy) : attrlist(NULL), attrlen(copy.attrlen)
8 {
9  if (copy.attrlen) {
10  attrlist = (char *)malloc((copy.attrlen + 1) * sizeof(char));
11  memcpy(attrlist, copy.attrlist, copy.attrlen + 1);
12  }
13 }
14 
15 WvAttrs::~WvAttrs()
16 {
17  free(attrlist);
18 }
19 
20 char *WvAttrs::_get(WvStringParm name) const
21 {
22  if (!attrlist)
23  return NULL;
24 
25  const char *curpos = attrlist;
26  while (*curpos)
27  {
28  const char *const valoffset = curpos + strlen(curpos) + 1;
29  if (!strcmp(curpos, name.cstr()))
30  return (char *)valoffset; //value
31 
32  curpos = valoffset + strlen(valoffset) + 1;
33  }
34 
35  return NULL;
36 }
37 
38 void WvAttrs::set(WvStringParm name, WvStringParm value)
39 {
40  if (!name)
41  return;
42 
43  const int namelen = name.len();
44  char *exists = _get(name);
45  if (exists)
46  {
47  //We're trying to readd a key. Sigh. Oh well, delete and readd!
48  const int toremove = namelen + strlen(exists) + 2;
49  exists -= namelen + 1; //index of name, rather than value
50 
51  /* Length of part after what we want to remove */
52  const int endpart = attrlen - (exists - attrlist) - toremove + 1;
53  memmove(exists, exists + toremove, endpart);
54  attrlen -= toremove;
55  attrlist = (char *)realloc(attrlist, (attrlen + 1)
56  * sizeof(char));
57  }
58 
59  if (!value) /* Make a null or empty value a delete */
60  return;
61 
62  const unsigned int totallen = namelen + value.len() + 2;
63  attrlist = (char *)realloc(attrlist, (attrlen + totallen + 1)*sizeof(char));
64 
65  char *const beginloc = attrlist + attrlen;
66  strcpy(beginloc, name.cstr());
67  strcpy(beginloc + namelen + 1, value.cstr());
68 
69  attrlen += totallen;
70  attrlist[attrlen] = 0;
71 }
WvAttrs
Definition: wvattrs.h:6