Archived
1
0
Fork 0

strbuf: strbuf_append_va

This commit is contained in:
Henrik Hautakoski 2011-02-05 14:10:59 +01:00
parent e67e03aceb
commit 9c73f8f867
3 changed files with 42 additions and 13 deletions

View file

@ -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

View file

@ -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) {

View file

@ -12,6 +12,7 @@
#define __STRBUF_H
#include <stddef.h>
#include <stdarg.h>
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);