]> git.mdlowis.com Git - proto/labwc.git/commitdiff
buf: add buf_add_fmt()
authorJohan Malm <jgm323@gmail.com>
Mon, 19 Aug 2024 20:22:50 +0000 (21:22 +0100)
committerConsolatis <35009135+Consolatis@users.noreply.github.com>
Wed, 21 Aug 2024 14:09:44 +0000 (16:09 +0200)
include/common/buf.h
src/common/buf.c
t/buf-simple.c

index bcbc8301ab4ad4273b87c8527d6731916a5e2ccd..a75c114406da9796b3bcfba8d0f07138cfabfe9b 100644 (file)
@@ -43,6 +43,13 @@ void buf_expand_tilde(struct buf *s);
  */
 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
index ecdddc6e8cd7e079156cd62c3e33d1faae0d21a7..d36f64d5defc695c7a239933a23ff6a2e8e26f55 100644 (file)
@@ -1,7 +1,9 @@
 // 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"
@@ -95,6 +97,38 @@ buf_expand(struct buf *s, int new_alloc)
        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)
 {
index 4772211688aeb11e70f4e0ab2ac477e7f68cb12d..3993ae83ab48f39ed7409c082eb5b6ea7afbd2d4 100644 (file)
@@ -55,10 +55,25 @@ test_expand_title(void **state)
        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);