reformatting: cJSONUtils_GenerateMergePatch

This commit is contained in:
Max Bruckner 2016-10-29 22:15:49 +07:00
parent 01a813f642
commit c0b17dc651

View File

@ -756,34 +756,58 @@ cJSON* cJSONUtils_MergePatch(cJSON *target, cJSON *patch)
return target; return target;
} }
cJSON *cJSONUtils_GenerateMergePatch(cJSON *from,cJSON *to) cJSON *cJSONUtils_GenerateMergePatch(cJSON *from, cJSON *to)
{ {
cJSON *patch=0; cJSON *patch = 0;
if (!to) return cJSON_CreateNull(); if (!to)
if (to->type!=cJSON_Object || !from || from->type!=cJSON_Object) return cJSON_Duplicate(to,1); {
/* patch to delete everything */
return cJSON_CreateNull();
}
if ((to->type != cJSON_Object) || !from || (from->type != cJSON_Object))
{
return cJSON_Duplicate(to, 1);
}
cJSONUtils_SortObject(from); cJSONUtils_SortObject(from);
cJSONUtils_SortObject(to); cJSONUtils_SortObject(to);
from=from->child;to=to->child;
patch=cJSON_CreateObject(); from = from->child;
to = to->child;
patch = cJSON_CreateObject();
while (from || to) while (from || to)
{ {
int compare=from?(to?strcmp(from->string,to->string):-1):1; int compare = from ? (to ? strcmp(from->string, to->string) : -1) : 1;
if (compare<0) if (compare < 0)
{ {
cJSON_AddItemToObject(patch,from->string,cJSON_CreateNull()); /* from has a value that to doesn't have -> remove */
from=from->next; cJSON_AddItemToObject(patch, from->string, cJSON_CreateNull());
from = from->next;
} }
else if (compare>0) else if (compare > 0)
{ {
cJSON_AddItemToObject(patch,to->string,cJSON_Duplicate(to,1)); /* to has a value that from doesn't have -> add to patch */
to=to->next; cJSON_AddItemToObject(patch, to->string, cJSON_Duplicate(to, 1));
to = to->next;
} }
else else
{ {
if (cJSONUtils_Compare(from,to)) cJSON_AddItemToObject(patch,to->string,cJSONUtils_GenerateMergePatch(from,to)); /* object key exists in both objects */
from=from->next;to=to->next; if (cJSONUtils_Compare(from, to))
{
/* not identical --> generate a patch */
cJSON_AddItemToObject(patch, to->string, cJSONUtils_GenerateMergePatch(from, to));
}
/* next key in the object */
from = from->next;
to = to->next;
} }
} }
if (!patch->child) {cJSON_Delete(patch);return 0;} if (!patch->child)
{
cJSON_Delete(patch);
return 0;
}
return patch; return patch;
} }