# HG changeset patch # User Matti Hamalainen # Date 1303314442 -10800 # Node ID a1ee6c76ca1c515d12c845e7ed2114eb3c62d47c # Parent e85d453e82ebbe81ff6398eb05d82990fcc4dd4c Functions for growing a string buffer when needed. diff -r e85d453e82eb -r a1ee6c76ca1c th_string.c --- a/th_string.c Wed Apr 20 15:46:42 2011 +0300 +++ b/th_string.c Wed Apr 20 18:47:22 2011 +0300 @@ -439,3 +439,46 @@ } +BOOL th_growbuf(char **buf, size_t *bufsize, size_t *len, size_t grow) +{ + assert(buf != NULL); + assert(bufsize != NULL); + assert(len != NULL); + + if (*buf == NULL) + *bufsize = 0; + + if (*buf == NULL || *len + grow >= *bufsize) { + *bufsize += grow + TH_BUFGROW; + *buf = (char *) th_realloc(*buf, *bufsize); + if (*buf == NULL) + return FALSE; + } + return TRUE; +} + + +void th_vputch(char **buf, size_t *bufsize, size_t *len, const char ch) +{ + if (!th_growbuf(buf, bufsize, len, 1)) + return; + + *buf[*len] = ch; + (*len)++; +} + + +void th_vputs(char **buf, size_t *bufsize, size_t *len, const char *str) +{ + size_t slen; + if (str == NULL) + return; + + slen = strlen(str); + if (!th_growbuf(buf, bufsize, len, slen)) + return; + + strcat(*buf + *len, str); + (*len) += slen; +} + diff -r e85d453e82eb -r a1ee6c76ca1c th_string.h --- a/th_string.h Wed Apr 20 15:46:42 2011 +0300 +++ b/th_string.h Wed Apr 20 18:47:22 2011 +0300 @@ -63,6 +63,12 @@ int th_get_hex_triplet(const char *); + +void th_vputch(char **buf, size_t *bufsize, size_t *len, const char ch); +void th_vputs(char **buf, size_t *bufsize, size_t *len, const char *str); + +#define TH_BUFGROW (32) + #ifdef __cplusplus } #endif