From: teodor Date: Mon, 25 Jan 2010 17:25:45 +0000 (+0000) Subject: add StringBuffer X-Git-Url: http://sigaev.ru/git/gitweb.cgi?a=commitdiff_plain;h=d87148e06e0655d4a0b9eca3e46082d5b0b48210;p=tedtools.git add StringBuffer --- 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; +} + diff --git a/tmalloc.h b/tmalloc.h index cc10c33..2d1fd69 100644 --- a/tmalloc.h +++ b/tmalloc.h @@ -85,5 +85,15 @@ void mcfree(void * ptr); char * mcstrdup(MemoryContext *cntx, char * src); char * mcnstrdup(MemoryContext *cntx, char *src, int len); +typedef struct { + char *buf; + char *ptr; + u_int32_t len; + MemoryContext *mc; +} StringBuffer; + +StringBuffer* initStringBuffer(StringBuffer* state, MemoryContext *mc, int initsize); +StringBuffer* appendStringBuffer( StringBuffer *state, char *string, int stringlen); +StringBuffer* printStringBuffer( StringBuffer *state, const char *format, ...); #endif