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.
20 #else /* !HAVE_STDARG_H */
21 # error Not enough var arg support!
22 #endif /* HAVE_STDARG_H */
28 struct printbuf
* printbuf_new()
32 if(!(p
= calloc(1, sizeof(struct printbuf
)))) return NULL
;
35 if(!(p
->buf
= malloc(p
->size
))) {
43 int printbuf_memappend(struct printbuf
*p
, char *buf
, int size
)
46 if(p
->size
- p
->bpos
<= size
) {
47 int new_size
= max(p
->size
* 2, p
->bpos
+ size
+ 8);
49 mc_debug("printbuf_memappend: realloc "
50 "bpos=%d wrsize=%d old_size=%d new_size=%d\n",
51 p
->bpos
, size
, p
->size
, new_size
);
52 #endif /* PRINTBUF_DEBUG */
53 if(!(t
= realloc(p
->buf
, new_size
))) return -1;
57 memcpy(p
->buf
+ p
->bpos
, buf
, size
);
59 p
->buf
[p
->bpos
]= '\0';
63 #if !HAVE_VSNPRINTF && defined(WIN32)
64 # define vsnprintf _vsnprintf
65 #elif !HAVE_VSNPRINTF /* !HAVE_VSNPRINTF */
66 # error Need vsnprintf!
67 #endif /* !HAVE_VSNPRINTF && defined(WIN32) */
70 /* CAW: compliant version of vasprintf */
71 static int vasprintf(char **buf
, const char *fmt
, va_list ap
)
74 static char _T_emptybuffer
= '\0';
75 #endif /* !defined(WIN32) */
79 if(!buf
) { return -1; }
82 chars
= _vscprintf(fmt
, ap
)+1;
83 #else /* !defined(WIN32) */
84 /* CAW: RAWR! We have to hope to god here that vsnprintf doesn't overwrite
85 our buffer like on some 64bit sun systems.... but hey, its time to move on */
86 chars
= vsnprintf(&_T_emptybuffer
, 0, fmt
, ap
)+1;
87 if(chars
< 0) { chars
*= -1; } /* CAW: old glibc versions have this problem */
88 #endif /* defined(WIN32) */
90 b
= (char*)malloc(sizeof(char)*chars
);
93 if((chars
= vsprintf(b
, fmt
, ap
)) < 0)
102 #endif /* !HAVE_VASPRINTF */
104 int sprintbuf(struct printbuf
*p
, const char *msg
, ...)
111 /* user stack buffer first */
113 size
= vsnprintf(buf
, 128, msg
, ap
);
115 /* if string is greater than stack buffer, then use dynamic string
116 with vasprintf. Note: some implementation of vsnprintf return -1
117 if output is truncated whereas some return the number of bytes that
118 would have been writen - this code handles both cases. */
119 if(size
== -1 || size
> 127) {
122 if((size
= vasprintf(&t
, msg
, ap
)) == -1) return -1;
124 ret
= printbuf_memappend(p
, t
, size
);
128 return printbuf_memappend(p
, buf
, size
);
132 void printbuf_reset(struct printbuf
*p
)
138 void printbuf_free(struct printbuf
*p
)