ESAPI-C 1.0
The OWASP Enterprise Security API for C
|
00001 00032 #ifndef UTSTRING_H 00033 #define UTSTRING_H 00034 00035 #define UTSTRING_VERSION 1.9.1 00036 00037 #ifdef __GNUC__ 00038 #define _UNUSED_ __attribute__ ((__unused__)) 00039 #else 00040 #define _UNUSED_ 00041 #endif 00042 00043 #include <stdlib.h> 00044 #include <string.h> 00045 #include <stdarg.h> 00046 #define oom() exit(-1) 00047 00048 typedef struct { 00049 char *d; 00050 size_t n; /* allocd size */ 00051 size_t i; /* index of first unused byte */ 00052 } UT_string; 00053 00054 #define utstring_reserve(s,amt) \ 00055 do { \ 00056 if (((s)->n - (s)->i) < (size_t)(amt)) { \ 00057 (s)->d = (char*)realloc((s)->d, (s)->n + amt); \ 00058 if ((s)->d == NULL) oom(); \ 00059 (s)->n += amt; \ 00060 } \ 00061 } while(0) 00062 00063 #define utstring_init(s) \ 00064 do { \ 00065 (s)->n = 0; (s)->i = 0; (s)->d = NULL; \ 00066 utstring_reserve(s,100); \ 00067 } while(0) 00068 00069 #define utstring_done(s) \ 00070 do { \ 00071 if ((s)->d != NULL) free((s)->d); \ 00072 (s)->n = 0; \ 00073 } while(0) 00074 00075 #define utstring_free(s) \ 00076 do { \ 00077 utstring_done(s); \ 00078 free(s); \ 00079 } while(0) 00080 00081 #define utstring_new(s) \ 00082 do { \ 00083 s = (UT_string*)calloc(sizeof(UT_string),1); \ 00084 if (!s) oom(); \ 00085 utstring_init(s); \ 00086 } while(0) 00087 00088 #define utstring_clear(s) \ 00089 do { \ 00090 (s)->i = 0; \ 00091 } while(0) 00092 00093 #define utstring_bincpy(s,b,l) \ 00094 do { \ 00095 utstring_reserve(s,(l)+1); \ 00096 if (l) memcpy(&(s)->d[(s)->i], b, l); \ 00097 s->i += l; \ 00098 s->d[s->i]='\0'; \ 00099 } while(0) 00100 00101 #define utstring_concat(dst,src) \ 00102 do { \ 00103 utstring_reserve(dst,(src->i)+1); \ 00104 if (src->i) memcpy(&(dst)->d[(dst)->i], src->d, src->i); \ 00105 dst->i += src->i; \ 00106 dst->d[dst->i]='\0'; \ 00107 } while(0) 00108 00109 #define utstring_len(s) ((unsigned)((s)->i)) 00110 00111 #define utstring_body(s) ((s)->d) 00112 00113 _UNUSED_ static void utstring_printf_va(UT_string *s, const char *fmt, va_list ap) { 00114 int n; 00115 va_list cp; 00116 while (1) { 00117 #ifdef _WIN32 00118 cp = ap; 00119 #else 00120 va_copy(cp, ap); 00121 #endif 00122 n = vsnprintf (&s->d[s->i], s->n-s->i, fmt, cp); 00123 va_end(cp); 00124 00125 if ((n > -1) && (n < (int)(s->n-s->i))) { 00126 s->i += n; 00127 return; 00128 } 00129 00130 /* Else try again with more space. */ 00131 if (n > -1) utstring_reserve(s,n+1); /* exact */ 00132 else utstring_reserve(s,(s->n)*2); /* 2x */ 00133 } 00134 } 00135 _UNUSED_ static void utstring_printf(UT_string *s, const char *fmt, ...) { 00136 va_list ap; 00137 va_start(ap,fmt); 00138 utstring_printf_va(s,fmt,ap); 00139 va_end(ap); 00140 } 00141 00142 #endif /* UTSTRING_H */