cJSON_Utils.c 26.5 KB
Newer Older
M
Max Bruckner 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*
  Copyright (c) 2009-2017 Dave Gamble and cJSON contributors

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
*/

23
#pragma GCC visibility push(default)
24
#include <ctype.h>
25 26
#include <string.h>
#include <stdlib.h>
27
#include <stdio.h>
M
Max Bruckner 已提交
28
#include <limits.h>
29
#pragma GCC visibility pop
M
Max Bruckner 已提交
30

31 32
#include "cJSON_Utils.h"

33
static unsigned char* cJSONUtils_strdup(const unsigned char* str)
34
{
M
Max Bruckner 已提交
35
    size_t len = 0;
36
    unsigned char *copy = NULL;
37

38 39
    len = strlen((const char*)str) + 1;
    if (!(copy = (unsigned char*)malloc(len)))
40
    {
41
        return NULL;
42 43 44 45 46 47
    }
    memcpy(copy, str, len);

    return copy;
}

48
static int cJSONUtils_strcasecmp(const unsigned char *s1, const unsigned char *s2)
49
{
M
Max Bruckner 已提交
50 51 52 53 54 55 56 57
    if (!s1)
    {
        return (s1 == s2) ? 0 : 1; /* both NULL? */
    }
    if (!s2)
    {
        return 1;
    }
M
Max Bruckner 已提交
58
    for(; tolower(*s1) == tolower(*s2); (void)++s1, ++s2)
M
Max Bruckner 已提交
59 60 61 62 63 64 65
    {
        if(*s1 == 0)
        {
            return 0;
        }
    }

66
    return tolower(*s1) - tolower(*s2);
67 68
}

69
/* JSON Pointer implementation: */
70
static int cJSONUtils_Pstrcasecmp(const unsigned char *a, const unsigned char *e)
71
{
72 73 74 75
    if (!a || !e)
    {
        return (a == e) ? 0 : 1; /* both NULL? */
    }
M
Max Bruckner 已提交
76
    for (; *a && *e && (*e != '/'); (void)a++, e++) /* compare until next '/' */
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
    {
        if (*e == '~')
        {
            /* check for escaped '~' (~0) and '/' (~1) */
            if (!((e[1] == '0') && (*a == '~')) && !((e[1] == '1') && (*a == '/')))
            {
                /* invalid escape sequence or wrong character in *a */
                return 1;
            }
            else
            {
                e++;
            }
        }
        else if (tolower(*a) != tolower(*e))
        {
            return 1;
        }
    }
    if (((*e != 0) && (*e != '/')) != (*a != 0))
    {
        /* one string has ended, the other not */
        return 1;
    }

    return 0;
103 104
}

105
static size_t cJSONUtils_PointerEncodedstrlen(const unsigned char *s)
106
{
107
    size_t l = 0;
M
Max Bruckner 已提交
108
    for (; *s; (void)s++, l++)
109 110 111 112 113 114 115 116 117
    {
        if ((*s == '~') || (*s == '/'))
        {
            l++;
        }
    }

    return l;
}
118

119
static void cJSONUtils_PointerEncodedstrcpy(unsigned char *d, const unsigned char *s)
120
{
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
    for (; *s; s++)
    {
        if (*s == '/')
        {
            *d++ = '~';
            *d++ = '1';
        }
        else if (*s == '~')
        {
            *d++ = '~';
            *d++ = '0';
        }
        else
        {
            *d++ = *s;
        }
    }

    *d = '\0';
140 141
}

