#include <stdlib.h>
#include <string.h>
#include <ctype.h>
+#include <stdarg.h>
#include "tlog.h"
#include "tmalloc.h"
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;
+}
+
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