4 * Copyright Metaparadigm Pte. Ltd. 2004.
5 * Michael Clark <michael@metaparadigm.com>
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public (LGPL)
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details: http://www.gnu.org/
24 #include "libjson/bits.h"
25 #include "libjson/debug.h"
26 #include "libjson/printbuf.h"
29 struct printbuf* printbuf_new()
33 if(!(p = calloc(1, sizeof(struct printbuf)))) return NULL;
36 if(!(p->buf = malloc(p->size))) {
44 int printbuf_memappend(struct printbuf *p, char *buf, int size)
47 if(p->size - p->bpos <= size) {
48 int new_size = max(p->size * 2, p->bpos + size + 8);
50 mc_debug("printbuf_memappend: realloc "
51 "bpos=%d wrsize=%d old_size=%d new_size=%d\n",
52 p->bpos, size, p->size, new_size);
54 if(!(t = realloc(p->buf, new_size))) return -1;
58 memcpy(p->buf + p->bpos, buf, size);
60 p->buf[p->bpos]= '\0';
65 int sprintbuf(struct printbuf *p, const char *msg, ...)
72 /* user stack buffer first */
74 size = vsnprintf(buf, 128, msg, ap);
76 /* if string is greater than stack buffer, then use dynamic string
77 with vasprintf. Note: some implementation of vsnprintf return -1
78 if output is truncated whereas some return the number of bytes that
79 would have been writeen - this code handles both cases. */
80 if(size == -1 || size > 127) {
83 if((size = vasprintf(&t, msg, ap)) == -1) return -1;
85 ret = printbuf_memappend(p, t, size);
89 return printbuf_memappend(p, buf, size);
94 void printbuf_reset(struct printbuf *p)
100 void printbuf_free(struct printbuf *p)