142
CJSON_PUBLIC(char *) cJSONUtils_FindPointerFromObjectTo(cJSON *object, cJSON *target)
143
{
144
    size_t c = 0;
145
    cJSON *obj = 0;
146

147 148 149
    if (object == target)
    {
        /* found */
150
        return (char*)cJSONUtils_strdup((const unsigned char*)"");
151
    }
152

153
    /* recursively search all children of the object */
M
Max Bruckner 已提交
154
    for (obj = object->child; obj; (void)(obj = obj->next), c++)
155
    {
156
        unsigned char *found = (unsigned char*)cJSONUtils_FindPointerFromObjectTo(obj, target);
157 158
        if (found)
        {
159
            if (cJSON_IsArray(object))
160 161
            {
                /* reserve enough memory for a 64 bit integer + '/' and '\0' */
162
                unsigned char *ret = (unsigned char*)malloc(strlen((char*)found) + 23);
163 164 165 166 167 168 169 170
                /* check if conversion to unsigned long is valid
                 * This should be eliminated at compile time by dead code elimination
                 * if size_t is an alias of unsigned long, or if it is bigger */
                if (c > ULONG_MAX)
                {
                    free(found);
                    return NULL;
                }
171
                sprintf((char*)ret, "/%lu%s", (unsigned long)c, found); /* /<array_index><path> */
172 173
                free(found);

174
                return (char*)ret;
175
            }
176
            else if (cJSON_IsObject(object))
177
            {
178
                unsigned char *ret = (unsigned char*)malloc(strlen((char*)found) + cJSONUtils_PointerEncodedstrlen((unsigned char*)obj->string) + 2);
179
                *ret = '/';
180 181
                cJSONUtils_PointerEncodedstrcpy(ret + 1, (unsigned char*)obj->string);
                strcat((char*)ret, (char*)found);
182 183
                free(found);

184
                return (char*)ret;
185 186 187 188
            }

            /* reached leaf of the tree, found nothing */
            free(found);
189
            return NULL;
190 191 192 193
        }
    }

    /* not found */
194
    return NULL;
195 196
}

197
CJSON_PUBLIC(cJSON *) cJSONUtils_GetPointer(cJSON *object, const char *pointer)
198
{
199 200 201
    /* follow path of the pointer */
    while ((*pointer++ == '/') && object)
    {
202
        if (cJSON_IsArray(object))
203
        {
204
            size_t which = 0;
205 206 207
            /* parse array index */
            while ((*pointer >= '0') && (*pointer <= '9'))
            {
M
Max Bruckner 已提交
208
                which = (10 * which) + (size_t)(*pointer++ - '0');
209 210 211 212
            }
            if (*pointer && (*pointer != '/'))
            {
                /* not end of string or new path token */
213
                return NULL;
214
            }
M
Max Bruckner 已提交
215 216 217 218 219
            if (which > INT_MAX)
            {
                return NULL;
            }
            object = cJSON_GetArrayItem(object, (int)which);
220
        }
221
        else if (cJSON_IsObject(object))
222 223 224
        {
            object = object->child;
            /* GetObjectItem. */
225
            while (object && cJSONUtils_Pstrcasecmp((unsigned char*)object->string, (const unsigned char*)pointer))
226 227 228 229 230 231 232 233 234 235 236
            {
                object = object->next;
            }
            /* skip to the next path token or end of string */
            while (*pointer && (*pointer != '/'))
            {
                pointer++;
            }
        }
        else
        {
237
            return NULL;
238 239 240 241
        }
    }

    return object;
242 243
}

244
/* JSON Patch implementation. */
245
static void cJSONUtils_InplaceDecodePointerString(unsigned char *string)
246
{
247
    unsigned char *s2 = string;
248 249 250 251 252

    if (string == NULL) {
        return;
    }

M
Max Bruckner 已提交
253
    for (; *string; (void)s2++, string++)
254
    {
255
        *s2 = (unsigned char) ((*string != '~')
256 257 258
            ? (*string)
            : ((*(++string) == '0')
                    ? '~'
259
                    : '/'));
260 261 262
    }

    *s2 = '\0';
263 264
}

265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
static cJSON_bool decode_array_index_from_pointer(const unsigned char * const pointer, size_t * const index)
{
    char *end_pointer = NULL;
    long int parsed_index = strtol((const char*)pointer, &end_pointer, 10);

    if (((unsigned char*)end_pointer == pointer) || (parsed_index < 0) || (*end_pointer != '\0'))
    {
        /* array index is invalid */
        return 0;
    }

    *index = (size_t)parsed_index;

    return 1;
}

