5 * Initialize an expandable text buffer.
7 public void xbuf_init(struct xbuffer *xbuf)
10 xbuf->size = xbuf->end = 0;
13 public void xbuf_deinit(struct xbuffer *xbuf)
15 if (xbuf->data != NULL)
20 public void xbuf_reset(struct xbuffer *xbuf)
26 * Add a byte to an expandable text buffer.
28 public void xbuf_add_byte(struct xbuffer *xbuf, unsigned char b)
30 if (xbuf->end >= xbuf->size)
33 if (ckd_add(&xbuf->size, xbuf->size, xbuf->size ? xbuf->size : 16))
35 data = (unsigned char *) ecalloc(xbuf->size, sizeof(unsigned char));
36 if (xbuf->data != NULL)
38 memcpy(data, xbuf->data, xbuf->end);
43 xbuf->data[xbuf->end++] = (unsigned char) b;
46 public void xbuf_add_data(struct xbuffer *xbuf, unsigned char *data, int len)
49 for (i = 0; i < len; i++)
50 xbuf_add_byte(xbuf, data[i]);
53 public int xbuf_pop(struct xbuffer *buf)
57 return (int) buf->data[--(buf->end)];
60 public void xbuf_set(struct xbuffer *dst, struct xbuffer *src)
63 xbuf_add_data(dst, src->data, src->end);
66 public char * xbuf_char_data(struct xbuffer *xbuf)
68 return (char *)(xbuf->data);
73 * Helper functions for the ckd_add and ckd_mul macro substitutes.
74 * These helper functions do not set *R on overflow, and assume that
75 * arguments are nonnegative, that INTMAX_MAX <= UINTMAX_MAX, and that
76 * sizeof is a reliable way to distinguish integer representations.
77 * Despite these limitations they are good enough for 'less' on all
78 * known practical platforms. For more-complicated substitutes
79 * without most of these limitations, see Gnulib's stdckdint module.
83 * If the integer *R can represent VAL, store the value and return FALSE.
84 * Otherwise, possibly set *R to an indeterminate value and return TRUE.
85 * R has size RSIZE, and is signed if and only if RSIGNED is nonzero.
87 static int help_fixup(void *r, uintmax val, int rsize, int rsigned)
91 if (rsize == sizeof (int))
98 } else if (rsize == sizeof (long long))
106 } else if (rsize == sizeof (intmax_t)) {
108 if (INTMAX_MAX < val)
112 } else /* rsize == sizeof (long) */
120 if (rsize == sizeof (unsigned)) {
124 *pr = (unsigned) val;
125 } else if (rsize == sizeof (unsigned long)) {
126 unsigned long *pr = r;
129 *pr = (unsigned long) val;
131 } else if (rsize == sizeof (unsigned long long)) {
133 if (ULLONG_MAX < val)
137 } else /* rsize == sizeof (uintmax) */
146 * If *R can represent the mathematical sum of A and B, store the sum
147 * and return FALSE. Otherwise, possibly set *R to an indeterminate
148 * value and return TRUE. R has size RSIZE, and is signed if and only
149 * if RSIGNED is nonzero.
151 public int help_ckd_add(void *r, uintmax a, uintmax b, int rsize, int rsigned)
154 return sum < a || help_fixup(r, sum, rsize, rsigned);
156 /* Likewise, but for the product of A and B. */
157 public int help_ckd_mul(void *r, uintmax a, uintmax b, int rsize, int rsigned)
159 uintmax product = a * b;
160 return ((b != 0 && a != product / b)
161 || help_fixup(r, product, rsize, rsigned));