*** empty log message ***
[yaz-moved-to-github.git] / util / wrbuf.c
1 /*
2  * Copyright (c) 1995, Index Data.
3  * See the file LICENSE for details.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: wrbuf.c,v $
7  * Revision 1.2  1995-11-01 13:55:06  quinn
8  * Minor adjustments
9  *
10  * Revision 1.1  1995/10/06  08:51:25  quinn
11  * Added Write-buffer.
12  *
13  *
14  */
15
16 /*
17  * Growing buffer for writing various stuff.
18  */
19
20 #include <stdlib.h>
21
22 #include <wrbuf.h>
23
24 WRBUF wrbuf_alloc(void)
25 {
26     WRBUF n;
27
28     if (!(n = xmalloc(sizeof(*n))))
29         abort();
30     n->buf = 0;
31     n->size = 0;
32     n->pos = 0;
33     return n;
34 }
35
36 void wrbuf_free(WRBUF b, int free_buf)
37 {
38     if (free_buf && b->buf)
39         xfree(b->buf);
40     xfree(b);
41 }
42
43 void wrbuf_rewind(WRBUF b)
44 {
45     b->pos = 0;
46 }
47
48 int wrbuf_grow(WRBUF b, int minsize)
49 {
50     int togrow;
51
52     if (!b->size)
53         togrow = 1024;
54     else
55         togrow = b->size;
56     if (togrow < minsize)
57         togrow = minsize;
58     if (b->size && !(b->buf =xrealloc(b->buf, b->size += togrow)))
59         abort();
60     else if (!b->size && !(b->buf = xmalloc(b->size = togrow)))
61         abort();
62     return 0;
63 }
64
65 int wrbuf_write(WRBUF b, char *buf, int size)
66 {
67     if (b->pos + size >= b->size)
68         wrbuf_grow(b, size);
69     memcpy(b->buf + b->pos, buf, size);
70     b->pos += size;
71     return 0;
72 }