]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
json: introduce json_append()
authorYu Watanabe <watanabe.yu+github@gmail.com>
Sat, 3 Sep 2022 14:10:24 +0000 (23:10 +0900)
committerYu Watanabe <watanabe.yu+github@gmail.com>
Sat, 3 Sep 2022 14:13:47 +0000 (23:13 +0900)
src/shared/json.c
src/shared/json.h
src/test/test-json.c

index f0416e66dc5d74d1c0a8573dfe1241fafe10d362..d541eb10361f362fd01694ed9c7d418b9e4ec622 100644 (file)
@@ -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,
index 98d184c3097905896e0e9a215f55b9a88941dc76..c75dfe8741946f645f65553841e226252ad68340 100644 (file)
@@ -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
index d22485630ac8b2e84c1ee67e298f467461127877..3563d004c8fa69a3e4f17437a0d56129a981f39d 100644 (file)
@@ -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);