X-Git-Url: http://sigaev.ru/git/gitweb.cgi?a=blobdiff_plain;f=tmalloc.c;fp=tmalloc.c;h=0d51e75cee71899effc04a1b92f5d8586399896e;hb=d87148e06e0655d4a0b9eca3e46082d5b0b48210;hp=c03a7ffedd81fe70a50d66d6296fe887479e182b;hpb=e8eed69019a2d7c048a9a7ed2bf4e1739678cb93;p=tedtools.git diff --git a/tmalloc.c b/tmalloc.c index c03a7ff..0d51e75 100644 --- a/tmalloc.c +++ b/tmalloc.c @@ -30,6 +30,7 @@ #include #include #include +#include #include "tlog.h" #include "tmalloc.h" @@ -296,3 +297,67 @@ mcnstrdup(MemoryContext *cntx, char *src, int len) { return dest; } +/*********StringBuffer********/ +StringBuffer* +initStringBuffer(StringBuffer* state, MemoryContext *mc, int initsize) { + state->len = (initsize>0) ? initsize : 1024; + state->mc = mc; + state->ptr = state->buf = (char*)mcalloc(state->mc, state->len); + *(state->ptr) ='\0'; + + return state; +} + +StringBuffer* +appendStringBuffer( StringBuffer *state, char *string, int stringlen) { + if ( string ) { + if ( stringlen <= 0 ) + stringlen = strlen(string); + } else + stringlen = 0; + + if ( stringlen == 0 ) + return state; + + while ( state->len - ( state->ptr - state->buf ) < stringlen + 1 ) { + state->len *= 2; + state->buf = (char*)mcrealloc( (void*)state->buf, state->len ); + } + + memcpy(state->ptr, string, stringlen); + state->ptr += stringlen; + *state->ptr = '\0'; + return state; +} + +StringBuffer* +printStringBuffer( StringBuffer *state, const char *format, ...) { + va_list args; + int printedlen; + int buffreelen; + + buffreelen = state->len - ( state->ptr - state->buf ) - 1; + + va_start(args, format); + printedlen = vsnprintf(state->ptr, buffreelen, format, args); + va_end(args); + /* + * if buffer too short, resize buffer and + * print it again + */ + if ( buffreelen<=printedlen ) { + u_int32_t curlen = state->ptr - state->buf; + do { + state->len *= 2; + } while( state->ptr - state->buf + printedlen >= state->len ); + + state->buf = (char*)mcrealloc( (void*)state->buf, state->len ); + state->ptr = state->buf + curlen; + va_start(args, format); + printedlen = vsnprintf(state->ptr, printedlen+1, format, args); + va_end(args); + } + state->ptr += printedlen; + return state; +} +