281
static cJSON *cJSONUtils_PatchDetach(cJSON *object, const unsigned char *path)
282
{
283 284
    unsigned char *parentptr = NULL;
    unsigned char *childptr = NULL;
285 286
    cJSON *parent = NULL;
    cJSON *ret = NULL;
287 288

    /* copy path and split it in parent and child */
289
    parentptr = cJSONUtils_strdup(path);
290 291 292 293
    if (parentptr == NULL) {
        return NULL;
    }

294
    childptr = (unsigned char*)strrchr((char*)parentptr, '/'); /* last '/' */
295
    if (childptr == NULL)
296
    {
297 298
        free(parentptr);
        return NULL;
299
    }
300 301 302
    /* split strings */
    *childptr++ = '\0';

303
    parent = cJSONUtils_GetPointer(object, (char*)parentptr);
304
    cJSONUtils_InplaceDecodePointerString(childptr);
305

306 307 308
    if (!parent)
    {
        /* Couldn't find object to remove child from. */
309
        ret = NULL;
310
    }
311
    else if (cJSON_IsArray(parent))
312
    {
313
        ret = cJSON_DetachItemFromArray(parent, atoi((char*)childptr));
314
    }
315
    else if (cJSON_IsObject(parent))
316
    {
317
        ret = cJSON_DetachItemFromObject(parent, (char*)childptr);
318 319
    }
    free(parentptr);
320

321 322
    /* return the detachted item */
    return ret;
323 324
}

M
Max Bruckner 已提交
325
static int cJSONUtils_Compare(cJSON *a, cJSON *b)
326
{
327
    if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF)))
M
Max Bruckner 已提交
328 329 330 331
    {
        /* mismatched type. */
        return -1;
    }
332
    switch (a->type & 0xFF)
M
Max Bruckner 已提交
333 334 335 336 337 338 339 340
    {
        case cJSON_Number:
            /* numeric mismatch. */
            return ((a->valueint != b->valueint) || (a->valuedouble != b->valuedouble)) ? -2 : 0;
        case cJSON_String:
            /* string mismatch. */
            return (strcmp(a->valuestring, b->valuestring) != 0) ? -3 : 0;
        case cJSON_Array:
M
Max Bruckner 已提交
341
            for ((void)(a = a->child), b = b->child; a && b; (void)(a = a->next), b = b->next)
M
Max Bruckner 已提交
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
            {
                int err = cJSONUtils_Compare(a, b);
                if (err)
                {
                    return err;
                }
            }
            /* array size mismatch? (one of both children is not NULL) */
            return (a || b) ? -4 : 0;
        case cJSON_Object:
            cJSONUtils_SortObject(a);
            cJSONUtils_SortObject(b);
            a = a->child;
            b = b->child;
            while (a && b)
            {
M
Max Bruckner 已提交
358
                int err = 0;
M
Max Bruckner 已提交
359
                /* compare object keys */
360
                if (cJSONUtils_strcasecmp((unsigned char*)a->string, (unsigned char*)b->string))
M
Max Bruckner 已提交
361 362 363 364 365 366 367 368 369 370 371 372 373 374
                {
                    /* missing member */
                    return -6;
                }
                err = cJSONUtils_Compare(a, b);
                if (err)
                {
                    return err;
                }
                a = a->next;
                b = b->next;
            }
            /* object length mismatch (one of both children is not null) */
            return (a || b) ? -5 : 0;
375

M
Max Bruckner 已提交
376 377 378 379 380
        default:
            break;
    }
    /* null, true or false */
    return 0;
381 382
}

383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
/* non broken version of cJSON_InsertItemInArray */
static cJSON_bool insert_item_in_array(cJSON *array, size_t which, cJSON *newitem)
{
    cJSON *child = array->child;
    while (child && (which > 0))
    {
        child = child->next;
        which--;
    }
    if (which > 0)
    {
        /* item is after the end of the array */
        return 0;
    }
    if (child == NULL)
    {
        cJSON_AddItemToArray(array, newitem);
        return 1;
    }

    /* insert into the linked list */
    newitem->next = child;
    newitem->prev = child->prev;
    child->prev = newitem;

    /* was it at the beginning */
    if (child == array->child)
    {
        array->child = newitem;
    }
    else
    {
        newitem->prev->next = newitem;
    }

    return 1;
}

