]> git.ipfire.org Git - thirdparty/krb5.git/commitdiff
Clarify and improve k5_json_object_set
authorGreg Hudson <ghudson@mit.edu>
Tue, 16 Jul 2013 22:09:55 +0000 (18:09 -0400)
committerGreg Hudson <ghudson@mit.edu>
Tue, 16 Jul 2013 22:09:55 +0000 (18:09 -0400)
Document that k5_json_object_set can be used to overwrite an existing
key, and make it possible to remove a key by setting it to NULL.

src/include/k5-json.h
src/util/support/json.c
src/util/support/t_json.c

index b01b8b847eab7d1f71792b44b3040736d0fe0f85..8b22cd39d33d9fdae527dc171a3c8c5d495a9050 100644 (file)
@@ -168,7 +168,11 @@ void k5_json_object_iterate(k5_json_object obj,
 /* Return the number of mappings in an object. */
 size_t k5_json_object_count(k5_json_object obj);
 
-/* Store val into object at key, incrementing val's reference count. */
+/*
+ * Store val into object at key, incrementing val's reference count and
+ * releasing any previous value at key.  If val is NULL, key is removed from
+ * obj if it exists, and obj remains unchanged if it does not.
+ */
 int k5_json_object_set(k5_json_object obj, const char *key, k5_json_value val);
 
 /* Get an alias to the object's value for key, without incrementing the
index b2dd1333e705d7e96e4584676b78b327fb3a0072..b99fabd496640c0801e0e14754950e8716ee0ccd 100644 (file)
@@ -429,15 +429,28 @@ int
 k5_json_object_set(k5_json_object obj, const char *key, k5_json_value val)
 {
     struct entry *ent, *ptr;
-    size_t new_alloc;
+    size_t new_alloc, i;
 
     ent = object_search(obj, key);
-    if (ent) {
+    if (ent != NULL) {
         k5_json_release(ent->value);
-        ent->value = k5_json_retain(val);
+        if (val == NULL) {
+            /* Remove this key. */
+            free(ent->key);
+            for (i = ent - obj->entries; i < obj->len - 1; i++)
+                obj->entries[i] = obj->entries[i + 1];
+            obj->len--;
+        } else {
+            /* Overwrite this key's value with the new one. */
+            ent->value = k5_json_retain(val);
+        }
         return 0;
     }
 
+    /* If didn't find a key the caller asked to remove, do nothing. */
+    if (val == NULL)
+        return 0;
+
     if (obj->len >= obj->allocated) {
         /* Increase the number of slots by 50% (16 slots minimum). */
         new_alloc = obj->len + 1 + (obj->len >> 1);
index 040a85a914053774772b13a68af6df9b65a5d7a1..1f229247b496764827f4ef68568bfb731813a960 100644 (file)
@@ -165,6 +165,15 @@ test_object(void)
     if (strcmp(k5_json_string_utf8(s), "hejsan") != 0)
         err("Retrieving key2 from object failed");
 
+    check(k5_json_object_get(object, "key3") == NULL,
+          "object nonexistent key");
+
+    k5_json_object_set(object, "key1", NULL);
+    check(k5_json_object_get(object, "key1") == NULL,
+          "object removed key");
+    check(k5_json_object_get(object, "key2") != NULL,
+          "object remaining key");
+
     k5_json_release(v1);
     k5_json_release(v2);
     k5_json_release(object);