strbuf: strbuf_append_va
This commit is contained in:
parent
e67e03aceb
commit
9c73f8f867
3 changed files with 42 additions and 13 deletions
32
src/strbuf.c
32
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) {
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
Reference in a new issue