M
Max Bruckner 已提交
421
static int cJSONUtils_ApplyPatch(cJSON *object, cJSON *patch)
422
{
423 424 425 426
    cJSON *op = NULL;
    cJSON *path = NULL;
    cJSON *value = NULL;
    cJSON *parent = NULL;
M
Max Bruckner 已提交
427
    int opcode = 0;
428 429
    unsigned char *parentptr = NULL;
    unsigned char *childptr = NULL;
430

M
Max Bruckner 已提交
431 432 433 434 435 436 437
    op = cJSON_GetObjectItem(patch, "op");
    path = cJSON_GetObjectItem(patch, "path");
    if (!op || !path)
    {
        /* malformed patch. */
        return 2;
    }
438

M
Max Bruckner 已提交
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
    /* decode operation */
    if (!strcmp(op->valuestring, "add"))
    {
        opcode = 0;
    }
    else if (!strcmp(op->valuestring, "remove"))
    {
        opcode = 1;
    }
    else if (!strcmp(op->valuestring, "replace"))
    {
        opcode = 2;
    }
    else if (!strcmp(op->valuestring, "move"))
    {
        opcode = 3;
    }
    else if (!strcmp(op->valuestring, "copy"))
    {
        opcode = 4;
    }
    else if (!strcmp(op->valuestring, "test"))
    {
        /* compare value: {...} with the given path */
        return cJSONUtils_Compare(cJSONUtils_GetPointer(object, path->valuestring), cJSON_GetObjectItem(patch, "value"));
    }
    else
    {
        /* unknown opcode. */
        return 3;
    }
470

M
Max Bruckner 已提交
471 472 473 474
    /* Remove/Replace */
    if ((opcode == 1) || (opcode == 2))
    {
        /* Get rid of old. */
475 476 477 478 479 480
        cJSON *old_item = cJSONUtils_PatchDetach(object, (unsigned char*)path->valuestring);
        if (old_item == NULL)
        {
            return 13;
        }
        cJSON_Delete(old_item);
M
Max Bruckner 已提交
481 482
        if (opcode == 1)
        {
483
            /* For Remove, this job is done. */
M
Max Bruckner 已提交
484 485 486
            return 0;
        }
    }
487

M
Max Bruckner 已提交
488 489 490 491 492 493 494 495 496
    /* Copy/Move uses "from". */
    if ((opcode == 3) || (opcode == 4))
    {
        cJSON *from = cJSON_GetObjectItem(patch, "from");
        if (!from)
        {
            /* missing "from" for copy/move. */
            return 4;
        }
497

M
Max Bruckner 已提交
498 499 500
        if (opcode == 3)
        {
            /* move */
501
            value = cJSONUtils_PatchDetach(object, (unsigned char*)from->valuestring);
M
Max Bruckner 已提交
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
        }
        if (opcode == 4)
        {
            /* copy */
            value = cJSONUtils_GetPointer(object, from->valuestring);
        }
        if (!value)
        {
            /* missing "from" for copy/move. */
            return 5;
        }
        if (opcode == 4)
        {
            value = cJSON_Duplicate(value, 1);
        }
        if (!value)
        {
            /* out of memory for copy/move. */
            return 6;
        }
    }
    else /* Add/Replace uses "value". */
    {
        value = cJSON_GetObjectItem(patch, "value");
        if (!value)
        {
            /* missing "value" for add/replace. */
            return 7;
        }
        value = cJSON_Duplicate(value, 1);
        if (!value)
        {
            /* out of memory for add/replace. */
            return 8;
        }
    }
538

M
Max Bruckner 已提交
539
    /* Now, just add "value" to "path". */
540

M
Max Bruckner 已提交
541
    /* split pointer in parent and child */
542 543
    parentptr = cJSONUtils_strdup((unsigned char*)path->valuestring);
    childptr = (unsigned char*)strrchr((char*)parentptr, '/');
M
Max Bruckner 已提交
544 545 546 547
    if (childptr)
    {
        *childptr++ = '\0';
    }
548
    parent = cJSONUtils_GetPointer(object, (char*)parentptr);
M
Max Bruckner 已提交
549
    cJSONUtils_InplaceDecodePointerString(childptr);
550

M
Max Bruckner 已提交
551
    /* add, remove, replace, move, copy, test. */
552
    if ((parent == NULL) || (childptr == NULL))
M
Max Bruckner 已提交
553 554 555 556 557 558
    {
        /* Couldn't find object to add to. */
        free(parentptr);
        cJSON_Delete(value);
        return 9;
    }
559
    else if (cJSON_IsArray(parent))
M
Max Bruckner 已提交
560
    {
561
        if (!strcmp((char*)childptr, "-"))
M
Max Bruckner 已提交
562 563 564 565 566
        {
            cJSON_AddItemToArray(parent, value);
        }
        else
        {
567 568
            size_t index = 0;
            if (!decode_array_index_from_pointer(childptr, &index))
569 570 571 572 573 574
            {
                free(parentptr);
                cJSON_Delete(value);
                return 11;
            }

575
            if (!insert_item_in_array(parent, index, value))
576 577 578 579 580
            {
                free(parentptr);
                cJSON_Delete(value);
                return 10;
            }
M
Max Bruckner 已提交
581 582
        }
    }
583
    else if (cJSON_IsObject(parent))
M
Max Bruckner 已提交
584
    {
585 586
        cJSON_DeleteItemFromObject(parent, (char*)childptr);
        cJSON_AddItemToObject(parent, (char*)childptr, value);
M
Max Bruckner 已提交
587 588 589 590 591 592 593 594 595
    }
    else
    {
        cJSON_Delete(value);
    }
    free(parentptr);

    return 0;
}
596

