Skip to content

Commit 6de045d

Browse files
committed
Added variadic string append function strb_appendv().
1 parent df2b821 commit 6de045d

File tree

2 files changed

+34
-10
lines changed

2 files changed

+34
-10
lines changed

src/util/strb.c

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -43,25 +43,29 @@ int strb_grow(strb *sb, size_t n) {
4343
return 0;
4444
}
4545

46-
void strb_appendf(strb *sb, const char *f, ...) {
47-
va_list ap;
48-
int s;
46+
void strb_appendv(strb *sb, const char *f, va_list ap) {
47+
va_list apSave;
48+
int s;
4949

50-
va_start(ap, f);
5150
#ifdef _MSC_VER
52-
s = _vscprintf(f, ap);
51+
/**
52+
* va_copy() is a C99 novelty that a particular company should have started
53+
* supporting a long time ago, to their undying shame.
54+
*/
55+
56+
apSave = ap;
57+
s = _vscprintf(f, apSave);
5358
#else
54-
s = vsnprintf(NULL, 0, f, ap);
59+
va_copy(apSave, ap);
60+
s = vsnprintf(NULL, 0, f, apSave);
5561
#endif
56-
va_end(ap);
57-
62+
va_end(apSave);
63+
5864
if (s < 0) { strb_seterror(sb); return; }
5965
s += 1;
6066

6167
if (strb_ensure(sb, s)) return;
62-
va_start(ap, f);
6368
s = vsnprintf(sb->s+sb->l, s, f, ap);
64-
va_end(ap);
6569
sb->l += s;
6670
}
6771

@@ -100,3 +104,11 @@ int strb_write(int fd, strb *sb) {
100104
}
101105
return 0;
102106
}
107+
108+
void strb_appendf(strb *sb, const char *f, ...) {
109+
va_list ap;
110+
va_start(ap, f);
111+
strb_appendv(sb, f, ap);
112+
va_end(ap);
113+
}
114+

src/util/strb.h

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
#define STRB_H
33

44
#include "private_config.h"
5+
#include <stdarg.h>
56

67
#ifdef __cplusplus
78
extern "C" {
@@ -187,6 +188,17 @@ void strb_read(strb *sb, int fd, size_t sz);
187188
*/
188189
int strb_write(int fd, strb *sb);
189190

191+
/*
192+
* Appends the result of a sprintf using the format string `f` and
193+
* following variadic arguments list, excluding terminating nul.
194+
*
195+
* Unlike sprintf, this function makes sure not to run off the end of
196+
* memory and behaves like asprintf in that respect.
197+
*
198+
* A format error will place the strb in error mode.
199+
*/
200+
void strb_appendv(strb *, const char *f, va_list ap);
201+
190202
/*
191203
* Returns a C string from the content of the strb.
192204
*

0 commit comments

Comments
 (0)