2 * $Id: printbuf.c,v 1.5 2006/01/26 02:16:28 mclark Exp $
4 * Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
5 * Michael Clark <michael@metaparadigm.com>
7 * This library is free software; you can redistribute it and/or modify
8 * it under the terms of the MIT license. See COPYING for details.
11 * Copyright (c) 2008-2009 Yahoo! Inc. All rights reserved.
12 * The copyrights to the contents of this file are licensed under the MIT License
13 * (http://www.opensource.org/licenses/mit-license.php)
24 #else /* !HAVE_STDARG_H */
25 # error Not enough var arg support!
26 #endif /* HAVE_STDARG_H */
30 #include "snprintf_compat.h"
31 #include "vasprintf_compat.h"
33 static int printbuf_extend(struct printbuf *p, int min_size);
35 struct printbuf* printbuf_new(void)
39 p = (struct printbuf*)calloc(1, sizeof(struct printbuf));
43 if(!(p->buf = (char*)malloc(p->size))) {
53 * Extend the buffer p so it has a size of at least min_size.
55 * If the current size is large enough, nothing is changed.
57 * Note: this does not check the available space! The caller
58 * is responsible for performing those calculations.
60 static int printbuf_extend(struct printbuf *p, int min_size)
65 if (p->size >= min_size)
68 new_size = p->size * 2;
69 if (new_size < min_size + 8)
70 new_size = min_size + 8;
72 MC_DEBUG("printbuf_memappend: realloc "
73 "bpos=%d min_size=%d old_size=%d new_size=%d\n",
74 p->bpos, min_size, p->size, new_size);
75 #endif /* PRINTBUF_DEBUG */
76 if(!(t = (char*)realloc(p->buf, new_size)))
83 int printbuf_memappend(struct printbuf *p, const char *buf, int size)
85 if (p->size <= p->bpos + size + 1) {
86 if (printbuf_extend(p, p->bpos + size + 1) < 0)
89 memcpy(p->buf + p->bpos, buf, size);
91 p->buf[p->bpos]= '\0';
95 int printbuf_memset(struct printbuf *pb, int offset, int charvalue, int len)
101 size_needed = offset + len;
102 if (pb->size < size_needed)
104 if (printbuf_extend(pb, size_needed) < 0)
108 memset(pb->buf + offset, charvalue, len);
109 if (pb->bpos < size_needed)
110 pb->bpos = size_needed;
115 int sprintbuf(struct printbuf *p, const char *msg, ...)
122 /* user stack buffer first */
124 size = vsnprintf(buf, 128, msg, ap);
126 /* if string is greater than stack buffer, then use dynamic string
127 with vasprintf. Note: some implementation of vsnprintf return -1
128 if output is truncated whereas some return the number of bytes that
129 would have been written - this code handles both cases. */
130 if(size == -1 || size > 127) {
132 if((size = vasprintf(&t, msg, ap)) < 0) { va_end(ap); return -1; }
134 printbuf_memappend(p, t, size);
138 printbuf_memappend(p, buf, size);
143 void printbuf_reset(struct printbuf *p)
149 void printbuf_free(struct printbuf *p)