diff --git a/docs/technical/strbuf.txt b/docs/technical/strbuf.txt index 6b712cb..b481e7e 100644 --- a/docs/technical/strbuf.txt +++ b/docs/technical/strbuf.txt @@ -43,6 +43,26 @@ Functions Adds the formated-string 'fmt' to the end of ->buf. +`strbuf_append_va()`:: + + Adds the formated-string 'fmt' (generated by a `va_list`) to the end of ->buf. + + Returns the number of characters that should have been written if ->buf was large enough. + + Therefor if the function returns zero. all characters has been written. + + + + Example usage: ++ +---- +va_start(va, fmt); +len = strbuf_append_va(s, fmt, va); +va_end(va); + +if (len > 0) { + strbuf_expand(s, len); + va_start(va, fmt); + len = strbuf_append_va(s, fmt, va); + va_end(va); +} +---- `strbuf_append_str()`:: Will add the 'str' C-string to the end of ->buf diff --git a/src/strbuf.c b/src/strbuf.c index 57be4ee..1abb42e 100644 --- a/src/strbuf.c +++ b/src/strbuf.c @@ -122,28 +122,34 @@ void strbuf_append(strbuf_t *s, const void *ptr, size_t len) { void strbuf_appendf(strbuf_t *s, const char *fmt, ...) { - va_list vl; + va_list va; int len; - + if (!strbuf_avail(s)) strbuf_expand(s, CHNK_SIZE-1); - va_start(vl, fmt); - len = vsnprintf(s->buf + s->len, s->alloc_size - s->len, fmt, vl); - va_end(vl); + va_start(va, fmt); + len = strbuf_append_va(s, fmt, va); + va_end(va); + if (len > 0) { + strbuf_expand(s, len); + va_start(va, fmt); + len = strbuf_append_va(s, fmt, va); + va_end(va); + } +} + +int strbuf_append_va(strbuf_t *s, const char *fmt, va_list va) { + + int len = vsnprintf(s->buf + s->len, s->alloc_size - s->len, fmt, va); if (len < 0) die_errno("vsnprintf"); - if (len > strbuf_avail(s)) { - strbuf_expand(s, len); - va_start(vl, fmt); - len = vsnprintf(s->buf + s->len, s->alloc_size - s->len, fmt, vl); - va_end(vl); - if (len > strbuf_avail(s)) - die_errno("vsnprintf"); - } + if (len > strbuf_avail(s)) + return len; s->len += len; s->buf[len] = '\0'; + return 0; } void strbuf_append_str(strbuf_t *s, const char *str) { diff --git a/src/strbuf.h b/src/strbuf.h index 919eaeb..25fdb14 100644 --- a/src/strbuf.h +++ b/src/strbuf.h @@ -12,6 +12,7 @@ #define __STRBUF_H #include +#include typedef struct { size_t alloc_size; @@ -45,6 +46,8 @@ void strbuf_append(strbuf_t *s, const void *ptr, size_t len); void strbuf_appendf(strbuf_t *s, const char *fmt, ...); +int strbuf_append_va(strbuf_t *s, const char *fmt, va_list va); + void strbuf_append_str(strbuf_t *s, const char *str); void strbuf_append_ch(strbuf_t *s, char ch);