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); {
cJSONUtils_SortObject(from); /* patch to delete everything */
cJSONUtils_SortObject(to); return cJSON_CreateNull();
from=from->child;to=to->child; }
patch=cJSON_CreateObject(); if ((to->type != cJSON_Object) || !from || (from->type != cJSON_Object))
while (from || to) {
{ return cJSON_Duplicate(to, 1);
int compare=from?(to?strcmp(from->string,to->string):-1):1; }
if (compare<0)
{ cJSONUtils_SortObject(from);
cJSON_AddItemToObject(patch,from->string,cJSON_CreateNull()); cJSONUtils_SortObject(to);
from=from->next;
} from = from->child;
else if (compare>0) to = to->child;
{ patch = cJSON_CreateObject();
cJSON_AddItemToObject(patch,to->string,cJSON_Duplicate(to,1)); while (from || to)
to=to->next; {
} int compare = from ? (to ? strcmp(from->string, to->string) : -1) : 1;
else if (compare < 0)
{ {
if (cJSONUtils_Compare(from,to)) cJSON_AddItemToObject(patch,to->string,cJSONUtils_GenerateMergePatch(from,to)); /* from has a value that to doesn't have -> remove */
from=from->next;to=to->next; cJSON_AddItemToObject(patch, from->string, cJSON_CreateNull());
} from = from->next;
} }
if (!patch->child) {cJSON_Delete(patch);return 0;} else if (compare > 0)
return patch; {
/* to has a value that from doesn't have -> add to patch */
cJSON_AddItemToObject(patch, to->string, cJSON_Duplicate(to, 1));
to = to->next;
}
else
{
/* object key exists in both objects */
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;
}
return patch;
} }