446b6d5d4f9f56d545c0d5776ffcbc4458eec9ec
[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.1  1995-10-06 08:51:25  quinn
8  * Added Write-buffer.
9  *
10  *
11  */
12
13 /*
14  * Growing buffer for writing various stuff.
15  */
16
17 #include <stdlib.h>
18
19 #include <wrbuf.h>
20
21 WRBUF wrbuf_alloc(void)
22 {
23     WRBUF n;
24
25     if (!(n = malloc(sizeof(*n))))
26         abort();
27     n->buf = 0;
28     n->size = 0;
29     n->pos = 0;
30     return n;
31 }
32
33 void wrbuf_free(WRBUF b, int free_buf)
34 {
35     if (free_buf && b->buf)
36         free(b->buf);
37     free(b);
38 }
39
40 void wrbuf_rewind(WRBUF b)
41 {
42     b->pos = 0;
43 }
44
45 int wrbuf_grow(WRBUF b, int minsize)
46 {
47     int togrow;
48
49     if (!b->size)
50         togrow = 1024;
51     else
52         togrow = b->size;
53     if (togrow < minsize)
54         togrow = minsize;
55     if (b->size && !(b->buf = realloc(b->buf, b->size += togrow)))
56         abort();
57     else if (!b->size && !(b->buf = malloc(b->size = togrow)))
58         abort();
59     return 0;
60 }
61
62 int wrbuf_write(WRBUF b, char *buf, int size)
63 {
64     if (b->pos + size >= b->size)
65         wrbuf_grow(b, size);
66     memcpy(b->buf + b->pos, buf, size);
67     b->pos += size;
68     return 0;
69 }