]> git.ipfire.org Git - collecty.git/commitdiff
args: Implement pushing arguments to the array
authorMichael Tremer <michael.tremer@ipfire.org>
Sun, 28 Sep 2025 09:04:19 +0000 (09:04 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Sun, 28 Sep 2025 09:04:19 +0000 (09:04 +0000)
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/daemon/args.c
src/daemon/args.h

index 915d920af0d8fd73c0ae2fba2b218732aec70c9e..ed7368b7349591beafe9782532396bdd395db7a5 100644 (file)
@@ -20,6 +20,7 @@
 
 #include <errno.h>
 #include <stddef.h>
+#include <stdio.h>
 #include <stdlib.h>
 
 #include "args.h"
 struct collecty_args {
        collecty_ctx* ctx;
        int nrefs;
+
+       // Arguments
+       char** argv;
+       int argc;
 };
 
 static void collecty_args_free(collecty_args* self) {
+       if (self->argv) {
+               for (int i = 0; i < self->argc; i++)
+                       free(self->argv[i]);
+               free(self->argv);
+       }
        if (self->ctx)
                collecty_ctx_unref(self->ctx);
        free(self);
@@ -67,3 +77,40 @@ collecty_args* collecty_args_unref(collecty_args* self) {
        collecty_args_free(self);
        return NULL;
 }
+
+int collecty_args_push(collecty_args* self, const char* format, ...) {
+       char** argv = NULL;
+       char* arg = NULL;
+       va_list args;
+       int r;
+
+       // Format the argument
+       va_start(args, format);
+       r = vasprintf(&arg, format, args);
+       va_end(args);
+
+       // Abort if we could not format the string
+       if (r < 0)
+               goto ERROR;
+
+       // Grow argv
+       argv = reallocarray(self->argv, self->argc + 1, sizeof(*self->argv));
+       if (!argv)
+               goto ERROR;
+
+       // Reference the string
+       argv[self->argc + 0] = arg;
+       argv[self->argc + 1] = NULL;
+
+       // Replace the array and increment the counter
+       self->argv = argv;
+       self->argc++;
+
+       return 0;
+
+ERROR:
+       if (arg)
+               free(arg);
+
+       return -errno;
+}
index 458a4ee909f4f14f7b4db775a68d899a75f70f34..f108e036e7712d4fc43f9cd4b6860ab5fd385d6b 100644 (file)
@@ -30,4 +30,7 @@ int collecty_args_create(collecty_args** args, collecty_ctx* ctx);
 collecty_args* collecty_args_ref(collecty_args* self);
 collecty_args* collecty_args_unref(collecty_args* self);
 
+int collecty_args_push(collecty_args* self, const char* format, ...)
+       __attribute__((format(printf, 2, 3)));
+
 #endif /* COLLECTY_ARGS_H */