Skip to content

Commit 0e8893c

Browse files
committed
Added variadic string append function strb_appendv().
1 parent 940c26d commit 0e8893c

File tree

2 files changed

+33
-10
lines changed

2 files changed

+33
-10
lines changed

src/util/strb.c

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -34,24 +34,35 @@ int strb_grow(strb *sb, size_t n) {
3434
return 0;
3535
}
3636

37-
void strb_appendf(strb *sb, const char *f, ...) {
38-
va_list ap;
39-
int s;
37+
void strb_appendv(strb *sb, const char *f, va_list ap) {
38+
va_list apSave;
39+
int s;
4040

41-
va_start(ap, f);
4241
#ifdef _MSC_VER
43-
s = _vscprintf(f, ap);
42+
/**
43+
* va_copy() is a C99 novelty that a particular company should have started
44+
* supporting a long time ago, to their undying shame.
45+
*/
46+
47+
apSave = ap;
48+
s = _vscprintf(f, apSave);
4449
#else
45-
s = vsnprintf(NULL, 0, f, ap);
50+
va_copy(apSave, ap);
51+
s = vsnprintf(NULL, 0, f, apSave);
4652
#endif
47-
va_end(ap);
48-
53+
va_end(apSave);
54+
4955
if (s < 0) { strb_seterror(sb); return; }
5056
s += 1;
5157

5258
if (strb_ensure(sb, s)) return;
53-
va_start(ap, f);
5459
s = vsnprintf(sb->s+sb->l, s, f, ap);
55-
va_end(ap);
5660
sb->l += s;
5761
}
62+
63+
void strb_appendf(strb *sb, const char *f, ...) {
64+
va_list ap;
65+
va_start(ap, f);
66+
strb_appendv(sb, f, ap);
67+
va_end(ap);
68+
}

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" {
@@ -170,6 +171,17 @@ static inline void strb_appendb(strb *sb, strb *sb2) {
170171
*/
171172
GPUARRAY_LOCAL void strb_appendf(strb *, const char *f, ...);
172173

174+
/*
175+
* Appends the result of a sprintf using the format string `f` and
176+
* following variadic arguments list, excluding terminating nul.
177+
*
178+
* Unlike sprintf, this function makes sure not to run off the end of
179+
* memory and behaves like asprintf in that respect.
180+
*
181+
* A format error will place the strb in error mode.
182+
*/
183+
GPUARRAY_LOCAL void strb_appendv(strb *, const char *f, va_list ap);
184+
173185
/*
174186
* Returns a C string from the content of the strb.
175187
*

0 commit comments

Comments
 (0)