Skip to content

Commit

Permalink
Clarify and improve k5_json_object_set
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
greghudson committed Jul 16, 2013
1 parent 57d0b4b commit ea29df4
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 4 deletions.
6 changes: 5 additions & 1 deletion src/include/k5-json.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 16 additions & 3 deletions src/util/support/json.c
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
9 changes: 9 additions & 0 deletions src/util/support/t_json.c
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit ea29df4

Please sign in to comment.