Archived
1
0
Fork 0

strbuf: added strbuf_avail and strbuf_appendf.

This commit is contained in:
Henrik Hautakoski 2011-02-04 17:18:21 +01:00
parent 6538fd9369
commit e67e03aceb
5 changed files with 59 additions and 1 deletions

View file

@ -9,7 +9,10 @@
*/
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "compat/string.h"
#include "util.h"
#include "xalloc.h"
#include "strbuf.h"
@ -23,6 +26,11 @@ void strbuf_init(strbuf_t *s) {
s->alloc_size = s->len = 0;
}
size_t strbuf_avail(strbuf_t *s) {
return s->alloc_size ? s->alloc_size - (s->len + 1) : 0;
}
void strbuf_expand(strbuf_t *s, size_t len) {
if (s->len + len + 1 < s->alloc_size)
@ -112,6 +120,32 @@ void strbuf_append(strbuf_t *s, const void *ptr, size_t len) {
s->buf[s->len] = '\0';
}
void strbuf_appendf(strbuf_t *s, const char *fmt, ...) {
va_list vl;
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);
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");
}
s->len += len;
s->buf[len] = '\0';
}
void strbuf_append_str(strbuf_t *s, const char *str) {
strbuf_append(s, str, strlen(str));

View file

@ -25,6 +25,8 @@ extern char strbuf_null;
void strbuf_init(strbuf_t *s);
size_t strbuf_avail(strbuf_t *s);
void strbuf_expand(strbuf_t *s, size_t len);
void strbuf_reduce(strbuf_t *s, size_t len);
@ -41,6 +43,8 @@ void strbuf_attach(strbuf_t *s, void *str, size_t len, size_t alloc_size);
void strbuf_append(strbuf_t *s, const void *ptr, size_t len);
void strbuf_appendf(strbuf_t *s, const char *fmt, ...);
void strbuf_append_str(strbuf_t *s, const char *str);
void strbuf_append_ch(strbuf_t *s, char ch);