Mercurial > hg > nnchat
changeset 241:a1ee6c76ca1c
Functions for growing a string buffer when needed.
author | Matti Hamalainen <ccr@tnsp.org> |
---|---|
date | Wed, 20 Apr 2011 18:47:22 +0300 |
parents | e85d453e82eb |
children | cb86d7543be2 |
files | th_string.c th_string.h |
diffstat | 2 files changed, 49 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- 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; +} +
--- 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