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