597
CJSON_PUBLIC(int) cJSONUtils_ApplyPatches(cJSON *object, cJSON *patches)
598
{
M
Max Bruckner 已提交
599
    int err = 0;
600

601
    if (!cJSON_IsArray(patches))
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
    {
        /* malformed patches. */
        return 1;
    }
    if (patches)
    {
        patches = patches->child;
    }
    while (patches)
    {
        if ((err = cJSONUtils_ApplyPatch(object, patches)))
        {
            return err;
        }
        patches = patches->next;
    }

    return 0;
620
}
621

622
static void cJSONUtils_GeneratePatch(cJSON *patches, const unsigned char *op, const unsigned char *path, const unsigned char *suffix, cJSON *val)
623
{
624
    cJSON *patch = cJSON_CreateObject();
625
    cJSON_AddItemToObject(patch, "op", cJSON_CreateString((const char*)op));
626 627
    if (suffix)
    {
628 629 630
        unsigned char *newpath = (unsigned char*)malloc(strlen((const char*)path) + cJSONUtils_PointerEncodedstrlen(suffix) + 2);
        cJSONUtils_PointerEncodedstrcpy(newpath + sprintf((char*)newpath, "%s/", (const char*)path), suffix);
        cJSON_AddItemToObject(patch, "path", cJSON_CreateString((const char*)newpath));
631 632 633 634
        free(newpath);
    }
    else
    {
635
        cJSON_AddItemToObject(patch, "path", cJSON_CreateString((const char*)path));
636 637 638 639 640 641
    }
    if (val)
    {
        cJSON_AddItemToObject(patch, "value", cJSON_Duplicate(val, 1));
    }
    cJSON_AddItemToArray(patches, patch);
642 643
}

644
CJSON_PUBLIC(void) cJSONUtils_AddPatchToArray(cJSON *array, const char *op, const char *path, cJSON *val)
M
Max Bruckner 已提交
645
{
646
    cJSONUtils_GeneratePatch(array, (const unsigned char*)op, (const unsigned char*)path, 0, val);
M
Max Bruckner 已提交
647
}
648

