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 :
12 : /* json-c private config. */
13 : #include "config.h"
14 :
15 : #include <stdio.h>
16 : #include <stdlib.h>
17 : #include <string.h>
18 :
19 : #if HAVE_STDARG_H
20 : # include <stdarg.h>
21 : #else /* !HAVE_STDARG_H */
22 : # error Not enough var arg support!
23 : #endif /* HAVE_STDARG_H */
24 :
25 : #include "bits.h"
26 : #include "debug.h"
27 : #include "printbuf.h"
28 :
29 : #include <cpl_port.h> /* MIN and MAX macros */
30 : #include <cpl_string.h>
31 :
32 20 : struct printbuf* printbuf_new()
33 : {
34 : struct printbuf *p;
35 :
36 20 : if((p = calloc(1, sizeof(struct printbuf))) == NULL) return NULL;
37 20 : p->size = 32;
38 20 : p->bpos = 0;
39 20 : if((p->buf = malloc(p->size)) == NULL) {
40 0 : free(p);
41 0 : return NULL;
42 : }
43 20 : return p;
44 : }
45 :
46 :
47 2337 : int printbuf_memappend(struct printbuf *p, char *buf, int size)
48 : {
49 : char *t;
50 2337 : if(p->size - p->bpos <= size) {
51 21 : int new_size = MAX(p->size * 2, p->bpos + size + 8);
52 : #ifdef PRINTBUF_DEBUG
53 : mc_debug("printbuf_memappend: realloc "
54 : "bpos=%d wrsize=%d old_size=%d new_size=%d\n",
55 : p->bpos, size, p->size, new_size);
56 : #endif /* PRINTBUF_DEBUG */
57 21 : if((t = realloc(p->buf, new_size)) == NULL) return -1;
58 21 : p->size = new_size;
59 21 : p->buf = t;
60 : }
61 2337 : memcpy(p->buf + p->bpos, buf, size);
62 2337 : p->bpos += size;
63 2337 : p->buf[p->bpos]= '\0';
64 2337 : return size;
65 : }
66 :
67 425 : int sprintbuf(struct printbuf *p, const char *msg, ...)
68 : {
69 : va_list ap;
70 : char *t;
71 : int size, ret;
72 :
73 425 : va_start(ap, msg);
74 425 : if((size = CPLVASPrintf(&t, msg, ap)) == -1) return -1;
75 425 : va_end(ap);
76 :
77 425 : ret = printbuf_memappend(p, t, size);
78 425 : free(t);
79 425 : return ret;
80 : }
81 :
82 260 : void printbuf_reset(struct printbuf *p)
83 : {
84 260 : p->buf[0] = '\0';
85 260 : p->bpos = 0;
86 260 : }
87 :
88 472 : void printbuf_free(struct printbuf *p)
89 : {
90 472 : if(p) {
91 20 : free(p->buf);
92 20 : free(p);
93 : }
94 472 : }
|