Skip to content

Commit 0fcf401

Browse files
author
James McLaughlin
committed
Add json_object_merge function
1 parent 761e2f5 commit 0fcf401

File tree

2 files changed

+49
-10
lines changed

2 files changed

+49
-10
lines changed

json-builder.c

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,46 @@ void json_object_sort (json_value * object, json_value * proto)
346346
}
347347
}
348348

349+
json_value * json_object_merge (json_value * objectA, json_value * objectB)
350+
{
351+
assert (objectA->type == json_object);
352+
assert (objectB->type == json_object);
353+
354+
if (objectB->u.object.length <=
355+
((json_builder_value *) objectA)->additional_length_allocated)
356+
{
357+
((json_builder_value *) objectA)->additional_length_allocated
358+
-= objectB->u.object.length;
359+
}
360+
else
361+
{
362+
json_object_entry * values_new;
363+
364+
unsigned int alloc =
365+
objectA->u.object.length
366+
+ ((json_builder_value *) objectA)->additional_length_allocated
367+
+ objectB->u.object.length;
368+
369+
if (! (values_new = (json_object_entry *)
370+
realloc (objectA->u.object.values, sizeof (json_object_entry) * alloc)))
371+
{
372+
return NULL;
373+
}
374+
375+
objectA->u.object.values = values_new;
376+
}
377+
378+
memcpy (objectA->u.object.values + objectA->u.object.length,
379+
objectB->u.object.values,
380+
objectB->u.object.length * sizeof (json_object_entry));
381+
382+
objectA->u.object.length += objectB->u.object.length;
383+
384+
free (objectB);
385+
386+
return objectA;
387+
}
388+
349389
static size_t measure_string (unsigned int length,
350390
const json_char * str)
351391
{

json-builder.h

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,15 @@ json_value * json_object_push_nocopy (json_value * object,
8484
unsigned int name_length, json_char * name,
8585
json_value *);
8686

87+
/* Merges all entries from objectB into objectA and destroys objectB.
88+
*/
89+
json_value * json_object_merge (json_value * objectA, json_value * objectB);
90+
91+
/* Sort the entries of an object based on the order in a prototype object.
92+
* Helpful when reading JSON and writing it again to preserve user order.
93+
*/
94+
void json_object_sort (json_value * object, json_value * proto);
95+
8796

8897

8998
/*** Strings
@@ -101,16 +110,6 @@ json_value * json_boolean_new (int);
101110
json_value * json_null_new ();
102111

103112

104-
/*** Sorting
105-
***/
106-
107-
/* Sort the entries of an object based on the order in a prototype object.
108-
* Helpful when reading JSON and writing it again to preserve user order.
109-
*/
110-
void json_object_sort (json_value * object, json_value * proto);
111-
112-
113-
114113
/*** Serializing
115114
***/
116115
#define json_serialize_mode_multiline 0

0 commit comments

Comments
 (0)