Home | History | Annotate | Download | only in lib
      1 #include <stdarg.h>
      2 #include <stdio.h>
      3 #include <stdlib.h>
      4 #include <bufprintf.h>
      5 
      6 int vbufprintf(struct print_buf *buf, const char *format, va_list ap)
      7 {
      8     va_list ap2;
      9     int rv;
     10 
     11     va_copy(ap2, ap);
     12     rv = vsnprintf(NULL, 0, format, ap);
     13 
     14     /* >= to make sure we have space for terminating null */
     15     if (rv + buf->len >= buf->size) {
     16 	size_t newsize = rv + buf->len + BUFPAD;
     17 	char *newbuf;
     18 
     19 	newbuf = realloc(buf->buf, newsize);
     20 	if (!newbuf) {
     21 	    rv = -1;
     22 	    goto bail;
     23 	}
     24 
     25 	buf->buf = newbuf;
     26 	buf->size = newsize;
     27     }
     28 
     29     rv = vsnprintf(buf->buf + buf->len, buf->size - buf->len, format, ap2);
     30     buf->len += rv;
     31 bail:
     32     va_end(ap2);
     33     return rv;
     34 }
     35 
     36 int bufprintf(struct print_buf *buf, const char *format, ...)
     37 {
     38     va_list ap;
     39     int rv;
     40 
     41     va_start(ap, format);
     42     rv = vbufprintf(buf, format, ap);
     43     va_end(ap);
     44     return rv;
     45 }
     46