From 6c2a47c73497bbc9fca5152a67ab46c8e6eeb007 Mon Sep 17 00:00:00 2001 From: Michael Tremer Date: Sat, 8 Feb 2025 17:46:38 +0000 Subject: [PATCH] json: Add a convenience function to format strings Signed-off-by: Michael Tremer --- src/pakfire/json.c | 22 ++++++++++++++++++++++ src/pakfire/json.h | 2 ++ 2 files changed, 24 insertions(+) diff --git a/src/pakfire/json.c b/src/pakfire/json.c index ee3177eb..b9ad764d 100644 --- a/src/pakfire/json.c +++ b/src/pakfire/json.c @@ -119,6 +119,28 @@ int pakfire_json_add_stringn(struct json_object* json, return json_object_object_add(json, name, object); } +int pakfire_json_add_stringf(struct json_object* json, + const char* name, const char* format, ...) { + char* buffer = NULL; + va_list args; + int r; + + // Format the input + va_start(args, format); + r = vasprintf(&buffer, format, args); + va_end(args); + if (r < 0) + return r; + + // Add the string + r = pakfire_json_add_stringn(json, name, buffer, r); + + // Cleanup + free(buffer); + + return r; +} + int pakfire_json_add_string_array(struct json_object* json, const char* name, char** array) { int r = 1; diff --git a/src/pakfire/json.h b/src/pakfire/json.h index 7ea0886e..6dfcb682 100644 --- a/src/pakfire/json.h +++ b/src/pakfire/json.h @@ -38,6 +38,8 @@ struct json_object* pakfire_json_new_object(void); int pakfire_json_add_string(struct json_object* json, const char* name, const char* value); int pakfire_json_add_stringn(struct json_object* json, const char* name, const char* value, size_t length); +int pakfire_json_add_stringf(struct json_object* json, const char* name, const char* format, ...) + __attribute__((format(printf, 3, 4))); int pakfire_json_add_int64(struct json_object* json, const char* name, int64_t value); int pakfire_json_add_uint64(struct json_object* json, const char* name, uint64_t value); int pakfire_json_add_double(struct json_object* json, const char* name, double value); -- 2.39.5