WvStreams
wvattrs.cc
00001 #include "wvattrs.h"
00002 
00003 WvAttrs::WvAttrs() : attrlist(NULL), attrlen(0)
00004 {
00005 }
00006 
00007 WvAttrs::WvAttrs(const WvAttrs &copy) : attrlist(NULL), attrlen(copy.attrlen)
00008 {
00009     if (copy.attrlen) {
00010         attrlist = (char *)malloc((copy.attrlen + 1) * sizeof(char));
00011         memcpy(attrlist, copy.attrlist, copy.attrlen + 1);
00012     }
00013 }
00014 
00015 WvAttrs::~WvAttrs()
00016 {
00017     free(attrlist);
00018 }
00019 
00020 char *WvAttrs::_get(WvStringParm name) const
00021 {
00022     if (!attrlist)
00023         return NULL;
00024 
00025     const char *curpos = attrlist;
00026     while (*curpos)
00027     {
00028         const char *const valoffset = curpos + strlen(curpos) + 1;
00029         if (!strcmp(curpos, name.cstr()))
00030             return (char *)valoffset; //value
00031 
00032         curpos = valoffset + strlen(valoffset) + 1;
00033     }
00034 
00035     return NULL;
00036 }
00037 
00038 void WvAttrs::set(WvStringParm name, WvStringParm value)
00039 {
00040     if (!name)
00041         return;
00042 
00043     const int namelen = name.len();
00044     char *exists = _get(name);
00045     if (exists)
00046     {
00047         //We're trying to readd a key.  Sigh.  Oh well, delete and readd!
00048         const int toremove = namelen + strlen(exists) + 2;
00049         exists -= namelen + 1; //index of name, rather than value
00050 
00051         /* Length of part after what we want to remove */
00052         const int endpart = attrlen - (exists - attrlist) - toremove + 1;
00053         memmove(exists, exists + toremove, endpart);
00054         attrlen -= toremove;
00055         attrlist = (char *)realloc(attrlist, (attrlen + 1)
00056                                                 * sizeof(char));
00057     }
00058 
00059     if (!value) /* Make a null or empty value a delete */
00060         return;
00061 
00062     const unsigned int totallen = namelen + value.len() + 2;
00063     attrlist = (char *)realloc(attrlist, (attrlen + totallen + 1)*sizeof(char));
00064 
00065     char *const beginloc = attrlist + attrlen;
00066     strcpy(beginloc, name.cstr());
00067     strcpy(beginloc + namelen + 1, value.cstr());
00068 
00069     attrlen += totallen;
00070     attrlist[attrlen] = 0;
00071 }