Check for config.h (currently not generated).
[yaz-moved-to-github.git] / util / wrbuf.c
1 /*
2  * Copyright (c) 1995-2000, Index Data.
3  * See the file LICENSE for details.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: wrbuf.c,v $
7  * Revision 1.9  2000-02-29 13:44:55  adam
8  * Check for config.h (currently not generated).
9  *
10  * Revision 1.8  1999/11/30 13:47:12  adam
11  * Improved installation. Moved header files to include/yaz.
12  *
13  * Revision 1.7  1999/11/03 09:05:56  adam
14  * Implemented wrbuf_puts.
15  *
16  * Revision 1.6  1999/10/28 11:36:40  adam
17  * wrbuf_write allows zero buffer length.
18  *
19  * Revision 1.5  1999/08/27 09:40:32  adam
20  * Renamed logf function to yaz_log. Removed VC++ project files.
21  *
22  * Revision 1.4  1998/02/11 11:53:36  adam
23  * Changed code so that it compiles as C++.
24  *
25  * Revision 1.3  1997/05/01 15:08:15  adam
26  * Added log_mask_str_x routine.
27  *
28  * Revision 1.2  1995/11/01 13:55:06  quinn
29  * Minor adjustments
30  *
31  * Revision 1.1  1995/10/06  08:51:25  quinn
32  * Added Write-buffer.
33  *
34  *
35  */
36
37 /*
38  * Growing buffer for writing various stuff.
39  */
40
41 #if HAVE_CONFIG_H
42 #include <config.h>
43 #endif
44
45 #include <stdlib.h>
46 #include <string.h>
47
48 #include <yaz/wrbuf.h>
49
50 WRBUF wrbuf_alloc(void)
51 {
52     WRBUF n;
53
54     if (!(n = (WRBUF)xmalloc(sizeof(*n))))
55         abort();
56     n->buf = 0;
57     n->size = 0;
58     n->pos = 0;
59     return n;
60 }
61
62 void wrbuf_free(WRBUF b, int free_buf)
63 {
64     if (free_buf && b->buf)
65         xfree(b->buf);
66     xfree(b);
67 }
68
69 void wrbuf_rewind(WRBUF b)
70 {
71     b->pos = 0;
72 }
73
74 int wrbuf_grow(WRBUF b, int minsize)
75 {
76     int togrow;
77
78     if (!b->size)
79         togrow = 1024;
80     else
81         togrow = b->size;
82     if (togrow < minsize)
83         togrow = minsize;
84     if (b->size && !(b->buf =(char *)xrealloc(b->buf, b->size += togrow)))
85         abort();
86     else if (!b->size && !(b->buf = (char *)xmalloc(b->size = togrow)))
87         abort();
88     return 0;
89 }
90
91 int wrbuf_write(WRBUF b, const char *buf, int size)
92 {
93     if (size <= 0)
94         return 0;
95     if (b->pos + size >= b->size)
96         wrbuf_grow(b, size);
97     memcpy(b->buf + b->pos, buf, size);
98     b->pos += size;
99     return 0;
100 }
101
102 int wrbuf_puts(WRBUF b, const char *buf)
103 {
104     wrbuf_write(b, buf, strlen(buf)+1);  /* '\0'-terminate as well */
105     (b->pos)--;                          /* don't include '\0' in count */
106     return 0;
107 }