649
static void cJSONUtils_CompareToPatch(cJSON *patches, const unsigned char *path, cJSON *from, cJSON *to)
650
{
651 652 653 654 655
    if ((from == NULL) || (to == NULL))
    {
        return;
    }

656
    if ((from->type & 0xFF) != (to->type & 0xFF))
657
    {
658
        cJSONUtils_GeneratePatch(patches, (const unsigned char*)"replace", path, 0, to);
659 660 661
        return;
    }

662
    switch ((from->type & 0xFF))
663 664 665 666
    {
        case cJSON_Number:
            if ((from->valueint != to->valueint) || (from->valuedouble != to->valuedouble))
            {
667
                cJSONUtils_GeneratePatch(patches, (const unsigned char*)"replace", path, 0, to);
668 669 670 671 672 673
            }
            return;

        case cJSON_String:
            if (strcmp(from->valuestring, to->valuestring) != 0)
            {
674
                cJSONUtils_GeneratePatch(patches, (const unsigned char*)"replace", path, 0, to);
675 676
            }
            return;
677

678 679
        case cJSON_Array:
        {
680
            size_t c = 0;
681
            unsigned char *newpath = (unsigned char*)malloc(strlen((const char*)path) + 23); /* Allow space for 64bit int. */
682
            /* generate patches for all array elements that exist in "from" and "to" */
M
Max Bruckner 已提交
683
            for ((void)(c = 0), (void)(from = from->child), to = to->child; from && to; (void)(from = from->next), (void)(to = to->next), c++)
684
            {
685 686 687 688 689 690 691 692
                /* check if conversion to unsigned long is valid
                 * This should be eliminated at compile time by dead code elimination
                 * if size_t is an alias of unsigned long, or if it is bigger */
                if (c > ULONG_MAX)
                {
                    free(newpath);
                    return;
                }
693
                sprintf((char*)newpath, "%s/%lu", path, (unsigned long)c); /* path of the current array element */
694 695 696
                cJSONUtils_CompareToPatch(patches, newpath, from, to);
            }
            /* remove leftover elements from 'from' that are not in 'to' */
M
Max Bruckner 已提交
697
            for (; from; (void)(from = from->next), c++)
698
            {
699 700 701 702 703 704 705 706
                /* check if conversion to unsigned long is valid
                 * This should be eliminated at compile time by dead code elimination
                 * if size_t is an alias of unsigned long, or if it is bigger */
                if (c > ULONG_MAX)
                {
                    free(newpath);
                    return;
                }
707
                sprintf((char*)newpath, "%lu", (unsigned long)c);
708
                cJSONUtils_GeneratePatch(patches, (const unsigned char*)"remove", path, newpath, 0);
709 710
            }
            /* add new elements in 'to' that were not in 'from' */
M
Max Bruckner 已提交
711
            for (; to; (void)(to = to->next), c++)
712
            {
713
                cJSONUtils_GeneratePatch(patches, (const unsigned char*)"add", path, (const unsigned char*)"-", to);
714 715 716 717 718 719 720
            }
            free(newpath);
            return;
        }

        case cJSON_Object:
        {
M
Max Bruckner 已提交
721 722
            cJSON *a = NULL;
            cJSON *b = NULL;
723 724 725 726 727 728 729 730
            cJSONUtils_SortObject(from);
            cJSONUtils_SortObject(to);

            a = from->child;
            b = to->child;
            /* for all object values in the object with more of them */
            while (a || b)
            {
731
                int diff = (!a) ? 1 : ((!b) ? -1 : cJSONUtils_strcasecmp((unsigned char*)a->string, (unsigned char*)b->string));
732 733 734
                if (!diff)
                {
                    /* both object keys are the same */
735 736
                    unsigned char *newpath = (unsigned char*)malloc(strlen((const char*)path) + cJSONUtils_PointerEncodedstrlen((unsigned char*)a->string) + 2);
                    cJSONUtils_PointerEncodedstrcpy(newpath + sprintf((char*)newpath, "%s/", path), (unsigned char*)a->string);
737 738 739 740 741 742 743 744 745
                    /* create a patch for the element */
                    cJSONUtils_CompareToPatch(patches, newpath, a, b);
                    free(newpath);
                    a = a->next;
                    b = b->next;
                }
                else if (diff < 0)
                {
                    /* object element doesn't exist in 'to' --> remove it */
746
                    cJSONUtils_GeneratePatch(patches, (const unsigned char*)"remove", path, (unsigned char*)a->string, 0);
747 748 749 750 751
                    a = a->next;
                }
                else
                {
                    /* object element doesn't exist in 'from' --> add it */
752
                    cJSONUtils_GeneratePatch(patches, (const unsigned char*)"add", path, (unsigned char*)b->string, b);
753 754 755 756 757 758 759 760 761 762
                    b = b->next;
                }
            }
            return;
        }

        default:
            break;
    }
}
763

764
CJSON_PUBLIC(cJSON *) cJSONUtils_GeneratePatches(cJSON *from, cJSON *to)
765
{
766
    cJSON *patches = cJSON_CreateArray();
767
    cJSONUtils_CompareToPatch(patches, (const unsigned char*)"", from, to);
768

769 770
    return patches;
}
771

