2 * Copyright (c) 2015, Juniper Networks, Inc.
4 * This SOFTWARE is licensed under the LICENSE provided in the
5 * ../Copyright file. By downloading, installing, copying, or otherwise
6 * using the SOFTWARE, you agree to be bound by the terms of that
8 * Phil Shafer, August 2015
12 * This file is an _internal_ part of the libxo plumbing, not suitable
13 * for external use. It is not considered part of the libxo API and
14 * will not be a stable part of that API. Mine, not your's, dude...
15 * The real hope is that something like this will become a standard part
16 * of libc and I can kill this off.
22 #define XO_BUFSIZ (8*1024) /* Initial buffer size */
23 #define XO_BUF_HIGH_WATER (XO_BUFSIZ - 512) /* When to auto-flush */
25 * xo_buffer_t: a memory buffer that can be grown as needed. We
26 * use them for building format strings and output data.
28 typedef struct xo_buffer_s {
29 char *xb_bufp; /* Buffer memory */
30 char *xb_curp; /* Current insertion point */
31 ssize_t xb_size; /* Size of buffer */
35 * Initialize the contents of an xo_buffer_t.
38 xo_buf_init (xo_buffer_t *xbp)
40 xbp->xb_size = XO_BUFSIZ;
41 xbp->xb_bufp = xo_realloc(NULL, xbp->xb_size);
42 xbp->xb_curp = xbp->xb_bufp;
46 * Reset the buffer to empty
49 xo_buf_reset (xo_buffer_t *xbp)
51 xbp->xb_curp = xbp->xb_bufp;
55 * Return the number of bytes left in the buffer
58 xo_buf_left (xo_buffer_t *xbp)
60 return xbp->xb_size - (xbp->xb_curp - xbp->xb_bufp);
64 * See if the buffer to empty
67 xo_buf_is_empty (xo_buffer_t *xbp)
69 return (xbp->xb_curp == xbp->xb_bufp);
73 * Return the current offset
75 static inline unsigned
76 xo_buf_offset (xo_buffer_t *xbp)
78 return xbp ? (xbp->xb_curp - xbp->xb_bufp) : 0;
82 xo_buf_data (xo_buffer_t *xbp, unsigned offset)
86 return xbp->xb_bufp + offset;
90 xo_buf_cur (xo_buffer_t *xbp)
98 * Initialize the contents of an xo_buffer_t.
101 xo_buf_cleanup (xo_buffer_t *xbp)
104 xo_free(xbp->xb_bufp);
105 bzero(xbp, sizeof(*xbp));
109 * Does the buffer have room for the given number of bytes of data?
110 * If not, realloc the buffer to make room. If that fails, we
111 * return 0 to tell the caller they are in trouble.
114 xo_buf_has_room (xo_buffer_t *xbp, ssize_t len)
116 if (xbp->xb_curp + len >= xbp->xb_bufp + xbp->xb_size) {
117 ssize_t sz = xbp->xb_size + XO_BUFSIZ;
118 char *bp = xo_realloc(xbp->xb_bufp, sz);
122 xbp->xb_curp = bp + (xbp->xb_curp - xbp->xb_bufp);
131 * Append the given string to the given buffer
134 xo_buf_append (xo_buffer_t *xbp, const char *str, ssize_t len)
136 if (!xo_buf_has_room(xbp, len))
139 memcpy(xbp->xb_curp, str, len);
144 * Append the given NUL-terminated string to the given buffer
147 xo_buf_append_str (xo_buffer_t *xbp, const char *str)
149 ssize_t len = strlen(str);
151 if (!xo_buf_has_room(xbp, len))
154 memcpy(xbp->xb_curp, str, len);
158 #endif /* XO_BUF_H */