5b416f656c353856c05925b0ef8da8a745f61183
[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.6  1999-10-28 11:36:40  adam
8  * wrbuf_write allows zero buffer length.
9  *
10  * Revision 1.5  1999/08/27 09:40:32  adam
11  * Renamed logf function to yaz_log. Removed VC++ project files.
12  *
13  * Revision 1.4  1998/02/11 11:53:36  adam
14  * Changed code so that it compiles as C++.
15  *
16  * Revision 1.3  1997/05/01 15:08:15  adam
17  * Added log_mask_str_x routine.
18  *
19  * Revision 1.2  1995/11/01 13:55:06  quinn
20  * Minor adjustments
21  *
22  * Revision 1.1  1995/10/06  08:51:25  quinn
23  * Added Write-buffer.
24  *
25  *
26  */
27
28 /*
29  * Growing buffer for writing various stuff.
30  */
31
32 #include <stdlib.h>
33 #include <string.h>
34
35 #include <wrbuf.h>
36
37 WRBUF wrbuf_alloc(void)
38 {
39     WRBUF n;
40
41     if (!(n = (WRBUF)xmalloc(sizeof(*n))))
42         abort();
43     n->buf = 0;
44     n->size = 0;
45     n->pos = 0;
46     return n;
47 }
48
49 void wrbuf_free(WRBUF b, int free_buf)
50 {
51     if (free_buf && b->buf)
52         xfree(b->buf);
53     xfree(b);
54 }
55
56 void wrbuf_rewind(WRBUF b)
57 {
58     b->pos = 0;
59 }
60
61 int wrbuf_grow(WRBUF b, int minsize)
62 {
63     int togrow;
64
65     if (!b->size)
66         togrow = 1024;
67     else
68         togrow = b->size;
69     if (togrow < minsize)
70         togrow = minsize;
71     if (b->size && !(b->buf =(char *)xrealloc(b->buf, b->size += togrow)))
72         abort();
73     else if (!b->size && !(b->buf = (char *)xmalloc(b->size = togrow)))
74         abort();
75     return 0;
76 }
77
78 int wrbuf_write(WRBUF b, const char *buf, int size)
79 {
80     if (size <= 0)
81         return 0;
82     if (b->pos + size >= b->size)
83         wrbuf_grow(b, size);
84     memcpy(b->buf + b->pos, buf, size);
85     b->pos += size;
86     return 0;
87 }