M
Max Bruckner 已提交
772
/* sort lists using mergesort */
773 774
static cJSON *cJSONUtils_SortList(cJSON *list)
{
M
Max Bruckner 已提交
775 776 777
    cJSON *first = list;
    cJSON *second = list;
    cJSON *ptr = list;
778

M
Max Bruckner 已提交
779 780 781 782 783
    if (!list || !list->next)
    {
        /* One entry is sorted already. */
        return list;
    }
784

785
    while (ptr && ptr->next && (cJSONUtils_strcasecmp((unsigned char*)ptr->string, (unsigned char*)ptr->next->string) < 0))
M
Max Bruckner 已提交
786 787 788 789 790 791 792 793 794
    {
        /* Test for list sorted. */
        ptr = ptr->next;
    }
    if (!ptr || !ptr->next)
    {
        /* Leave sorted lists unmodified. */
        return list;
    }
795

M
Max Bruckner 已提交
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
    /* reset ptr to the beginning */
    ptr = list;
    while (ptr)
    {
        /* Walk two pointers to find the middle. */
        second = second->next;
        ptr = ptr->next;
        /* advances ptr two steps at a time */
        if (ptr)
        {
            ptr = ptr->next;
        }
    }
    if (second && second->prev)
    {
        /* Split the lists */
812
        second->prev->next = NULL;
M
Max Bruckner 已提交
813
    }
814

M
Max Bruckner 已提交
815 816 817
    /* Recursively sort the sub-lists. */
    first = cJSONUtils_SortList(first);
    second = cJSONUtils_SortList(second);
818
    list = ptr = NULL;
M
Max Bruckner 已提交
819 820 821

    while (first && second) /* Merge the sub-lists */
    {
822
        if (cJSONUtils_strcasecmp((unsigned char*)first->string, (unsigned char*)second->string) < 0)
M
Max Bruckner 已提交
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
        {
            if (!list)
            {
                /* start merged list with the first element of the first list */
                list = ptr = first;
            }
            else
            {
                /* add first element of first list to merged list */
                ptr->next = first;
                first->prev = ptr;
                ptr = first;
            }
            first = first->next;
        }
        else
        {
            if (!list)
            {
                /* start merged list with the first element of the second list */
                list = ptr = second;
            }
            else
            {
                /* add first element of second list to merged list */
                ptr->next = second;
                second->prev = ptr;
                ptr = second;
            }
            second = second->next;
        }
    }
    if (first)
    {
        /* Append rest of first list. */
        if (!list)
        {
            return first;
        }
        ptr->next = first;
        first->prev = ptr;
    }
    if (second)
    {
        /* Append rest of second list */
        if (!list)
        {
            return second;
        }
        ptr->next = second;
        second->prev = ptr;
    }

    return list;
877 878
}

879
CJSON_PUBLIC(void) cJSONUtils_SortObject(cJSON *object)
M
Max Bruckner 已提交
880 881 882
{
    object->child = cJSONUtils_SortList(object->child);
}
883

884
CJSON_PUBLIC(cJSON *) cJSONUtils_MergePatch(cJSON *target, cJSON *patch)
885
{
886
    if (!cJSON_IsObject(patch))
M
Max Bruckner 已提交
887 888 889 890 891
    {
        /* scalar value, array or NULL, just duplicate */
        cJSON_Delete(target);
        return cJSON_Duplicate(patch, 1);
    }
892

893
    if (!cJSON_IsObject(target))
M
Max Bruckner 已提交
894 895 896 897 898 899 900 901
    {
        cJSON_Delete(target);
        target = cJSON_CreateObject();
    }

    patch = patch->child;
    while (patch)
    {
902
        if (cJSON_IsNull(patch))
M
Max Bruckner 已提交
903 904 905 906 907 908 909 910 911 912 913 914
        {
            /* NULL is the indicator to remove a value, see RFC7396 */
            cJSON_DeleteItemFromObject(target, patch->string);
        }
        else
        {
            cJSON *replaceme = cJSON_DetachItemFromObject(target, patch->string);
            cJSON_AddItemToObject(target, patch->string, cJSONUtils_MergePatch(replaceme, patch));
        }
        patch = patch->next;
    }
    return target;
915
}
916

917
CJSON_PUBLIC(cJSON *) cJSONUtils_GenerateMergePatch(cJSON *from, cJSON *to)
918
{
919
    cJSON *patch = NULL;
920 921 922 923 924
    if (!to)
    {
        /* patch to delete everything */
        return cJSON_CreateNull();
    }
925
    if (!cJSON_IsObject(to) || !cJSON_IsObject(from))
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
    {
        return cJSON_Duplicate(to, 1);
    }

    cJSONUtils_SortObject(from);
    cJSONUtils_SortObject(to);

    from = from->child;
    to = to->child;
    patch = cJSON_CreateObject();
    while (from || to)
    {
        int compare = from ? (to ? strcmp(from->string, to->string) : -1) : 1;
        if (compare < 0)
        {
            /* from has a value that to doesn't have -> remove */
            cJSON_AddItemToObject(patch, from->string, cJSON_CreateNull());
            from = from->next;
        }
        else if (compare > 0)
        {
            /* 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);
967
        return NULL;
968 969 970
    }

    return patch;
M
Max Bruckner 已提交
971
}