10 #include "asn1_buffer.h"
12 #if !defined(HAVE_DECL_VASPRINTF) || (HAVE_DECL_VASPRINTF == 0)
13 int vasprintf(char **ret, const char *fmt, va_list args);
17 * Create and destroy the buffer.
21 abuf *ab = calloc(1, sizeof(abuf));
25 ab->buffer = calloc(1, ab->size);
30 void abuf_free(abuf *ab) {
36 const_cast.c_buf = ab->buffer;
37 free(const_cast.nc_buf);
43 * Erase contents of the buffer (without destroying it).
46 abuf_clear(abuf *ab) {
53 ab->buffer = calloc(1, ab->size);
56 const_cast.c_buf = ab->buffer;
58 const_cast.nc_buf[0] = '\0';
62 abuf_resize_by(abuf *ab, size_t size) {
67 const_cast.c_buf = ab->buffer;
69 assert(!ab->buffer || ab->buffer[ab->length] == '\0');
71 size_t new_size = ab->length + size;
72 char *p = realloc(const_cast.nc_buf, new_size);
75 assert(ab->length == 0);
79 assert(ab->buffer[ab->length] == '\0');
83 void abuf_add_bytes(abuf *ab, const char *str, size_t size) {
84 abuf_resize_by(ab, size + 1);
89 const_cast.c_buf = ab->buffer;
90 memcpy(&const_cast.nc_buf[ab->length], str, size);
92 const_cast.nc_buf[ab->length] = '\0';
95 void abuf_str(abuf *ab, const char *str) {
96 abuf_add_bytes(ab, str, strlen(str));
99 void abuf_buf(abuf *ab, const abuf *buf) {
100 abuf_add_bytes(ab, buf->buffer, buf->length);
103 int abuf_printf(abuf *ab, const char *fmt, ...) {
111 const_cast.c_buf = ab->buffer;
113 int ret = vsnprintf(&const_cast.nc_buf[ab->length],
114 ab->size - ab->length, fmt, ap);
117 if((size_t)ret < ab->size - ab->length) {
119 assert(ab->buffer[ab->length] == '\0');
122 const_cast.nc_buf[ab->length] = '\0'; /* Restore order */
123 abuf_resize_by(ab, ret + 1);
127 int abuf_vprintf(abuf *ab, const char *fmt, va_list ap) {
131 ret = vasprintf(&str, fmt, ap);
135 abuf_add_bytes(ab, str, ret);
142 #if !defined(HAVE_DECL_VASPRINTF) || (HAVE_DECL_VASPRINTF == 0)
143 /* Solaris doesn't have vasprintf(3). */
145 vasprintf(char **ret, const char *fmt, va_list args) {
146 int actual_length = -1;
150 int suggested = vsnprintf(NULL, 0, fmt, args);
152 *ret = malloc(suggested + 1);
154 int actual_length = vsnprintf(*ret, suggested + 1, fmt, copy);
155 if(actual_length >= 0) {
156 assert(actual_length == suggested);
157 assert((*ret)[actual_length] == '\0');
165 assert(suggested >= 0); /* Can't function like this */
169 return actual_length;