*/
void buf_expand_shell_variables(struct buf *s);
+/**
+ * buf_add_fmt - add format string to C string buffer
+ * @s: buffer
+ * @fmt: format string to be added
+ */
+void buf_add_fmt(struct buf *s, const char *fmt, ...);
+
/**
* buf_add - add data to C string buffer
* @s: buffer
// SPDX-License-Identifier: GPL-2.0-only
#include <assert.h>
#include <ctype.h>
+#include <stdarg.h>
#include <stdbool.h>
+#include <stdio.h>
#include <string.h>
#include "common/buf.h"
#include "common/macros.h"
s->alloc = new_alloc;
}
+void
+buf_add_fmt(struct buf *s, const char *fmt, ...)
+{
+ if (string_null_or_empty(fmt)) {
+ return;
+ }
+ size_t size = 0;
+ va_list ap;
+
+ va_start(ap, fmt);
+ int n = vsnprintf(NULL, size, fmt, ap);
+ va_end(ap);
+
+ if (n < 0) {
+ return;
+ }
+
+ size = (size_t)n + 1;
+ buf_expand(s, s->len + size);
+
+ va_start(ap, fmt);
+ n = vsnprintf(s->data + s->len, size, fmt, ap);
+ va_end(ap);
+
+ if (n < 0) {
+ return;
+ }
+
+ s->len += n;
+ s->data[s->len] = 0;
+}
+
void
buf_add(struct buf *s, const char *data)
{
free(s.data);
}
+static void
+test_buf_add_fmt(void **state)
+{
+ (void)state;
+
+ struct buf s = BUF_INIT;
+
+ buf_add(&s, "foo");
+ buf_add_fmt(&s, " %s baz %d", "bar", 10);
+ assert_string_equal(s.data, "foo bar baz 10");
+
+ buf_reset(&s);
+}
+
int main(int argc, char **argv)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(test_expand_title),
+ cmocka_unit_test(test_buf_add_fmt),
};
return cmocka_run_group_tests(tests, NULL, NULL);