/*********StringBuffer********/
-#define SBALLOC(s) ( ( (s)->mc ) ? mcalloc((s)->mc, (s)->len) : tmalloc((s)->len) )
-#define SBREALLOC(s) ( ( (s)->mc ) ? mcrealloc((s)->buf, (s)->len) : trealloc((s)->buf, (s)->len) )
+static inline void*
+StringBufferAlloc(StringBuffer* state, void *ptr, size_t size) {
+ if (state->mc)
+ return (ptr) ? mcrealloc(ptr, size) : mcalloc(state->mc, size);
+ else if (state->memalloc)
+ return state->memalloc(ptr, size);
+ else
+ return (ptr) ? trealloc(ptr, size) : tmalloc(size);
+}
-StringBuffer*
-initStringBuffer(StringBuffer* state, MemoryContext *mc, int initsize) {
+static StringBuffer*
+initStringBufferInternal(StringBuffer* state, int initsize) {
state->len = (initsize>0) ? initsize : 1024;
- state->mc = mc;
- state->ptr = state->buf = (char*)SBALLOC(state);
+ state->ptr = state->buf = (char*)StringBufferAlloc(state, NULL, initsize);
+ if (!state->ptr)
+ return NULL;
+
*(state->ptr) ='\0';
return state;
}
+StringBuffer*
+initStringBuffer(StringBuffer* state, int initsize) {
+ memset(state, 0, sizeof(*state));
+
+ return initStringBufferInternal(state, initsize);
+}
+
+StringBuffer*
+initStringBufferMC(StringBuffer* state, MemoryContext *mc, int initsize) {
+ memset(state, 0, sizeof(*state));
+ state->mc = mc;
+
+ return initStringBufferInternal(state, initsize);
+}
+
+StringBuffer*
+initStringBufferMA(StringBuffer* state, MemAlloc memalloc, int initsize) {
+ memset(state, 0, sizeof(*state));
+ state->memalloc = memalloc;
+
+ return initStringBufferInternal(state, initsize);
+}
+
StringBuffer*
appendStringBuffer( StringBuffer *state, char *string, int stringlen) {
if ( string ) {
int diff = state->ptr - state->buf;
state->len *= 2;
- state->buf = (char*)SBREALLOC(state);
+ state->buf = (char*)StringBufferAlloc(state, state->buf, state->len);
state->ptr = state->buf + diff;
}
state->len *= 2;
} while( state->ptr - state->buf + printedlen >= state->len );
- state->buf = (char*)SBREALLOC(state);
+ state->buf = (char*)StringBufferAlloc(state, state->buf, state->len);
state->ptr = state->buf + curlen;
va_start(args, format);
printedlen = vsnprintf(state->ptr, printedlen+1, format, args);
char * mcstrdup(MemoryContext *cntx, char * src);
char * mcnstrdup(MemoryContext *cntx, char *src, int len);
+typedef void* (*MemAlloc)(void *ptr, size_t size);
+
typedef struct {
char *buf;
char *ptr;
u_int32_t len;
MemoryContext *mc;
+ MemAlloc memalloc;
} StringBuffer;
-StringBuffer* initStringBuffer(StringBuffer* state, MemoryContext *mc, int initsize);
+StringBuffer* initStringBuffer(StringBuffer* state, int initsize);
+StringBuffer* initStringBufferMC(StringBuffer* state, MemoryContext *mc, int initsize);
+StringBuffer* initStringBufferMA(StringBuffer* state, MemAlloc memalloc, int initsize);
StringBuffer* appendStringBuffer( StringBuffer *state, char *string, int stringlen);
StringBuffer* printStringBuffer( StringBuffer *state, const char *format, ...);