xdas_util.c
Go to the documentation of this file.00001 
00002 
00003 
00004 
00005 
00006 
00007 
00008 
00009 
00010 
00011 
00012 
00013 
00014 
00015 
00016 
00017 
00018 
00019 
00020 
00021 
00022 
00023 
00024 
00025 
00026 
00027 
00028 
00029 
00030 
00039 #include "xdas_util.h"
00040 
00041 #include <malloc.h>
00042 #include <string.h>
00043 
00044 #ifdef _WIN32
00045 # define strdup _strdup
00046 #endif
00047 
00063 static char * xdas_strdup(const char * sp, const char * limit)
00064 {
00065    size_t splen = limit? (limit - sp): strlen(sp);
00066    char * spdup = (char *)malloc(splen + 1);
00067    if (spdup != 0)
00068    {
00069       strncpy(spdup, sp, splen);
00070       spdup[splen] = 0;
00071    }
00072    return spdup;
00073 }
00074 
00091 static char * xdas_tokenize(char * str, const char * delims, 
00092       char esc, char ** nextok)
00093 {
00094    char * thistok;
00095    if (str) 
00096       *nextok = str;
00097    thistok = *nextok;
00098    if (thistok)
00099    {
00100       while ((*nextok = strpbrk(*nextok, delims)) != 0 
00101             && *nextok != str && (*nextok)[-1] == esc) 
00102          (*nextok)++;
00103       if (*nextok != 0)
00104          *(*nextok)++ = 0;
00105    }
00106    return thistok;
00107 }
00108 
00134 int xdas_parse_info(const char * info, const char * limit, char ** fields, unsigned maxflds)
00135 {
00136    unsigned i;
00137    char * info_copy, * saveptr;
00138 
00139 #define FLD_DELIMS   ":"
00140 #define ESC_CHAR     '%'
00141 
00142    
00143    if ((info_copy = xdas_strdup(info, limit)) == 0)
00144       return -1;
00145 
00146    
00147    for (saveptr = info_copy; *saveptr; saveptr++)
00148       if ((unsigned char)*saveptr < 32) *saveptr = ' ';
00149 
00150    
00151    fields[0] = xdas_tokenize(info_copy, FLD_DELIMS, ESC_CHAR, &saveptr);
00152    for (i = 1; i < maxflds && fields[i-1]; i++)
00153       fields[i] = xdas_tokenize(0, FLD_DELIMS, ESC_CHAR, &saveptr);
00154 
00155    return saveptr? -2: 0;
00156 }
00157