GRS-1 render for ZOOM.
[yaz-moved-to-github.git] / util / wrbuf.c
1 /*
2  * Copyright (c) 1995-2002, Index Data.
3  * See the file LICENSE for details.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Id: wrbuf.c,v 1.10 2002-10-22 10:05:36 adam Exp $
7  */
8
9 /*
10  * Growing buffer for writing various stuff.
11  */
12
13 #if HAVE_CONFIG_H
14 #include <config.h>
15 #endif
16
17 #include <stdlib.h>
18 #include <string.h>
19 #include <stdarg.h>
20
21 #include <yaz/wrbuf.h>
22
23 WRBUF wrbuf_alloc(void)
24 {
25     WRBUF n;
26
27     if (!(n = (WRBUF)xmalloc(sizeof(*n))))
28         abort();
29     n->buf = 0;
30     n->size = 0;
31     n->pos = 0;
32     return n;
33 }
34
35 void wrbuf_free(WRBUF b, int free_buf)
36 {
37     if (free_buf && b->buf)
38         xfree(b->buf);
39     xfree(b);
40 }
41
42 void wrbuf_rewind(WRBUF b)
43 {
44     b->pos = 0;
45 }
46
47 int wrbuf_grow(WRBUF b, int minsize)
48 {
49     int togrow;
50
51     if (!b->size)
52         togrow = 1024;
53     else
54         togrow = b->size;
55     if (togrow < minsize)
56         togrow = minsize;
57     if (b->size && !(b->buf =(char *)xrealloc(b->buf, b->size += togrow)))
58         abort();
59     else if (!b->size && !(b->buf = (char *)xmalloc(b->size = togrow)))
60         abort();
61     return 0;
62 }
63
64 int wrbuf_write(WRBUF b, const char *buf, int size)
65 {
66     if (size <= 0)
67         return 0;
68     if (b->pos + size >= b->size)
69         wrbuf_grow(b, size);
70     memcpy(b->buf + b->pos, buf, size);
71     b->pos += size;
72     return 0;
73 }
74
75 int wrbuf_puts(WRBUF b, const char *buf)
76 {
77     wrbuf_write(b, buf, strlen(buf)+1);  /* '\0'-terminate as well */
78     (b->pos)--;                          /* don't include '\0' in count */
79     return 0;
80 }
81
82 void wrbuf_printf(WRBUF b, const char *fmt, ...)
83 {
84     va_list ap;
85     char buf[4096];
86
87     va_start(ap, fmt);
88 #ifdef WIN32
89     _vsnprintf(buf, sizeof(buf)-1, fmt, ap);
90 #else
91 /* !WIN32 */
92 #if HAVE_VSNPRINTF
93     vsnprintf(buf, sizeof(buf)-1, fmt, ap);
94 #else
95     vsprintf(buf, fmt, ap);
96 #endif
97 #endif
98     wrbuf_puts (b, buf);
99
100     va_end(ap);
101 }
102