From 41dceb91dd10fd597d3a26adcb245a18e0c2c077 Mon Sep 17 00:00:00 2001 From: Yu Watanabe Date: Sat, 3 Sep 2022 23:10:24 +0900 Subject: json: introduce json_append() --- src/shared/json.c | 24 ++++++++++++++++++++++++ src/shared/json.h | 3 +++ src/test/test-json.c | 15 +++++++++++++++ 3 files changed, 42 insertions(+) diff --git a/src/shared/json.c b/src/shared/json.c index f0416e66dc..d541eb1036 100644 --- a/src/shared/json.c +++ b/src/shared/json.c @@ -4120,6 +4120,30 @@ int json_build(JsonVariant **ret, ...) { return r; } +int json_appendv(JsonVariant **v, va_list ap) { + _cleanup_(json_variant_unrefp) JsonVariant *w = NULL; + int r; + + assert(v); + + r = json_buildv(&w, ap); + if (r < 0) + return r; + + return json_variant_merge(v, w); +} + +int json_append(JsonVariant **v, ...) { + va_list ap; + int r; + + va_start(ap, v); + r = json_appendv(v, ap); + va_end(ap); + + return r; +} + int json_log_internal( JsonVariant *variant, int level, diff --git a/src/shared/json.h b/src/shared/json.h index 98d184c309..c75dfe8741 100644 --- a/src/shared/json.h +++ b/src/shared/json.h @@ -327,6 +327,9 @@ enum { int json_build(JsonVariant **ret, ...); int json_buildv(JsonVariant **ret, va_list ap); + /* These two functions below are equivalent to json_build() (or json_buildv()) and json_variant_merge(). */ +int json_append(JsonVariant **v, ...); +int json_appendv(JsonVariant **v, va_list ap); /* A bitmask of flags used by the dispatch logic. Note that this is a combined bit mask, that is generated from the bit * mask originally passed into json_dispatch(), the individual bitmask associated with the static JsonDispatch callout diff --git a/src/test/test-json.c b/src/test/test-json.c index d22485630a..3563d004c8 100644 --- a/src/test/test-json.c +++ b/src/test/test-json.c @@ -631,4 +631,19 @@ TEST(variant) { test_variant_one("[ 0, -0, 0.0, -0.0, 0.000, -0.000, 0e0, -0e0, 0e+0, -0e-0, 0e-0, -0e000, 0e+000 ]", test_zeroes); } +TEST(json_append) { + _cleanup_(json_variant_unrefp) JsonVariant *v = NULL, *w = NULL; + + assert_se(json_build(&v, JSON_BUILD_OBJECT( + JSON_BUILD_PAIR("b", JSON_BUILD_STRING("x")), + JSON_BUILD_PAIR("c", JSON_BUILD_CONST_STRING("y")), + JSON_BUILD_PAIR("a", JSON_BUILD_CONST_STRING("z")))) >= 0); + + assert_se(json_append(&w, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("b", JSON_BUILD_STRING("x")))) >= 0); + assert_se(json_append(&w, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("c", JSON_BUILD_STRING("y")))) >= 0); + assert_se(json_append(&w, JSON_BUILD_OBJECT(JSON_BUILD_PAIR("a", JSON_BUILD_STRING("z")))) >= 0); + + assert_se(json_variant_equal(v, w)); +} + DEFINE_TEST_MAIN(LOG_DEBUG); -- cgit v1.2.3