xref: /freebsd/contrib/less/xbuf.c (revision 3e8eb5c7f4909209c042403ddee340b2ee7003a5)
1 #include "less.h"
2 #include "xbuf.h"
3 
4 /*
5  * Initialize an expandable text buffer.
6  */
7 	public void
8 xbuf_init(xbuf)
9 	struct xbuffer *xbuf;
10 {
11 	xbuf->data = NULL;
12 	xbuf->size = xbuf->end = 0;
13 }
14 
15 	public void
16 xbuf_deinit(xbuf)
17 	struct xbuffer *xbuf;
18 {
19 	if (xbuf->data != NULL)
20 		free(xbuf->data);
21 	xbuf_init(xbuf);
22 }
23 
24 	public void
25 xbuf_reset(xbuf)
26 	struct xbuffer *xbuf;
27 {
28 	xbuf->end = 0;
29 }
30 
31 /*
32  * Add a char to an expandable text buffer.
33  */
34 	public void
35 xbuf_add(xbuf, ch)
36 	struct xbuffer *xbuf;
37 	char ch;
38 {
39 	if (xbuf->end >= xbuf->size)
40 	{
41 		char *data;
42 		xbuf->size = (xbuf->size == 0) ? 16 : xbuf->size * 2;
43 		data = (char *) ecalloc(xbuf->size, sizeof(char));
44 		if (xbuf->data != NULL)
45 		{
46 			memcpy(data, xbuf->data, xbuf->end);
47 			free(xbuf->data);
48 		}
49 		xbuf->data = data;
50 	}
51 	xbuf->data[xbuf->end++] = ch;
52 }
53