1 : /*
2 : * $Id: printbuf.c,v 1.5 2006/01/26 02:16:28 mclark Exp $
3 : *
4 : * Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
5 : * Michael Clark <michael@metaparadigm.com>
6 : *
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.
9 : *
10 : *
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)
14 : */
15 :
16 : #include "config.h"
17 :
18 : #if defined(__GNUC__) && !defined(_GNU_SOURCE)
19 : #define _GNU_SOURCE 1 /* seems to be required to bring in vasprintf */
20 : #endif
21 : #include <stdio.h>
22 : #include <stdlib.h>
23 : #include <string.h>
24 :
25 : #include "cpl_string.h"
26 :
27 : #if HAVE_STDARG_H
28 : # include <stdarg.h>
29 : #else /* !HAVE_STDARG_H */
30 : # error Not enough var arg support!
31 : #endif /* HAVE_STDARG_H */
32 :
33 : #include "bits.h"
34 : #include "debug.h"
35 : #include "printbuf.h"
36 :
37 : struct printbuf* printbuf_new(void)
38 47 : {
39 : struct printbuf *p;
40 :
41 47 : p = (struct printbuf*)calloc(1, sizeof(struct printbuf));
42 47 : if(!p) return NULL;
43 47 : p->size = 32;
44 47 : p->bpos = 0;
45 47 : if(!(p->buf = (char*)malloc(p->size))) {
46 0 : free(p);
47 0 : return NULL;
48 : }
49 47 : return p;
50 : }
51 :
52 :
53 : int printbuf_memappend(struct printbuf *p, const char *buf, int size)
54 1580 : {
55 : char *t;
56 1580 : if(p->size - p->bpos <= size) {
57 75 : int new_size = json_max(p->size * 2, p->bpos + size + 8);
58 : #ifdef PRINTBUF_DEBUG
59 : MC_DEBUG("printbuf_memappend: realloc "
60 : "bpos=%d wrsize=%d old_size=%d new_size=%d\n",
61 : p->bpos, size, p->size, new_size);
62 : #endif /* PRINTBUF_DEBUG */
63 75 : if(!(t = (char*)realloc(p->buf, new_size))) return -1;
64 75 : p->size = new_size;
65 75 : p->buf = t;
66 : }
67 1580 : memcpy(p->buf + p->bpos, buf, size);
68 1580 : p->bpos += size;
69 1580 : p->buf[p->bpos]= '\0';
70 1580 : return size;
71 : }
72 :
73 : /* Use CPLVASPrintf for portability issues */
74 : int sprintbuf(struct printbuf *p, const char *msg, ...)
75 1363 : {
76 : va_list ap;
77 : char *t;
78 : int size, ret;
79 :
80 : /* user stack buffer first */
81 1363 : va_start(ap, msg);
82 1363 : if((size = CPLVASPrintf(&t, msg, ap)) == -1) return -1;
83 1363 : va_end(ap);
84 :
85 1363 : if (strcmp(msg, "%f") == 0)
86 : {
87 165 : char* pszComma = strchr(t, ',');
88 165 : if (pszComma)
89 0 : *pszComma = '.';
90 : }
91 :
92 1363 : ret = printbuf_memappend(p, t, size);
93 1363 : free(t);
94 1363 : return ret;
95 : }
96 :
97 : void printbuf_reset(struct printbuf *p)
98 632 : {
99 632 : p->buf[0] = '\0';
100 632 : p->bpos = 0;
101 632 : }
102 :
103 : void printbuf_free(struct printbuf *p)
104 1135 : {
105 1135 : if(p) {
106 47 : free(p->buf);
107 47 : free(p);
108 : }
109 1135 : }
|